0% found this document useful (0 votes)
31 views

JAVA Merged MN

Uploaded by

shaheena.atas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

JAVA Merged MN

Uploaded by

shaheena.atas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

Introduction to java

Java is a class based high level object oriented programming language


developed by James Gosling in 1995.

Currently 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
 And much, much more!

Features of Java

 Object Oriented − In Java, everything is an Object. Java can be easily


extended since it is based on the Object model.
 Platform Independent − Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral
object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler in
Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design
feature allows the developers to construct interactive applications that can
run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
 High Performance − With the use of Just-In-Time compilers, Java
enables high performance.
 Distributed − Java is designed for the distributed environment of the
internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it
is designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
First Java Program
Let us look at a simple code that will print the words Hello World.

/* This is my first java program.


* This will print 'Hello World' as the output
*/
public class myFirstJavaClass {
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}

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

Java JVM, JRE, JDK

 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).

Java is a platform-independent language. It's because when you write


Java code, it's ultimately written for JVM but not your physical machine
(computer). Since JVM executes the Java bytecode which is platform-
independent, Java is platform-independent.

Working of Java Program

 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.

JRE is the superset of JVM.


Java Programming

Java Runtime Environment

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.

In addition to JRE, JDK also contains a number of development tools


(compilers, JavaDoc, Java Debugger, etc).

Java Development Kit


Java Programming

Java Input & Output

Java Input

Java provides different ways to get input from the user.


However, in this tutorial, you will learn to get input from user using the
object of Scanner class.
In order to use the object of Scanner, we need to import
java.util.Scanner package.

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.

// create an object of Scanner


Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

Example: Get Integer Input From the User

import java.util.Scanner;

class Input {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);


Java Programming

System.out.print("Enter an integer: ");


int number = input.nextInt();
System.out.println("You entered " + number);

}
}

Output:

Enter an integer: 23
You entered 23

In the above example, we have created an object named input of

the Scanner class. We then call the nextInt() method of

the Scanner class to get an integer input from the user.

Similarly, we can use nextLong(), nextFloat(), nextDouble(),


and next() methods to get long, float, double, and string input
respectively from the user.

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

Let's take an example to output a line.

class Topperworld {
public static void main(String[] args) {

System.out.println("Java programming is interesting.");


}
}

Output:

Java programming is interesting.

Here, we have used the println() method to display the string.

Difference between println(), print().

 print() - It prints string inside the quotes.



 println() - It prints string inside the quotes similar

like print() method. Then the cursor moves to the beginning of the
next line.

Example: print() and println()

class Output {
public static void main(String[] args) {

System.out.println("1. println ");


System.out.println("2. println ");

System.out.print("1. print ");


System.out.print("2. print");
}
}

Output:

1. println
2. println
1. print 2. print
Java Programming

Keywords in Java

Keywords are predefined, reserved words used in Java


programming that have special meanings to the compiler.

For example:

int score;

Here, int is a keyword. It indicates that the variable score is of integer


