Difference between procedural programming and
object-oriented programming
Object-oriented programming and procedural programming both are used to develop the
applications. Both of them are high-level programming languages.
Procedural Programming
It is defined as a programming language derived from the structure programming and based
on calling procedures. The procedures are the functions, routines, or subroutines that consist
of the computational steps required to be carried. It follows a step-by-step approach in order
to break down a task into a set of variables and routines via a sequence of instructions.
During the program's execution, a procedure can be called at any point, either by other
procedures or by itself. The examples of procedural programming are ALGOL, COBOL,
BASIC, PASCAL, FORTRAN, and C.
As compared to object-oriented programming, procedural programming is less secure.
Procedural programming follows a top-down approach during the designing of a program. It
gives importance to the concept of the function and divides the large programs into smaller
parts or called as functions. Procedural programming is straightforward. Unlike object-
oriented programming, there are no access modifiers introduced in procedural programming.
Object-oriented programming
Object-oriented programming is a computer programming design philosophy or methodology
that organizes/ models software design around data or objects rather than functions and logic.
It includes two words, "object" and "oriented". In a dictionary object is an article or entity
that exists in the real world. The meaning of oriented is interested in a particular kind of thing
or entity. In layman's terms, it is a programming pattern that rounds around an object or
entity.
The programming paradigm where everything is represented as an object is known as a truly
object-oriented programming language. Smalltalk is said to be the first truly object-oriented
programming language.
[Link]. On the basis Procedural Object-oriented programming
of Programming
1. Definition It is a programming Object-oriented programming is a
language that is derived computer programming design
from structure philosophy or methodology that
programming and based organizes/ models software design
upon the concept of calling around data or objects rather than
procedures. It follows a functions and logic.
step-by-step approach in
order to break down a task
into a set of variables and
1
routines via a sequence of
instructions.
2. Security It is less secure than Data hiding is possible in object-
OOPs. oriented programming due to
abstraction. So, it is more secure
than procedural programming.
3. Approach It follows a top-down It follows a bottom-up approach.
approach.
4. Data In procedural In OOP, objects can move and
movement programming, data moves communicate with each other via
freely within the system member functions.
from one function to
another.
5. Orientation It is structure/procedure- It is object-oriented.
oriented.
6. Access There are no access The access modifiers in OOP are
modifiers modifiers in procedural named as private, public, and
programming. protected.
7. Inheritance Procedural programming There is a feature of inheritance in
does not have the concept object-oriented programming.
of inheritance.
8. Code There is no code It offers code reusability by using
reusability reusability present in the feature of inheritance.
procedural programming.
9. Overloading Overloading is not In OOP, there is a concept of
possible in procedural function overloading and operator
programming. overloading.
10. Data hiding There is not any proper There is a possibility of data
way for data hiding. hiding.
Characteristics or Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
2
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
3
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
4
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages
Java supports dynamic compilation and automatic memory management (garbage collection).
5
Java Environment
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
6
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
7
JAVA SOURCE FILE
Simple Java Program
class Example
public static void main(String args[])
[Link](“hello”);
Class : Example Declares a class[Every must be placed inside a class]
Here , Class:Keyword, Example:identifier (specifies the name).
Main line:
main()-Starting point for the interpreter to start the execution of the program.
public: access specifier (making it reachable to all the other classes)
static: main must be declared as static; because the main interpreter uses this function
before any objects are created.
8
void-main :function does not return any value(but simply prints a few text to the screen).
All the parameters to a function are declared inside a pair of parenthesis.
String args[] declares a argument named args, which hold Array of objects of the type
string.
Output Line: println-function is a member of the out object,which is a static data field of
system class.
Println all the time appends a newline character to the close of the string.
This means that any following output will start on a new line.
Every java must close with a semi colon.
[Link] COMPILATION
The steps to execute java program
preparation of the program text
compilation of the program
execution of the compiled program
1. Preparation of the program text
To write the program text we need to write a file containing code. For a Java program, The
file name must be represented
[Link]
where ClassNameis the name of the class defined in the program. E.g.,[Link]
The program can be written by any program that allows one text file (editor). E.g., NotePad,
Emacs, ...
2. Compilation of the program
The compilation of the program is essential to convert the program into a sequence of
commands that can be openly executed by the computer. The standard Java compiler,
which is part of the Java Standard Development Kit (Java SDK), is javac. To make use of it,
you have to execute the following command:
javac [Link]
The compilation yields a file called [Link], which contains the command that can
9
be straight executed by the system. For example:
javac [Link]
creates the file [Link].
3. Execution of the compiled program
After compilation step, we have to execute the java [Link] Java the execution of a
program is done in following manner
java ClassName
public static void main(String args[]) and [Link]()
Public keyword is an access specifier. Static allows main() to be called without having
to instantiate a particular instance of class. Void does not return any value. Main() is
the method where java application [Link] args[] receives any command line
arguments during [Link] is a predefined class that provides access to the
system. Out is output stream connected to [Link] displays the output
Static Member
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods
You can create a static method by using the keyword static. Static methods can access only
static fields, methods. To access static methods there is no need to instantiate the class, you
can do it just using the class name as
Static Blocks
10
These are a block of codes with a static keyword. In general, these are used to initialize the
static members. JVM executes static blocks before the main method at the time of class
loading.
final in Java
In the program, there can be variables of various types. If there is a variable as int x=1; later
in the program, that variable value can be changed to some other value. A variable that is
declared as final and initialized with a value cannot be changed later in the program.
Example:1
11
Example:2
Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
12
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
13
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
14
Example:
Example to understand the types of variables in java
Another Example:
Java Comments
15
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Why do we use comments in a code?
o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the
alternative code.
Types of Java Comments
There are three types of comments in Java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
16
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.
Let's use single line comment in a Java program.
2) Java Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
17
Let's use multi-line comment in a Java program.
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation
comments are placed between /** and */.
18
Data Types
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
Primitive data types are variables permits us to store only one value but they not at all
allows us to store multiple values of similar type. This is a data type whose variable can
contain maximum one value at a time.
Example:
int a; // valid
a=10; // valid
a=10, 20, 30; // invalid
There are 8 types of primitive data types:
o boolean data type
o byte data type
o char data type
o short data type
19
o int data type
o long data type
o float data type
o double data type
Java Non-Primitive Data Types
It is Used to store multiple [Link] variables are produced using defined
constructors of the classes. They are used to contact objects. These variables are declared
to be of a particular type that cannot be changed. Class objects and various types of array
variables come below reference data type. Default value of any reference variable is null. A
reference variable can be used to refer any other object of the declared type or any
compatible type.
Objects and Arrays are the reference or non-primitive data types in Java. They are
so called since they are handled “by reference” i.e. variables of their kind store the address
of the object or array is stored in a variable. They are passed by reference.
For Ex:
char [] arr = { 'a', 'b', 'c', 'd' }; //'arr' stores the references for the 4 values
20
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.
Example:
21
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
Example:
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
22
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'
Simple Example for Primitive Data type:
public class PrimitiveDemo
public static void main(String[] args)
byte b =100;
short s =123;
int v = 123543;
int calc = -9876345;
long amountVal = 1234567891;
float intrestRate = 12.25f;
23
double sineVal = 12345.234d;
boolean flag = true;
booleanval = false;
char ch1 = 88; // code for X
char ch2 = 'Y';
[Link]("byte Value = "+ b);
[Link]("short Value = "+ s);
[Link]("int Value = "+ v);
[Link]("int second Value = "+ calc);
[Link]("long Value = "+ amountVal);
[Link]("float Value = "+ intrestRate);
[Link]("double Value = "+ sineVal);
[Link]("boolean Value = "+ flag);
[Link]("boolean Value = "+ val);
[Link]("char Value = "+ ch1);
[Link]("char Value = "+ ch2);
Output:
Operators
24
It is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
25
Java Unary Operator Example: ++ and --
Java Unary Operator Example 2: ++ and --
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
26
Java Arithmetic Operator Example
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
27
Java Left Shift Operator Example
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
Relational Operators in Java
Java has 6 relational operators.
28
1. == is the equality operator. This returns true if both the operands are referring to the same
object, otherwise false.
2. != is for non-equality operator. It returns true if both the operands are referring to the
different objects, otherwise false.
3. < is less than operator.
4. > is greater than operator.
5. <= is less than or equal to operator.
6. >= is greater than or equal to operator.
Example:
Output:
29
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
30
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
31
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
32
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
Java Assignment Operator Example
Control Statements
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
33
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
decision-making statements decide which statement to execute and when. Decision-making
statements evaluate the Boolean expression and control the program flow depending upon the
result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
Example:
34
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Example:
35
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
Example Program:
36
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable.
37
Syntax
Example program:
import [Link].*;
class Student
public static void main(String args[])
{ int num;
Scanner s=new Scanner([Link]);
[Link]("Enter the number:");
num=[Link]();
switch(num)
case 0: [Link]("Hello");
break;
case 1: [Link]("Welcome");
break;
default: [Link]("Welcome to java");
38
}
Output:
Enter the number
Welcome
Another Example:
class Student
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
39
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
Syntax
Example:
40
Output:
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable.
Syntax:
Example program:
41
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
Syntax:
42
Example:
43
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
Syntax
Flowchart:
44
public class Calculation {
public static void main(String[] args)
{
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
}
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
45
Jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
JAVA BREAK STATEMENT
The break statement is used to break the current flow of the program and transfer the control
to the next statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
public class BreakExample {
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
[Link](i);
if(i==6)
{
break;
}
}
}
}
JAVA CONTINUE STATEMENT
The continue statement doesn't break the loop, whereas, it skips the specific part of the loop
and jumps to the next iteration of the loop immediately.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i = 0; i<= 2; i++)
{
46
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
[Link](j);
}
}
}
Output:
CONSTRUCTORS
DEFINITION:
A constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
It is a special type of method which is used to initialize the object.
47
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
If there is no constructor in a class, compiler automatically creates a default
constructor.
What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
TYPES OF CONSTRUCTORS
no-arg constructor
parameterized constructor
RULES FOR CREATING JAVA CONSTRUCTOR
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
TYPES OF JAVA CONSTRUCTORS
There are two types of constructors in Java:
48
1. Default constructor (no-arg constructor)
2. Parameterized constructor
JAVA DEFAULT CONSTRUCTOR
DEFINITION
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
class Bike1{
Bike1()
{
[Link]("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Example of default constructor that displays the default
values
Example Program:
class Student4
{
int id;
49
String name;
id = i;
name = n;
}
void display(){[Link](id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}
50