0% found this document useful (0 votes)
25 views39 pages

Java NOTES IA-1-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also covers Java data types, operators, and arrays, detailing their characteristics and usage. Additionally, it explains the syntax for declaring and using single and multidimensional arrays, along with examples of various operators in Java.

Uploaded by

robog49037
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views39 pages

Java NOTES IA-1-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also covers Java data types, operators, and arrays, detailing their characteristics and usage. Additionally, it explains the syntax for declaring and using single and multidimensional arrays, along with examples of various operators in Java.

Uploaded by

robog49037
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Java OOPs Concepts

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Object

o 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.
o An Object can be defined as an instance of a class. An object contains an
address and takes up some space in memory. Objects can communicate
without knowing the details of each other's data or code. The only
necessary thing is the type of message accepted and the type of response
returned by the objects.
o Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.
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

When one object acquires all the properties and behaviors of a parent object, it
is known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For


example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve


polymorphism.

Another example can be to speak something; for example, a cat speaks meow,
dog barks woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

In Java, abstraction is achieved by interfaces and abstract classes. We can


achieve 100% abstraction using interfaces.
The abstract method contains only method declaration but not implementation.
Demonstration of Abstract class
Java
//abstract class
abstract class GFG{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.

//Encapsulation using private modifier

//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}
Different lexical issues in Java:

White space
free-form means we can write total code in a single line. like tab, space.
Identifiers
names used to classes, behaviors, variables.
uses numbers, dollar symbol, underscore, letters.
valid- Method, Addition1, run_any, $method.
invalid- 123.
Literals
A value of a corresponding variable.
example: 12,123.0.'r',"String".
Comments
the content ignored by the compiler which explains the operation of the
program.
single line comment- // for line by line description.
multi line comment- /* */ for 3-4 lines description.
Documentation comment- in html document like /** */.
Separators
terminate the statements.
()- Parentheses--- to arguments, control statements like if, while, for.
[]-Brackets---- to declare size of arrays.
{}-Braces--- to define methods ,classes, automatic initialization of arrays.
,- comma--- to declare variables, in for loop.
;- semicolon---terminates the statements.
.- Period-- for packages, sub packages, references to class.
::- Colons--- Used to create a method or constructor reference
Keywords
totally 50 are there which are cannot be used as variables, class names,
method names.
Libraries
Java has built in class libraries that contain methods for IO operations, GUI,
Networking, String handling etc which provides greater functionality to java.

DATA TYPES:
Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all test
cases. Java has two categories in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long,
float, and double. The Boolean with uppercase B is a wrapper class
for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String,
Array, etc.
Primitive Data Types in Java
Primitive data are only single values and have no special capabilities. There
are 8 primitive data types. They are depicted below in tabular format below as
follows:
Descripti Defau Siz Example
Type on lt e Literals Range of values

boolea true or 8
false true, false true, false
n false bits

twos-
8
compleme 0 (none) -128 to 127
bits
byte nt integer

‘a’, characters
Unicode \u000 16 ‘\u0041’, representation of
character 0 bits ‘\101’, ‘\\’, ASCII values
char ‘\’, ‘\n’, ‘β’ 0 to 255

twos-
16
compleme 0 (none) -32,768 to 32,767
bits
short nt integer

twos- -2,147,483,648
32
compleme 0 -2,-1,0,1,2 to
bits
int nt intger 2,147,483,647

-
9,223,372,036,854,775,
twos- -2L,-
64 808
compleme 0 1L,0L,1L,2
bits to
nt integer L
9,223,372,036,854,775,
long 807

IEEE 754 1.23e100f ,


32
floating 0.0 -1.23e-100f upto 7 decimal digits
bits
float point , .3f ,3.14F
Descripti Defau Siz Example
Type on lt e Literals Range of values

1.23456e30
IEEE 754
64 0d , -
floating 0.0 upto 16 decimal digits
bits 123456e-
point
double 300d , 1e1d
Non-Primitive (Reference) Data Types
The Non-Primitive (Reference) Data Types will contain a memory address
of variable values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities
2. Class
A class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access. Refer
to access specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized
by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-
life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State : It is represented by the attributes of an object. It also reflects
the properties of an object.
2. Behavior : It is represented by the methods of an object. It also
reflects the response of an object to other objects.
3. Identity : It gives a unique name to an object and enables one object
to interact with other objects.
4. Array
An Array is a group of like-typed variables that are referred to by a common
name. Arrays in Java work differently than they do in C/C++. The following
are some important points about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using
member length. This is different from C/C++ where we find length
using size.
• A Java array variable can also be declared like other variables with []
after the data type.
• The variables in the array are ordered and each has an index
beginning with 0.
• Java array can also be used as a static field, a local variable, or a
method parameter.
• The size of an array must be specified by an int value and not long or
short.
• The direct superclass of an array type is Object.
Java Arrays:
Normally, an array is a collection of similar type of elements which has
contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, the elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort


the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

• Single Dimensional Array


• Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix
form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Output:

123
245
445
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +,
-, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

postfix expr++ expr--


Unary
prefix ++expr --expr +expr -expr ~ !

multiplicative */%
Arithmetic
additive +-

Shift shift << >> >>>

comparison < > <= >= instanceof


Relational
equality == !=

Bitwise bitwise AND &


bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&


Logical
logical OR ||

Ternary ternary ?:

= += -= *= /= %= &= ^= |=
Assignment assignment
<<= >>= >>>=

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:

15
5
50
2
0

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

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:

14
16

Java Assignment Operator Example

public class OperatorExample{


public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:

13
9
18
9

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.

Syntax:
variable = Expression1 ? Expression2: Expression3

Java Ternary Operator Example

public class OperatorExample{


public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:

2
Another Example:

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:

Java Relational Operators are a bunch of binary operators used to check for
relations between two operands, including equality, greater than, less than, etc.
They return a boolean result after the comparison and are extensively used in
looping statements as well as conditional if-else statements and so on. The
general format of representing relational operator is:
Syntax:
variable1 relation_operator variable2
Let us look at each one of the relational operators in Java:
Operator 1: ‘Equal to’ operator (==)
This operator is used to check whether the two given operands are equal or
not. The operator returns true if the operand at the left-hand side is equal to the
right-hand side, else false.
Syntax:
var1 == var2
Example:
// Java Program to Illustrate equal to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 == var2: "
+ (var1 == var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 == var3: "
+ (var1 == var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
Operator 2: ‘Not equal to’ Operator(!=)
This operator is used to check whether the two given operands are equal or
not. It functions opposite to that of the equal-to-operator. It returns true if the
operand at the left-hand side is not equal to the right-hand side, else false.
Syntax:
var1 != var2
Example:
// Java Program to Illustrate No- equal-to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 != var2: "
+ (var1 != var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 != var3: "
+ (var1 != var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 != var2: true
var1 != var3: false
Operator 3: ‘Greater than’ operator(>)
This checks whether the first operand is greater than the second operand or
not. The operator returns true when the operand at the left-hand side is greater
than the right-hand side.
Syntax:
var1 > var2
Illustration:
var1 = 30
var2 = 20

var1 > var2 results in true


Example:
• Java

// Java code to Illustrate Greater than operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 30, var2 = 20, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 > var2: " + (var1 > var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var3 > var1: "
+ (var3 >= var1));
}
}
Output
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false
Operator 4: ‘Less than’ Operator(<)
This checks whether the first operand is less than the second operand or not.
The operator returns true when the operand at the left-hand side is less than the
right-hand side. It functions opposite to that of the greater-than operator.
Syntax:
var1 < var2
Illustration:
var1 = 10
var2 = 20

var1 < var2 results in true


Example:
• Java

// Java code to Illustrate Less than Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 20, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);
// Comparing var1 and var2 and
// printing corresponding boolean value
System.out.println("var1 < var2: " + (var1 < var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 < var3: " + (var2 < var3));
}
}
Output
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
Operator 5: Greater than or equal to (>=)
This checks whether the first operand is greater than or equal to the second
operand or not. The operator returns true when the operand at the left-hand
side is greater than or equal to the right-hand side.
Syntax:
var1 >= var2
Illustration:
var1 = 20
var2 = 20
var3 = 10

var1 >= var2 results in true


var2 >= var3 results in true
Example:
• Java

// Java Program to Illustrate Greater than or equal to


// Operator
// Importing I/O classes
import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 20, var2 = 20, var3 = 10;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 >= var2: "
+ (var1 >= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 >= var3: "
+ (var2 >= var3));
}
}
Output
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: true
Operator 6: Less than or equal to (<=)
This checks whether the first operand is less than or equal to the second
operand or not. The operator returns true when the operand at the left-hand
side is less than or equal to the right-hand side.
Syntax:
var1 <= var2
Illustration:
var1 = 10
var2 = 10
var3 = 9

var1 <= var2 results in true


var2 <= var3 results in false
Example:
• Java

// Java Program to Illustrate Less


// than or equal to operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 10, var3 = 9;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 <= var2: "
+ (var1 <= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 <= var3: "
+ (var2 <= var3));
}
}
Output
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false

program that implements all relational operators in Java for user input:

import java.util.Scanner;

public class RelationalOperators {


public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

//System.out.println("Enter first number: ");


// int num1 = scan.nextInt();

// System.out.println("Enter second number: ");


// int num2 = scan.nextInt();

int num1 =1;


int num2 = 2;

System.out.println("num1 > num2 is " + (num1 > num2));


System.out.println("num1 < num2 is " + (num1 < num2));
System.out.println("num1 >= num2 is " + (num1 >= num2));
System.out.println("num1 <= num2 is " + (num1 <= num2));
System.out.println("num1 == num2 is " + (num1 == num2));
System.out.println("num1 != num2 is " + (num1 != num2));
}
}
Output
num1 > num2 is false
num1 < num2 is true
num1 >= num2 is false
num1 <= num2 is true
num1 == num2 is false
num1 != num2 is true
Java Control Statements | Control Flow
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. 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.

if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the
java code.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20
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.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else {
statement 2; //executes when condition is false
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20

3.Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:

Delhi

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. However, it will also be a constant
value.
The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:

While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value. The
switch permits only int, string, and Enum type variables to be used.

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.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++. 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.

for(initialization, condition, increment/decrement) {


//block of statements
}
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for
loop in java.

public class Calculattion {


public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:

The sum of first 10 natural numbers is 55

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.

The syntax of the while loop is given below.


while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.

Consider the following example.

public class Calculation {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

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.

It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while


loop in Java.
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Java break statement:

As the name suggests, 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++) {
System.out.println(i);
if(i==6) {
break;
}
}
}

}
Output:

0
1
2
3
4
5
6

Java continue statement:

Unlike break 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.

Consider the following example to understand the functioning of the continue


statement in Java.

public class ContinueExample {

public static void main(String[] args) {


for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {
continue;
}
System.out.println(j);
}
}
}

}
Output:

0
1
2
3
5
1
2
3
5
2
3
5
Constructors in Java:
constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor
is called.

Rules for creating Java constructor

There are two rules defined for the 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:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor:

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
at the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:

Bike is created

Java Parameterized Constructor:

A constructor which has a specific number of parameters is called a parameterized


constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

111 Karan
222 Aryan

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method

A constructor is used to initialize the state A method is used to expose the behavior of
of an object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default


The method is not provided by the compiler
constructor if you don't have any
in any case.
constructor in a class.

The constructor name must be same as the The method name may or may not be same
class name. as the class name.

You might also like