type (32-bit signed two's complement integer).
You cannot use keywords like int, for, class, etc as variable name (or
identifiers) as they are part of the Java programming language syntax.

Java has a total of 50 keywords, which are used to define the


syntax and structure of Java programming language.

Here's the complete list of all keywords in Java programming.

 abstract: used to declare a class or method as abstract. An

abstract class is a class that cannot be instantiated, and an

abstract method is a method without a body that must be

implemented in a subclass.

 assert: used to perform assertion testing in Java. An assertion is

a statement that should always be true, and if it is false, then

an AssertionError is thrown.
Java Programming

 boolean: used to declare a boolean variable, which can only

have two values: true or false.

 break: used to break out of a loop or switch statement.

 byte: used to declare a byte variable, which is a data type that

can store values from -128 to 127.

 case: used in a switch statement to define a case label.

 catch: used to catch and handle exceptions in Java.

 char: used to declare a char variable, which is a data type that

can store a single character.

 class: used to declare a class in Java.

 const: a keyword that was reserved but never implemented in

Java.

 continue: used to skip the current iteration of a loop and

continue to the next iteration.

 default: used in a switch statement to define a default case.

 do: used to start a do-while loop.

 double: used to declare a double variable, which is a data type

that can store decimal values.

 else: used in an if statement to define an alternative block of

code to execute if the condition is false.

 enum: used to declare an enumeration, which is a type that

consists of a set of named constants.


Java Programming

 extends: used to extend a class in Java.

 final: used to declare a variable or method as final, which means

that its value or implementation cannot be changed.

 finally: used in a try-catch block to define a block of code that

will always be executed, regardless of whether an exception is

thrown or not.

 float: used to declare a float variable, which is a data type that

can store decimal values with less precision than double.

 for: used to start a for loop.

 goto: a keyword that was reserved but never implemented in

Java.

 if: used to define a conditional statement in Java.

 implements: used to implement an interface in Java.

 import: used to import a package or class into a Java program.

 instanceof: used to check if an object is an instance of a

particular class or interface.

 int: used to declare an int variable, which is a data type that can

store whole numbers.

 interface: used to declare an interface in Java.

 long: used to declare a long variable, which is a data type that

can store larger whole numbers than int.


Java Programming

 native: used to declare a method as native, which means that its

implementation is provided by the underlying platform, rather

than in Java code.

 new: used to create a new object in Java.

 package: used to define a package in Java.

 private: used to declare a variable or method as private, which

means that it can only be accessed within the same class.

 protected: used to declare a variable or method as protected,

which means that it can be accessed within the same class or any

subclass.

 public: used to declare a variable or method as public, which

means that it can be accessed from anywhere in the Java

program.

 return: used to return a value from a method or exit a method

without returning a value.

 short: used to declare a short variable, which is a data type that

can store smaller whole numbers than int.

 static: used to declare a variable or method as static, which

means that it belongs to the class rather than to individual

objects of the class.

 strictfp: used to enforce strict floating-point precision in Java.

 super: used to call a method or constructor in the superclass.


Java Programming

 switch: used to start a switch statement in Java.

 synchronized: used to ensure that only one thread can access a

block of code or object at a time in Java.

 this: used to refer to the current object in Java.

 throw: used to throw an exception in Java.

 throws: used to declare that a method may throw an exception

in Java.

 transient: used to declare a variable as transient, which means

that it will not be serialized when the object is written to a file or

transmitted over a network.

 try: used to start a try-catch block in Java.

 void: used to declare a method that does not return a value.

 volatile: used to declare a variable as volatile, which means that

it is subject to optimization by the Java Virtual Machine.

Rules to follow for keywords:

 Keywords cannot be used as an identifier for class, subclass, variables, and


methods.
 Keywords are case-sensitive.
Java Programming

Keywords in the Java programming

abstract assert boolean break byte

case catch char class const*

continue default do double else

enum extends final finally float

for goto* if implements import

instanceof int interface long native

new package private protected public

return short static strictfp super

switch synchronized this throw Throws

transient try void volatile while


Java Programming

Data Types 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.

Java has two categories in which data types are segregated:

 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

-> Primitive Data Types

1. boolean type

 The boolean data type has two possible values, either true or false.

 Default value: false.


 They are usually used for true/false conditions.

Example : Java boolean data type

class Main {
public static void main(String[] args) {

boolean flag = true;


System.out.println(flag); // prints true
}
}

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

Example : Java byte data type

class Main {
public static void main(String[] args) {

byte range;
Java Programming

range = 124;
System.out.println(range); // prints 124
}
}

3. short type

 The short data type in Java can have values from -


32768 to 32767 (16-bit signed two's complement integer).
 If it's certain that the value of a variable will be within -32768 and
32767, then it is used instead of other integer data types ( int, long).
 Default value: 0

Example : Java short data 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

Example : Java int data type

class Main {
public static void main(String[] args) {

int range = -4250000;


System.out.println(range); // print -4250000
}
}

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

Example : Java long data type

class LongExample {
public static void main(String[] args) {

long range = -42332200000L;


System.out.println(range); // prints -42332200000
Java Programming

}
}

Notice, the use of L at the end of -42332200000. This represents that it's an

integer of the long type.

6. double type

 The double data type is a double-precision 64-bit floating-point.


 It should never be used for precise values such as currency.

 Default value: 0.0 (0.0d)

Example: Java double data type

class Main {
public static void main(String[] args) {

double number = -42.3;


System.out.println(number); // prints -42.3
}
}

7. float type

 The float data type is a single-precision 32-bit floating-point.


 It should never be used for precise values such as currency.

 Default value: 0.0 (0.0f)


Java Programming

Example : Java float data type

class Main {
public static void main(String[] args) {

float number = -42.3f;


System.out.println(number); // prints -42.3
}
}

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

 It's a 16-bit Unicode character.

 The minimum value of the char data type is '\u0000' (0) and the

maximum value of the is '\uffff'.


 Default value: '\u0000'

Example: Java char data type

class Main {
public static void main(String[] args) {

char letter = '\u0051';


System.out.println(letter); // prints Q
}
}
Here, the Unicode value of Q is \u0051. Hence, we get Q as the output.
Java Programming

Here is another example:

class Main {
public static void main(String[] args) {

char letter1 = '9';


System.out.println(letter1); // prints 9

char letter2 = 65;


System.out.println(letter2); // prints A

}
}

Here, we have assigned 9 as a character (specified by single quotes) to


the letter1 variable. However, the letter2 variable is assigned 65 as an
integer number (no single quotes).
Hence, A is printed to the output. It is because Java treats characters as an

integer and the ASCII value of A is 65.


Java Programming

 Non-Primitive Data Types

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,

String myString = "Java Programming";

Here, myString is an object of the String class.

Example: Create a String in Java


class Main {
public static void main(String[] args) {

// 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

 Conditional Statement is also Known as Decision-Making


Statement.
 Conditional Statement decides which statement to execute and
when.
 Java provides the facility to make decisions using selection
statements.
 They evaluate the decision based on provided conditions and
proceed with the flow of the program in a certain direction.

Java provides two types of conditional statements :

 if Statement

 switch Statement

 Java-if Statement :

The java if-Statement is used to test the condition.It check boolean condition:
true or false.

There are varios types of if-Statement in java.

 If statement
 If-else statement
 If-else-if ladder
 Nested if statement
Java Programming

1. Java if Statement

The syntax of an if-then statement is:

if (condition) {
// statements
}

Here, condition is a boolean expression such as age >= 18.


 if condition evaluates to true, statements are executed

 if condition evaluates to false, statements are skipped

Working of if Statement

Working of Java if statement


Java Programming

Example 1: Java if Statement

class IfStatement {
public static void main(String[] args) {

int number = 10;

// checks if number is less than 0


if (number < 0) {
System.out.println("The number is negative.");
}

System.out.println("Statement outside if block");


}
}

Output

Statement outside if block

In the program, number < 0 is false. Hence, the code inside the body of
the if statement is skipped.

2. Java if...else (if-then-else) Statement


The if statement executes a certain section of code if the test expression is

evaluated to true. However, if the test expression is evaluated to false, it


does nothing.
In this case, we can use an optional else block. Statements inside the body

of else block are executed if the test expression is evaluated to false. This is
known as the if-...else statement in Java.

The syntax of the if...else statement is:

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.

Working of if...else statement

Example 2: Java if...else Statement

class Main {
public static void main(String[] args) {
int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// execute this block


// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}

System.out.println("Statement outside if...else block");


Java Programming

}
}

Output

The number is positive.


Statement outside if...else block

In the above example, we have a variable named number. Here, the test

expression number > 0 checks if number is greater than 0.

Since the value of the number is 10, the test expression evaluates to true.

Hence code inside the body of if is executed.


Now, change the value of the number to a negative integer. Let's say -5.

int number = -5;

If we run the program with the new value of number, the output will be:

The number is not positive.


Statement outside if...else block

Here, the value of number is -5. So the test expression evaluates to false.

Hence code inside the body of else is executed.

3. Java if...else...if Statement

In Java, we have an if...else...if ladder, that can be used to execute one


block of code among multiple other blocks.
Java Programming

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.

Working of if...else...if ladder


Java Programming

Example 3: Java if...else...if Statement

class Main {
public static void main(String[] args) {

int number = 0;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}

// if both condition is false


else {
System.out.println("The number is 0.");
}
}
}

Output

The number is 0.

In the above example, we are checking


whether number is positive, negative, or zero. Here, we have two
condition expressions:
 number > 0 - checks if number is greater than 0

 number < 0 - checks if number is less than 0

Here, the value of number is 0. So both the conditions evaluate to false.

Hence the statement inside the body of else is executed.


Java Programming

4. Java Nested if..else Statement

In Java, it is also possible to use if..else statements inside


an if...else statement. It's called the nested if...else statement.
Here's a program to find the largest of 3 numbers using the
nested if...else statement.

Example 4: Nested if...else Statement

class Main {
public static void main(String[] args) {

// declaring double type variables


Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largest;

// checks if n1 is greater than or equal to n2


if (n1 >= n2) {

// if...else statement inside the if block


// checks if n1 is greater than or equal to n3
if (n1 >= n3) {
largest = n1;
}

else {
largest = n3;
}
} else {

// if..else statement inside else block


// checks if n2 is greater than or equal to n3
if (n2 >= n3) {
largest = n2;
}

else {
largest = n3;
}
}

System.out.println("Largest Number: " + largest);


}
}
Java Programming

Output:

Largest Number: 4.5

In the above programs, we have assigned the value of variables ourselves to


make this easier.

 Switch Statement :

The Switch statement allows us to execute a block of code among many


alternatives.

The syntax of the switch statement in Java is:

switch (expression) {

case value1:
// code
break;

case value2:
// code
break;

...
...

default:
// default statements
}
Java Programming

Working of switch case statement


The expression is evaluated once and compared with the values of each
case.
 If expression matches with value1, the code of case value1 are

executed. Similarly, the code of case value2 is executed

if expression matches with value2.


 If there is no match, the code of the default case is executed.

Example: Java switch Statement

// Java Program to check the size


// using the switch...case statement

class Main {
public static void main(String[] args) {

int number = 44;


String size;

// switch statement to check size


switch (number) {

case 29:
size = "Small";
break;

case 42:
size = "Medium";
break;

// match the value of week


case 44:
size = "Large";
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;

Here, the size variable is assigned with the value Large.


Java Programming

Looping Statement

A "looping statement" is a programming instruction that lets you


execute a block of code repeatedly as long as a certain condition is met.

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 :

Java for loop is used to run a block of code for a

certain number of times. The syntax of for loop is:

for (initialization; condition; increment/Decrement) {


// body of the loop
}
Java Programming

Here,

1. The initialization initializes and/or declares variables and executes


only once.
2. The condition is evaluated. If the condition is true, the body of

the for loop is executed.


3. The increment/Decrement updates the value
of initialExpression.
4. The condition is evaluated again. The process continues until
the condition is false.

Flowchart of Java for loop


Java Programming

Example : Display a Text Five Times

// Program to print a text 5 times

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.

The syntax of the Java for-each loop is:

for(dataType item : array) {


...
}
Java Programming

Here,

 array - an array or a collection


 item - each item of array/collection is assigned to this variable
 dataType - the data type of the array/collection

Example : Print Array Elements


// print array elements

class Main {
public static void main(String[] args) {

// create an array
int[] numbers = {31, 9, 5, -15};

// for each loop


for (int number: numbers) {
System.out.println(number);
}
}
}

Output

31
9
5
-15

Here, we have used the for-each loop to print each element of


the numbers array one by one.

 In the first iteration, element will be 31.



 In the second iteration, element will be 9.

 In the third iteration, element will be 5.

 In the fourth iteration, element will be -15.
Java Programming

 While Loop :

Java while loop is used to run a specific code


until a certain condition is met. The syntax of the while loop is:

while (condition) {
// body of loop
}

Here,

1. A while loop evaluates the condition inside the parenthesis ().


2. If the condition evaluates to true, the code inside the while loop is
executed.
3. The condition is evaluated again.
4. This process continues until the condition is false.

5. When the condition evaluates to false, the loop stops.

Flowchart of while loop


Java Programming

Example : Display Numbers from 1 to 5

// Program to display numbers from 1 to 5

class Main {
public static void main(String[] args) {

// declare variables
int i = 1, n = 5;

// while loop from 1 to 5


while(i <= n) {
System.out.println(i);
i++;
}
}
}

Output

1
2
3
4
5

 Do…While loop :

The do…while loop is similar to while loop.


However, the body of do…while loop is executed once before the test
expression is checked.
The syntax of the do…while loop is:

do {
// body of loop
} while(condition);
Java Programming

Here,

1. The body of the loop is executed at first. Then the condition is


evaluated.
2. If the condition evaluates to true, the body of the loop inside

the do statement is executed again.


3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop inside

the do statement is executed again.

5. This process continues until the condition evaluates to false. Then


the loop stops.

Flowchart of Java do while loop


Java Programming

Example : Display Numbers from 1 to 5


// Java Program to display numbers from 1 to 5

import java.util.Scanner;

// Program to find the sum of natural numbers from 1 to 100.

class Main {
public static void main(String[] args) {

int i = 1, n = 5;

// do...while loop from 1 to 5


do {
System.out.println(i);
i++;
} while(i <= n);
}
}

Output

1
2
3
4
5
Java Programming

Jumping Statement

Jumping statements are control statements that move program


execution from one location to another.

Jump statements are used to shift program control unconditionally from


one location to another within the program. Jump statements are typically
used to forcefully end a loop or switch-case.

Types of Jumping Statement


In Java, there are three types of jumping statement:

1. Break statement
2. Continue statement
3. Return statement

 Break Statement :

The „break‟ statement in Java terminates the


loop immediately, and the control of the program moves to the next
statement following the loop.
It is almost always used with decision-making statements (Java if...else
Statement).
Here is the syntax of the break statement in Java:

break;
Java Programming

FlowChart of Break statement

Example 1: Java break statement


class Topperworld {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if the value of i is 5 the loop terminates


if (i == 5) {
break;
}
System.out.println(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 :

The „continue‟ statement skips the


current iteration of a loop (for, while, do…while, etc).
After the continue statement, the program moves to the end of the loop.
And, test expression is evaluated (update statement is evaluated in case
of the for loop).
Here's the syntax of the continue statement.

continue;

FlowChart of continue statement


Java Programming

Example : Java continue statement


class Main {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if value of i is between 4 and 9


// continue is executed
if (i > 4 && i < 9) {
continue;
}
System.out.println(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.

if (i > 4 && i < 9) {


continue;
}

Here, the continue statement is executed when the value of i becomes


more than 4 and less than 9.
It then skips the print statement for those values. Hence, the output skips
the values 5, 6, 7, and 8.
Java Programming

 Return Statement :

The „return‟ keyword is used to transfer


a program‟s control from a method back to the one that called it. Since
the control jumps from one part of the program to another, return is
also a jump statement.

Example : Java return statement

public class Main {

public static int add(int a, int b){


int sum = a+b;
return sum;
}
public static void main(String[] args) {
int x = 5, y = 10;
int sum = add(x, y);
System.out.println("Sum of a and b: " + sum);
}
}

Output:

Sum of a & b: 15
Java Programming

Operator in Java

Java operators are symbols that are used to perform operations on


variables and manipulate the values of the operands. Each operator performs
specific operations.

Let us consider an expression 5 + 1 = 6; here, 5 and 1 are operands, and


the symbol + (plus) is called the operator. We will also learn about operator
precedence and operator associativity.

Types of Java Operator


 Arithmetic Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Relational Operators

 Arithmetic Operators :

Arithmetic operators are used to performing addition, subtraction,


multiplication, division, and modulus. It acts as a mathematical
operations.
Java Programming

Operator Description
+ ( Addition ) This operator is used to add the value of the
operands.

– ( Subtraction ) This operator is used to subtract the right-hand


operator with the left hand operator.

* ( Multiplication ) This operator is used to multiply the value of the


operands.

/ ( Division ) This operator is used to divide the left hand


operator with right hand operator.

% ( Modulus ) This operator is used to divide the left hand


operator with right hand operator and returns
remainder.

Example

Let us look at a simple code that in which all the arithmetic operators are used.

public class ArithmeticOperatorsExample {


public static void main(String[] args) {
int num1 = 10, num2 = 5, result;

// 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

System.out.println("Division: " + result);

// 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

This operator is used to add right operand to the

+= left operand and assigns the result to the left


operand.
This operator subtracts right operand from the

-= left operand and assigns the result to the left


operand.
This operator multiplies right operand with the

*= left operand and assigns the result to the left


operand.

This operator divides left operand with the right

/= operand and assigns the result to the left


operand.

Example

Let us look at a simple code in which all the assignment operators are used.

public class Topperworld {


public static void main ( String[] args ) {
int a = 10;
int b = 20;
int c;
System.out.println ( c = a );
System.out.println ( b += a );
System.out.println ( b -= a);
System.out.println ( b *= a );
System.out.println ( b /= a );
System.out.println ( b ^= a );
System.out.println ( b %= a );
}
}

OUTPUT

10
30
Java Programming

10
200
2
0

 Logical Operators :

Logical operators are used to combining two or more conditions or


complement the evaluation of the original condition under consideration.

Operator Description
This operator returns True if both the operands
&& (Logical AND)
are true, otherwise, it returns False.

This operator returns True if either the operands


|| (Logical OR)
are true, otherwise it returns False.

This operator returns True if an operand is False.


! (Logical AND)
It reverses the logical state of an operand.

This operator returns True if both the operands


&& (Logical AND)
are true, otherwise, it returns False.

This operator returns True if either the operands


|| (Logical OR)
are true, otherwise it returns False.

Example

Let us look at a simple code that in which all the logical operators are used.

public class Topperworld {


public static void main ( String args[] ) {
int a = 5;
System.out.println ( a<5 && a<20 );
Java Programming

System.out.println ( a<5 || a<20 );


System.out.println ( ! ( a<5 && a<20 ));
}
}

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.

This operator takes two numbers as operands


| (Bitwise OR)
and does OR on every bit of two numbers.

This operator takes two numbers as operands


^ (Bitwise XOR)
and does XOR on every bit of two numbers.

This operator takes one number as an operand


~ (Bitwise NOT)
and does invert all bits of that number.
Java Programming

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.

public class Topperworld {


public static void main(String[] args) {
int num1 = 10, num2 = 5;

// Bitwise AND Operator


int result = num1 & num2;
System.out.println("Bitwise AND: " + result);

// Bitwise OR Operator
result = num1 | num2;
System.out.println("Bitwise OR: " + result);

// Bitwise XOR Operator


result = num1 ^ num2;
System.out.println("Bitwise XOR: " + result);

// Bitwise Complement Operator


result = ~num1;
System.out.println("Bitwise Complement of num1: " + result);

// Left Shift Operator


result = num1 << 2;
System.out.println("Left Shift of num1: " + result);

// Right Shift Operator


result = num1 >> 2;
System.out.println("Right Shift of num1: " + result);

// Unsigned Right Shift Operator


result = num1 >>> 2;
System.out.println("Unsigned Right Shift of num1: " + result);
}
Java Programming

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 :

Ternary operator is an conditional operator, it reduces the line of code


while performing the conditional or comparisons. It is the replacement of
if-else or nested if-else statements. It is also referred to as inline if,
conditional operator, or ternary if..

Example

Let us look at a simple code of Ternary operator.

public class Topperworld {


public static void main ( String args[] ) {
int a = 4;
int b = 9;
int min = ( a<b ) ? a : b;
System.out.println ( min );
}
}
Java Programming

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.

This operator returns True, if two operands are


== (Equal to)
equal, else it returns False.
Java Programming

Example

Let us look at a simple code that in which all the realational operators are used.

public class Topperworld {


public static void main ( String args[] ) {
int a = 10;
int b = 20;
System.out.println ( a < b );
System.out.println( a > b );
System.out.println ( a <= b );
System.out.println (a >= b );
System.out.println ( a == b );
System.out.println ( a != b );
}
}

OUTPUT

true
false
true
false
false
true
Java Programming

Java Operator Precedence Table

Category Operator Associativity

Postfix >() [] . (dot operator) Left toright

Unary >++ - - ! ~ Right to left

Multiplicative >* / Left to right

Additive >+ - Left to right

Shift >>> >>> << Left to right

Relational >> >= < <= Left to right

Equality >== != Left to right

Bitwise AND >& Left to right

Bitwise XOR >^ Left to right

Bitwise OR >| Left to right

Logical AND >&& Left to right

Logical OR >|| Left to right

Conditional ?: Right to left

>= += -= *= /= %= >>=
Assignment Right to left
<<= &= ^= |=
Java Programming

Package in Java

A package is simply a container that groups related types (Java classes,


interfaces, enumerations, and annotations). For example, in core Java,
the ResultSet interface belongs to the java.sql package. The package
contains all the related types that are needed for the SQL query and
database connection.

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).

As mentioned earlier, packages are just containers for Java classes,


interfaces and so on. These packages help you to reserve the class
namespace and create a maintainable code.

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

Based on whether the package is defined by the user or not, packages


are divided into two categories :

 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) {

ArrayList<Integer> myList = new ArrayList<>(3);


myList.add(3);
myList.add(2);
myList.add(1);

System.out.println(myList);
}
}

Output:

myList = [3, 2, 1]

The Arraylist class belongs to java.util package . To use it, we have to


import the package first using the import statement.

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.

How to define a Java package?

To define a package in Java, you use the keyword Package.

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 {

public static void main(String[] args){


Java Programming

System.out.println("Hello World!");

Output:

Hello World!

Here, the Test class now belongs to the com.test package.

Package Naming convention

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

And, there is no limitation on how many subdirectories (package


hierarchy) you can create.
Java Programming

How to create a package in Intellij IDEA?

In IntelliJ IDEA, here's how you can create a package:

1. Right-click on the source folder.

2. Go to new and then package.

3. A pop-up box will appear where you can enter the package name.

Once the package is created, a similar folder structure will be created on


your file system as well. Now, you can create classes, interfaces, and so
on inside the package.
Java Programming

How to import packages in Java?

Java has an import statement that allows you to import an entire


package (as in earlier examples), or use only certain classes and
interfaces defined in the package.
The general form of import statement is:

import package.name.ClassName; // To import a certain class only

import package.name.* // To import the whole package

For example,

import java.util.Date; // imports only Date class

import java.io.*; // imports everything inside java.io package

The import statement is optional in Java.


If you want to use class/interface from a certain package, you can also
use its fully qualified name, which includes its full package hierarchy.
Here is an example to import a package using the import statement.
Java Programming

import java.util.Date;

class MyClass implements Date {

// body

The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date {

//body

Example: Package and importing package

Suppose, you have defined a package com.programiz that contains a


class Helper.

package com.programiz;

public class Helper {

public static String getFormattedDollar (double value){

return String.format("$%.2f", value);

}
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 {

public static void main(String[] args) {

double value = 99.5;

String formattedValue = Helper.getFormattedDollar(value);

System.out.println("formattedValue = " + formattedValue);

Output:

formattedValue = $99.50

Here,

1. The Helper class is defined in com.programiz package.


2. The Helper class is imported to a different file. The file contains
useHelper class.
3. The getFormattedDollar() method of the Helper class is called from
inside the useHelper class.
Java Programming

Java import package

In Java, the import statement is written directly after the package


statement (if it exists) and before the class definition.
For example,

package package.name;

import package.ClassName; // only import a Class

class MyClass {

// body

}
Java Programming

Array in Java

Array is a collection of elements of the same data type, arranged in a


contiguous block of memory. Each element of an array can be accessed by
its index or position within the array.

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 :

A single-dimensional array is a collection of elements of the same data


type that are stored in a contiguous block of memory. Each element in the
array is accessed using an index, which starts from 0 and goes up to the
length of the array minus 1.
Java Programming

Declare an array in Java

In Java, here is how we can declare an array.

dataType[] arrayName;

 dataType - it can be primitive data types like int , char , double , byte ,

etc. or Java objects


 arrayName - it is an identifier

For example,

double[] data;

Here, data is an array that can hold values of type double.

But, how many elements can array this hold?


Good question! To define the number of elements that an array can hold, we
have to allocate memory for the array in Java. For example,

// 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,

double[] data = new double[10];


Java Programming

Initialize Arrays in Java


In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};

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;
..

Java Arrays initialization


Java Programming

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.

Access Elements of an Array in Java

We can access the element of an array using the index number. Here is the
syntax for accessing elements of an array,

// access array elements


array[index]

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements

class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
Java Programming

System.out.println("Fifth Element: " + age[4]);


}
}

Output

Accessing Elements of Array:


First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5

 Multi-Dimensional Array :

A multidimensional array is an array of arrays. Each element of a


multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-


dimensional array, that can hold a maximum of 12 elements,
Java Programming

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,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of

type String.

Initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Java Programming

As we can see, each element of the multidimensional array is an array itself.


And also, unlike C/C++, each row of the multidimensional array in Java can
be of different lengths.

Example: 2-dimensional Array


class MultidimensionalArray {
public static void main(String[] args) {

// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

// calculate the length of each row


System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}

Output:

Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Java Programming

In the above example, we are creating a multidimensional array named a.

Since each component of a multidimensional array is also an array


(a[0], a[1] and a[2] are also arrays).

Example: Print all elements of 2d array Using Loop

class MultidimensionalArray {
public static void main(String[] args) {

int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};

for (int i = 0; i < a.length; ++i) {


for(int j = 0; j < a[i].length; ++j) {

System.out.println(a[i][j]);
}
}
}
}

Output:

1
-2
3
-4
-5
6
9
7

We can also use the for...each loop to access elements of the


multidimensional array. For example,
Java Programming

class MultidimensionalArray {
public static void main(String[] args) {

// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};

// first for...each loop access the individual array


// inside the 2d array
for (int[] innerArray: a) {
// second for...each loop access each element inside the row
for(int data: innerArray) {
System.out.println(data);
}
}
}
}
Output:

-2

-4

-5

In the above example, we are have created a 2d array named a. We then


used for loop and for...each loop to access each element of the array.
Java Programming

Initialize a 3d array in Java

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}
}
};

Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also


vary in length just like in a 2d array.

Example: 3-dimensional Array

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

// for..each loop to iterate through elements of 3d array


for (int[][] array2D: test) {
for (int[] array1D: array2D) {
for(int item: array1D) {
System.out.println(item);
}
}
}
}
}

Output:

1
-2
3
2
3
4
-4
-5
6
9
1
2
3
Java Programming

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.

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

Here, Topperworld() is a constructor. It has the same name as that of the


class and doesn't have a return type.

Rules for creating a Constructor :

 The class name and constructor name should be the same.


 It must have no explicit return type.
 It can not be abstract, static, final, and synchronized.

Types of Constructor
In Java, constructors can be divided into 3 types:

 Default Constructor

 Parameterized Constructor
Java Programming

 Default Constructor :

A constructor with no parameters is


known as default constructor.

If we do not create any constructor, the Java compiler automatically create a


no-arg constructor during the execution of the program. This constructor is
called default constructor.

Example : Default Constructor


class Main {

int a;
boolean b;

public static void main(String[] args) {

// A default constructor is called


Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

Output:

Default Value:
a=0
b = false

Here, we haven't created any constructors. Hence, the Java compiler


automatically creates the default constructor.
Java Programming

 Parameterized Constructor :

A constructor with some


specified number of parameters is known as a parameterized constructor.

Example : Parameterized constructor

class Topperworld {

String languages;

// constructor accepting single value


Topperworld (String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


Topperworld obj1 = new Topperworld("Java");
Topperworld obj2 = new Topperworld("Python");
Topperworld obj3 = new Topperworld("C");
}
}

Output:

Java Programming Language


Python Programming Language
C Programming Language

In the above example, we have created a constructor named Topperworld().


Here, the constructor takes a single parameter. Notice the expression,

Topperworld obj1 = new Topperworld("Java");

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

OOP‟s Concept in Java

 Object-oriented programming System(OOPs) is a programming

concept that is based on “objects”.

 It allows users to create objects they want and create methods to

handle those objects.

 The basic concept of OOPs is to create objects, re-use them

throughout the program, and manipulate these objects to get

results.

 The main principles of object-oriented programming are abstraction,

encapsulation, inheritance, and polymorphism. These concepts aim to

implement real-world entities in programs.

List Of OOP‟s Concept in Java

 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.

An Object can be defined as an instance of a class. An object contains an


address and takes up some space in memory.

 Class :

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.

 Inheritance :

Inheritance is a mechanism in which a new

class is derived from an existing class. The new class is called the

subclass, and the existing class is called the superclass. The subclass

inherits the properties and behavior of the superclass.


Java Programming

 Polymorphism :

Polymorphism means the ability of an

object to take on many forms. In Java, polymorphism can be achieved

through method overloading and method overriding.

 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

Advantage of OOP‟s in Java

 There are various advantages of object-oriented programming.


 OOP‟s provide reusability to the code and extend the use of existing
classes.
 In OOP‟s, it is easy to maintain code as there are classes and
objects, which helps in making it easy to maintain rather than
restructuring.
 It also helps in data hiding, keeping the data and information safe
from leaking or getting exposed.

Disadvantage of OOP‟s in Java

 The length of the programmes developed using OOP language is


much larger than the procedural approach. Since the programme
becomes larger in size, it requires more time to be executed that
leads to slower execution of the programme.
 We can not apply OOP everywhere as it is not a universal language.
It is applied only when it is required. It is not suitable for all types
of problems.
 Programmers need to have brilliant designing skill and programming
skill along with proper planning because using OOP is little bit
tricky.
 OOP‟s take time to get used to it. The thought process involved in
object-oriented programming may not be natural for some people.
 Everything is treated as object in OO‟P so before applying it we
need to have excellent thinking in terms of objects.
Java Programming

Benefits of OOPs in Java

 The benefit of code reusability.


 Easier to co-relate with the real-world.
 Generation of a secured program.
 Convenient to solve complex problems.
 Easy to maintain the software complexity.
 Multiple instances can be generated for an object.
Java Programming

Java Class & Object

Java is an object-oriented programming language. The core concept of


the object-oriented approach is to break complex problems into smaller
objects.

An object is any entity that has a state and behavior. For example,
a bicycle is an object. It has

 States: idle, first gear, etc


 Behaviors: braking, accelerating, etc.
Before we learn about objects, let's first know about classes in Java.

Java Class

A class is a blueprint for the object. Before we create an object, we first


need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains


all the details about the floors, doors, windows, etc. Based on these
descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can
create many objects from a class.
Java Programming

Create a class in Java

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

the object respectively.


 fields are used to store data

 methods are used to perform some operations

For our bicycle object, we can create the class as

class Bicycle {

// state or field
private int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

In the above example, we have created a class named Bicycle . It contains

a field named gear and a method named braking().

Here, Bicycle is a prototype. Now, we can create any number of bicycles


using the prototype.
Java Programming

Java Object

An object is called an instance of a class. For example, suppose Bicycle is

a class then MountainBicycle, SportsBicycle, TouringBicycle, etc can be

considered as objects of the class.

Creating an Object in Java

Here is how we can create an object of a class.

className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();

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

the Bicycle class.

Here, sportsBicycle and touringBicycle are the names of objects. We can

use them to access fields and methods of the class.


As you can see, we have created two objects of the cla
Java Programming

Access Members of a Class

We can use the name of objects along with the . operator to access

members of a class. For example,

class Bicycle {

// field of class
int gear = 5;

// method of class
void braking() {
...
}
}

// create object
Bicycle sportsBicycle = new Bicycle();

// access field and method


sportsBicycle.gear;
sportsBicycle.braking();

In the above example,


we have created a class named Bicycle. It includes a field named gear and

a method named braking(). Notice the statement,

Bicycle sportsBicycle = new Bicycle();

Here,
we have created an object of Bicycle named sportsBicycle. We then use

the object to access the field and method of the class.


 sportsBicycle.gear - access the field gear

 sportsBicycle.braking() - access the method braking()

We have mentioned the word method quite a few times.


Java Programming

Example: Java Class and Objects


class Lamp {

// stores the value for light


// true if light is on
// false if light is off
boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

// method to turnoff the light


void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}

class Main {
public static void main(String[] args) {

// create objects led and halogen


Lamp led = new Lamp();
Lamp halogen = new Lamp();

// turn on the light by


// calling method turnOn()
led.turnOn();

// turn off the light by


// calling method turnOff()
halogen.turnOff();
}
}

Output:

Light on? true


Light on? false
Java Programming

In the above program, we have created a class named Lamp. It contains a


variable: isOn and two methods: turnOn() and turnOff().
Inside the Main class, we have created two objects: led and halogen of
the Lamp class. We then used the objects to call the methods of the class.
 led.turnOn() - It sets the isOn variable to true and prints the
output.
 halogen.turnOff() - It sets the isOn variable to false and prints the

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.

 Difference between Class & Object

Class Object
A class is a template for creating The object is an instance of a

objects in program. class.

A class is a logical entity Object is a physical entity

A class does not allocate memory Object allocates memory space

space when it is created. whenever they are created.

You can create more than one


You can declare class only once.
object using a class.
Java Programming

Example: Car. Example: Jaguar, BMW, Tesla, etc.

Class generates objects Objects provide life to the class.

Classes can‟t be manipulated as


They can be manipulated.
they are not available in memory.

Each and every object has its own


It doesn‟t have any values which
values, which are associated with
are associated with the fields.
the fields.

You can create class using “class” You can create object using “new”

keyword. keyword in Java


Java Programming

Inheritance in Java

Inheritance is an object-oriented programming concept in which one


class acquires the properties and behavior of another class.

It represents a parent-child relationship between two classes. This


parent-child relationship is also known as an IS-A relationship.

The new class that is created is known as subclass (child or derived


class) and the existing class from where the child class is derived is
known as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java. For example,

class Animal {
// methods and fields
}

// use of extends keyword


// to perform inheritance
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}

In the above example, the Dog class is created by inheriting the methods

and fields from the Animal class.

Here, Dog is the subclass and Animal is the superclass.


Java Programming

Let us discuss a real-world example that helps us understand the


need and importance of inheritance.

Imagine you have built a standard calculator application in java. Your


application does addition, subtraction, multiplication, division, and square
root.

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.

Why use inheritance in java ?

In the real-world scenario we discussed in the introduction, applying


inheritance would give us reusability. You could use the code you have
written for the standard calculator in the new scientific calculator without
writing the same again.

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

Terms used in inheritance

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.

Superclass: The class whose attributes and methods the subclass


inherits.

Extends: The subclass uses the keyword to inherit the superclass.

Reusability: The methods and attributes of the superclass can be reused


in the subclass because of inheritance, this is called reusability.

Example :

Below is a simple JAVA program that illustrates how inheritance works:

class SuperClass {
void methodSuper() {
System.out.println("I am a super class method");
}
}

// Inheriting SuperClass to SubClass


class SubClass extends SuperClass {
void methodSubclass() {
System.out.println("I am a sub class method");
}
}
class Main {
public static void main(String args[]) {
SubClass obj = new SubClass();
obj.methodSubClass();
obj.methodSuper();
}
}

Output:
Java Programming

I am a sub class method


I am a super class method

Explanation:

 A class Superclass with method methodSuper() and another


class Subclass with method methodSubclass() are written.
 Inherit the Superclass to Subclass using the extends keyword.
 Create an object for SubClass obj in the main method
 Since the SuperClass is inherited to the SubClass, the
methodSuper() of SuperClass is now part of the SubClass.
 So, SubClass now has two methods, methodSuper() and
methodSubclass(), which can be called using the obj Object.

Types of Inheritance in Java


There are five different types of inheritances in Java:

1. Single

2. Multilevel

3. Hierarchical

4. Multiple

5. Hybrid
Java Programming

 Single Inheritance :

In single inheritance, a single subclass extends from a single


superclass. For example,

Example : Single Inheritance


class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}

Output:
I am green!
I am a Bird
Java Programming

Here,

 Bird Class is written with a method fly().


 The Parrot Class inherited the Bird Class using extends keyword.
 An object of type parrot is created in the main method of the main
class. This object is able to call the fly() method of the Bird class as
it inherits the Bird class.

 Multilevel Inheritance :

In multilevel inheritance, a subclass extends from a superclass and


then the same subclass acts as a superclass for another class. For
example,
Java Programming

Example : Multilevel Inheritance


class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
System.out.println("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
obj.whatCanISing();
obj.whatColourAmI();
obj.fly();
}
}

Output:
I can sing Opera!
I am green!
I am a Bird

Here,

 Here in this program, the chain of inheritance is the Bird class is


inherited by the Parrot class, and the Parrot class is, in turn,
inherited by the SingingParrot class.
 The object of SingingParrot created in the main method of java will
be able to access the methods whatCanISing(), whatColourAmI(),
fly() as they are all inherited by SingingParrot class using multilevel
inheritance in java.
Java Programming

 Hierarchical Inheritance :

In Hierarchical inheritance, multiple subclasses extend from a single


superclass. For example,

Example : Hierarchical Inheritance


class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
System.out.println("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.whatColourAmI();
par.fly();

//Call methods of Crow Class


cro.whatColourAmI();
cro.fly();
}
Java Programming

Output:
I am green!
I am a Bird
I am black!
I am a Bird

Here,

 The superclass Bird is inherited separately by two different


subclasses Parrot and Crow.
 The Parrot object can call its method whatColourAmI() and also the
fly() method, which is inherited from the superclass Bird.
 The Crow object can call its method whatColourAmI() and also the
fly() method, which is inherited from the superclass Bird.

 Multiple Inheritance :

In multiple inheritance, a single subclass extends from multiple


superclasses. For example,
Java Programming

Consider there is a superclass1 name A, and A class has a method


testMethod(). And Consider there is a superclass2 named B, and B

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.

Example : Multiple Inheritance


class A {
void testMethod() {
System.out.println("I am from class A");
}
}
class B {
void testMethod() {
System.out.println("I am from class B");
}
}
// Not possible to inherit classes this way, But for understanding, let
us suppose
class C extends A, B {
void newMethod() {
System.out.println("I am from subclass");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
obj.testMethod();
// Ambiguity here as it's present in both A and B class
}
}

Note: The above program is just for understanding that multiple


inheritance of classes is invalid in java.
Java Programming

 Hybrid Inheritance :

Hybrid inheritance is a combination of two or more types of inheritance.


For example,
Java Programming

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.

Example : Super Keyword in Inheritance


class TestParentClass {
int
var = 100;
}
class TestChildClass extends TestParentClass {
int
var = 50; //Same variable is present in both parent and child

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:

 Class TestChildClass inherits the TestParentClass. Both classes have


a common variable, var. In such a conflict, priority is always given
to the child class's variable. 
 To access the variable of the parent class from the child class, we
can make use of the keyword super.
Java Programming

Access modifiers and How they affect inheritance ?

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:

Variables and methods declared private in the parent class cannot be


inherited by child classes. They can only be accessed in the parent class.
By creating public getter and setter methods, we can access these
variables in the child class.

 Public:

Variables and methods declared as public in the parent class would be


inherited by the child class and can be accessed directly by the child
class.

 Protected:

Variables and methods declared as protected in the parent class would be


inherited by the child class and can be accessed directly by the child
class. But the access level is limited to one subclass. So if the subclass is
again inherited by another class, they will not have access to those
protected variables/methods.

 Default:

This is the case where no access modifier is specified. Variables and


methods which have default access modifiers in the parent class can be
accessed by the child class.
Java Programming

Polymorphism in Java

Polymorphism is an important concept of object-oriented programming.


It simply means more than one form.

That is, the same entity (method or operator or object) can perform
different operations in different scenarios.

Let us understand the definition of polymorphism by an example; a lady can


have different characteristics simultaneously. She can be a mother, a
daughter, or a wife, so the same lady possesses different behavior in
different situations.

Example: Java Polymorphism


class Polygon {

// method to render a shape


public void render() {
System.out.println("Rendering Polygon...");
}
}

class Square extends Polygon {

// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}

class Circle extends Polygon {

// renders circle
public void render() {
System.out.println("Rendering Circle...");
Java Programming

}
}

class Main {
public static void main(String[] args) {

// create an object of Square


Square s1 = new Square();
s1.render();

// create an object of Circle


Circle c1 = new Circle();
c1.render();
}
}

Output

Rendering Square...
Rendering Circle...

In the above example,

we have created a superclass: Polygon and two subclasses: Square and


Circle. Notice the use of the render() method.

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.

Hence, the render() method behaves differently in different classes.

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.

Java Method Overloading

In a Java class, we can create methods with the same name if they differ
in parameters. For example,

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.

Example : Polymorphism using method overloading

class Pattern {

// method without parameter


public void display() {
for (int i = 0; i < 10; i++) {
System.out.print("*");
}
}

// method with single parameter


public void display(char symbol) {
for (int i = 0; i < 10; i++) {
System.out.print(symbol);
}
}
}

class Main {
public static void main(String[] args) {
Java Programming

Pattern d1 = new Pattern();

// call method without any argument


d1.display();
System.out.println("\n");

// call method with a single argument


d1.display('#');
}
}

Output:

**********

##########

In the above example, we have created a class named Pattern. The class

contains a method named display() that is overloaded.

// method with no arguments


display() {...}

// method with a single char type argument


display(char symbol) {...}

Here, the main function of display() is to print the pattern. However,


based on the arguments passed, the method is performing different
operations:
 prints a pattern of *, if no argument is passed or

 prints pattern of the parameter, if a single char type argument is


passed.
Java Programming

 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.

Java Method Overriding

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,

Example : Polymorphism using method overriding

class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}

class Java extends Language {


@Override
public void displayInfo() {
System.out.println("Java Programming Language");
}
}

class Main {
public static void main(String[] args) {

// create an object of Java class


Java j1 = new Java();
j1.displayInfo();

// create an object of Language class


Language l1 = new Language();
l1.displayInfo();
Java Programming

}
}

Output:

Java Programming Language


Common English Language

In the above example,


we have created a superclass named Language and a subclass

named Java.

Here, the method displayInfo() is present in both Language and Java.

The use of displayInfo() is to print the information. However, it is printing


different information in Language and Java.

Characteristics of Polymorphism :

 Overloading: Polymorphism in Java is achieved through method


overloading, which allows multiple methods to have the same name
but different parameters or argument types. The Java compiler
determines which method to call based on the arguments provided
at compile time.
 Overriding: Polymorphism in Java is also achieved through method
overriding, where a subclass provides a different implementation of
a method that is already defined in its parent class. The subclass
method must have the same name and signature as the parent class
method. When the method is called on an object of the subclass, the
subclass method is executed instead of the parent class method.
Java Programming

 Dynamic binding: Polymorphism in Java also involves dynamic


binding, where the actual implementation of a method is determined
at runtime instead of compile time. This allows for more flexible and
adaptable code as objects can be manipulated and used in different
ways.
 Flexibility: Polymorphism in Java allows objects of different classes
to be treated as if they were of the same class, making the code more
flexible and reusable.
 Extensibility: Polymorphism in Java allows for more modular and
extensible code as it enables objects to be manipulated and used in
different ways, making it easier to add new functionality or modify
existing code.
 Abstraction: Polymorphism in Java is closely related to abstraction,
as it allows objects to be abstracted into a common interface or
superclass, allowing for more generic code that can handle different
types of objects.
Java Programming

Encapsulation in Java

Data Encapsulation is a process of wrapping of code and data in a


single unit. In object-oriented programming, we call this single unit - a
class, interface, etc.

We can visualize it like a medical capsule (as the name suggests,


too), where in the enclosed medicine can be compared to fields and
methods of a class.

Data encapsulation helps organize thousands of lines of code for better


readability and management. At the same time, it protects the sensitive
data as well by restricting access to internal implementation details.

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

Example of Java Encapsulation


let us look at a real-life example first.
Suppose a technical fest is being organized in your college. Many teams
coordinate and work together, for example, Finance team, Sponsorship
team, Public Relations team, etc. Information or data of a particular team
and the members of that team who can manipulate this information are
wrapped under a single name. This is what encapsulation is. These teams
are like code units. Relating a team to a medical capsule, the team
information, and the team members can be compared to the
enclosed medicine.

Let us consider a simpler case for implementation in Java. Below is a


program to calculate the perimeter of a rectangle.

class Perimeter {

//Variables of the class


int length;
int breadth;

// constructor to initialize values


Perimeter(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}

// Method that manipulates the variables


public void getPerimeter() {
int perimeter = 2 * (length + breadth);
System.out.println("Perimeter of Rectangle : " + perimeter);
}
}

class Main {
public static void main(String[] args) {

//object of class Perimeter


Perimeter rectangle = new Perimeter(3, 6);
rectangle.getPerimeter();
}
Java Programming

Output:

Perimeter of Rectangle : 18

Here in the class Perimeter:

 The length and breadth variables, the


method getPerimeter() manipulating them, and the constructor to
initialize the values are defined.
 In other words, all the data is encapsulated inside the class Perimeter.
 The method getPerimeter() takes length and breadth variables and
calculates the perimeter.

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 ?

 In Java, encapsulation helps us to keep related fields and methods


together, which makes our code cleaner and easy to read.

 It helps to control the values of our data fields. For example,

class Person {
private int age;

public void setAge(int age) {


if (age >= 0) {
Java Programming

this.age = age;
}
}
}

Here, we are making the age variable private and applying logic

inside the setAge() method. Now, age cannot be negative.


 The getter and setter methods provide read-only or write-
only access to our class fields. For example,

getName() // provides read-only access


setName() // provides write-only access

 It helps to decouple components of a system. For example, we can


encapsulate code into multiple bundles.
These decoupled components (bundle) can be developed, tested,
and debugged independently and concurrently. And, any changes in
a particular component do not have any effect on other
components.
 We can also achieve data hiding using encapsulation. In the above
example, if we change the length and breadth variable into private,
then the access to these fields is restricted.

And, they are kept hidden from outer classes. This is called data
hiding.

Advantage of Java Encapsulation

 Data Protection: The program runner will not be able to identify or


see which methods are present in the code. Therefore he/she
Java Programming

doesn‟t get any chance to change any specific variable or data and
hinder the running of the program.

 Flexibility: The code which is encapsulated looks


more cleaner and flexible, and can be changed as per the needs.
We can change the code read-only or write-only by getter and
setter methods. This also helps in debugging the code if needed.

 Reusability: The methods can be changed and the code


is reusable.

Disadvantage of Java Encapsulation

 Code Size:The length of the code increases drastically in the case


of encapsulation as we need to provide all the methods with the
specifiers.

 More Instructions: As the size of the code increases, therefore,


you need to provide additional instructions for every method.

 Increased code execution: Encapsulation results in an increase in


the duration of the program execution. It is because more
instructions are added to the code therefore they require more time
to execute.
Java Programming

Data Hiding

Data hiding is a way of restricting the access of our data


members by hiding the implementation details. Encapsulation
also provides a way for data hiding.

Example : Data hiding using the private specifier

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) {

// create an object of Person


Person p1 = new Person();

// change age using setter


p1.setAge(24);

// access age using getter


System.out.println("My age is " + p1.getAge());
Java Programming

}
}

Output

My age is 24

In the above example,

we have a private field age. Since it is private, it cannot be accessed


from outside the class.

In order to access age, we have used public methods: getAge() and


setAge(). These methods are called getter and setter methods.

Making “age” private allowed us to restrict unauthorized access from


outside the class. This is data hiding.

If we try to access the age field from the Main class, we will get an error.

// error: age has private access in Person


p1.age = 24;
Java Programming

Abstraction in Java

Abstraction in Java refers to hiding the implementation details of a code


and exposing only the necessary information to the user.

It provides the ability to simplify complex systems by ignoring irrelevant


details and reducing complexity.

Java provides many in-built abstractions and few tools to create our own.

Abstraction in Java can be achieved by Use of :

 Abstract classes
 Interfaces

Java Abstract Class

The abstract class in Java cannot be instantiated (we cannot create


objects of abstract classes). We use the abstract keyword to declare an
abstract class. For example,

// create an abstract class


abstract class Language {
// fields and methods
}
...

// try to create an object Language


// throws an error
Language obj = new Language();
Java Programming

An abstract class can have both the regular methods and abstract
methods. For example,

abstract class Language {

// abstract method
abstract void method1();

// regular method
void method2() {
System.out.println("This is regular method");
}
}

Java Abstract Method

A method that doesn't have its body is known as an abstract method. We


use the same abstract keyword to create abstract methods. For example,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced

by ;.

If a class contains an abstract method, then the class should be declared


abstract. Otherwise, it will generate an error.

For example,

// error
// class should be abstract
class Language {

// abstract method
abstract void method1();
Java Programming

A practical example of abstraction can be motorbike brakes. We


know what brake does. When we apply the brake, the motorbike
will stop. However, the working of the brake is kept hidden from us.

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.

Let's take an example that helps us to better understand Java abstraction..

Example : Java Abstraction

abstract class MotorBike {


abstract void brake();
}

class SportsBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("SportsBike Brake");
}
}

class MountainBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("MountainBike Brake");
}
}

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

In the above example, we have created an abstract super


class MotorBike. The superclass MotorBike has an abstract

method brake().

The brake() method cannot be implemented inside MotorBike. It is


because every bike has different implementation of brakes. So, all the
subclasses of MotorBike would have different implementation of brake().

So, the implementation of brake() in MotorBike is kept hidden.


Here, MountainBike makes its own implementation

of brake() and SportsBike makes its own implementation of brake().

Advantage of Abstraction :

 Modularity: Abstraction allows you to break down a complex


system into smaller, more manageable parts. By hiding
implementation details and focusing only on the essential features,
you can create modular components that can be easily maintained,
modified, and reused.
 Encapsulation: Abstraction helps to enforce the principle of
encapsulation, which is one of the key principles of OOP.
Encapsulation means that the implementation details of an object
are hidden from the outside world, and can only be accessed
through a well-defined interface. Abstraction allows you to define a
Java Programming

well-defined interface for an object, and hide its implementation


details.
 Polymorphism: Abstraction allows you to achieve polymorphism in
Java, which means that you can treat objects of different classes as
if they were of the same type. By defining a common interface for a
group of objects, you can write code that can work with any object
that implements that interface, without knowing its specific type.
 Code Reusability: Abstraction promotes code reusability in Java,
as you can define common behaviors and interfaces that can be
implemented by multiple classes. This reduces the amount of code
that needs to be written and maintained, and allows you to create
more efficient and scalable applications.

Disadvantage of Abstraction :

 Complexity: Abstraction can add complexity to your code if not


used properly. If the abstraction is too complex or abstract, it can
be difficult to understand and maintain the code.
 Performance Overhead: Abstraction can introduce a performance
overhead, as the code needs to be processed through additional
layers of abstraction. This can lead to slower execution times,
especially for large or complex applications.
 Design Overhead: Abstraction requires careful design and
planning, which can add additional overhead to the development
process. This can lead to longer development times and higher
development costs.
 Limited Flexibility: Abstraction can limit the flexibility of your
code, as it may restrict the ways in which you can use or extend the
code. This can make it more difficult to adapt the code to changing
requirements or new use cases.
Java Programming

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and


abstract methods(methods without a body).

The interface in Java is a mechanism to achieve abstraction. There can


be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.

We use the interface keyword to create an interface in Java.


For example,

interface Topperworld {
public void getType();

public void getVersion();


}

Here,

 Topperworld is an interface.

 It includes abstract methods: getType() and getVersion().

Use of Java interface

There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple
inheritance.
 It can be used to achieve loose coupling.
Java Programming

Implementation of Interface

Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use


the implements keyword to implement an interface.

Example : Java Interface

interface Topperworld {
void getArea(int length, int breadth);
}

// implement the Topperworld interface


class Rectangle implements Topperworld {

// implementation of abstract method


public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(10, 5);
}
}

Output

The area of the rectangle is 50

In the above example, we have created an interface named Topperworld.

The interface contains an abstract method getArea().

Here, the Rectangle class implements Topperworld. And, provides the

implementation of the getArea() method.


Java Programming

When implementation interfaces, there are several rules :−

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a
class can extend another class.

 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
}

Here, the Topperworld interface extends the Javatutorial interface. Now,

if any class implements Topperworld, it should provide implementations

for all the abstract methods of both Javatutorial and Topperworld.

Extending Multiple Interfaces

An interface can extend multiple interfaces. For example,

interface A {
...
}
interface B {
...
}
Java Programming

interface C extends A, B {
...
}

 Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For example,

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:

 Abstraction: Interfaces provide a level of abstraction that allows

you to separate the implementation details from the interface

definition. This allows you to change the implementation of a class

without affecting the code that uses the class through its interface.

 Multiple Inheritance: Unlike classes, interfaces support multiple

inheritance in Java. A class can implement multiple interfaces,

which allows it to inherit the abstract methods and constants from

each of those interfaces.

 Polymorphism: Interfaces provide a way to achieve polymorphism

in Java. Polymorphism allows you to write code that works with

objects of different classes, as long as those classes implement the

same interface.

 Loose Coupling: Using interfaces promotes loose coupling between

components of a system. By programming to an interface rather

than a concrete implementation, you can create more flexible and

maintainable code.

 API Design: Interfaces are commonly used in Java to define APIs

(Application Programming Interfaces). By defining an interface, you

provide a clear and concise contract that other developers can use

to build their own implementations of the interface. This promotes

modularity and code reuse.


Java Programming

Difference between Class & Interface

CLASS INTERFACE

The „class‟ keyword is used to The „interface‟ keyword is used to


create a class. create an interface.

An object of a class can be An object of an interface cannot be


created. created.

Class doesn‟t support multiple Interface supports multiple


inheritance. inheritance.

A class can inherit another class. An Interface cannot inherit a class.

A class can be inherited by another An Interface can be inherited by a


class using the keyword „extends‟. class using the keyword
„implements‟ and it can be
inherited by another interface
using the keyword „extends‟.

A class can contain constructors. An Interface cannot contain


constructors.

It cannot contain abstract It consists of abstract methods


methods. only.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy