Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Module in Cc103 Intermediate Programming Java

This document serves as an introduction to Java programming, covering its applications, basic syntax, and fundamental concepts such as variables, literals, and operators. It includes examples of a simple 'Hello, World!' program, variable creation, and various types of operators in Java. The course aims to provide an interactive learning experience, enabling students to write and execute Java code effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module in Cc103 Intermediate Programming Java

This document serves as an introduction to Java programming, covering its applications, basic syntax, and fundamental concepts such as variables, literals, and operators. It includes examples of a simple 'Hello, World!' program, variable creation, and various types of operators in Java. The course aims to provide an interactive learning experience, enabling students to write and execute Java code effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

MODULE IN

CC 103 –
INTERMEDIATE
PROGRAMMING

(JAVA)
Introduction to Java
Java is a popular general-purpose programming language with a wide range of applications.
It's used for developing mobile and desktop applications, big data processing, embedded
systems, and so on.

Being one of the older programming languages, Java still has a huge demand in the current
job market. Hence, it's safe to say that you cannot go wrong with learning Java.

This course is an introduction to Java programming in the most interactive way possible.
Here's how the learning process works:

1. Learn a concept.
2. Edit and run code related to it.
3. Practice what you have learned in real-time.

By the end, you'll write hundreds of programs and become comfortable writing code in
Java.

Java Hello World Program


A "Hello, World!" is a simple program that outputs Hello, World! on the screen.
Since it's a very simple program, it's often used to introduce a new
programming language to a newbie.
Let's explore how Java "Hello, World!" program works.

Note: You can use our online Java compiler to run Java programs.

Java "Hello, World!" Program

// Your First Program


class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output

Hello, World!

How Java "Hello, World!" Program Works?


1. // Your First Program

In Java, any line starting with // is a comment. Comments are intended


for users reading the code to understand the intent and functionality of
the program. It is completely ignored by the Java compiler (an
application that translates Java program to Java bytecode that computer
can execute). To learn more, visit Java comments.
2. class HelloWorld { ... }

In Java, every application begins with a class definition. In the


program, HelloWorld is the name of the class, and the class definition is:

3. class HelloWorld {

4. ... .. ...

}
For now, just remember that every Java application has a class
definition, and the name of the class should match the filename in Java.
5. public static void main(String[] args) { ... }

This is the main method. Every application in Java must contain the
main method. The Java compiler starts executing the code from the
main method.

How does it work? Good question. However, we will not discuss it in


this article. After all, it's a basic program to introduce Java programming
language to a newbie. We will learn the meaning of public , static , void ,

and how methods work? in later chapters.

For now, just remember that the main function is the entry point of your
Java application, and it's mandatory in a Java program. The signature of
the main method in Java is:

6. public static void main(String[] args) {

7. ... .. ...

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

The code above is a print statement. It prints the text Hello, World! to
standard output (your screen). The text inside the quotation marks is
called String in Java.
Notice the print statement is inside the main function, which is inside the
class definition.

Things to take away

• Every valid Java Application must have a class definition that matches
the filename (class name and file name should be same).

• The main method must be inside the class definition.

• The compiler executes the codes starting from the main function.

This is a valid Java program that does nothing.

public class HelloWorld {


public static void main(String[] args) {
// Write your code here
}
}

Don't worry if you don't understand the meaning of class , static , methods, and
so on for now. We will discuss it in detail in later chapters.
Java Variables and Literals
Java Variables
A variable is a location in memory (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name
(identifier). Learn more about Java identifiers.

Create Variables in Java

Here's how we create a variable in Java,

int speedLimit = 80;

Here, speedLimit is a variable of int data type and we have assigned value 80 to
it.
The int data type suggests that the variable can only hold integers. To learn
more, visit Java data types.
In the example, we have assigned value to the variable during declaration.
However, it's not mandatory.

You can declare variables and assign variables separately. For example,

int speedLimit;
speedLimit = 80;
Note: Java is a statically-typed language. It means that all variables must be
declared before they can be used.

Change values of variables

The value of a variable can be changed in the program, hence the


name variable. For example,

int speedLimit = 80;

... .. ...

speedLimit = 90;

Here, initially, the value of speedLimit is 80. Later, we changed it to 90.


However, we cannot change the data type of a variable in Java within the
same scope.

What is the variable scope?

Don't worry about it for now. Just remember that we can't do something like
this:

int speedLimit = 80;

... .. ...

float speedLimit;

To learn more, visit: Can I change declaration type for a variable in Java?
Rules for Naming Variables in Java
Java programming language has its own set of rules and conventions for
naming variables. Here's what you need to know:

• Java is case sensitive. Hence, age and AGE are two different variables.
For example,

• int age = 24;


• int AGE = 25;

• System.out.println(age); // prints 24

System.out.println(AGE); // prints 25

• Variables must start with either a letter or an underscore, _ or a dollar,


$ sign. For example,

• int age; // valid name and good practice


• int _age; // valid but bad practice

int $age; // valid but bad practice

• Variable names cannot start with numbers. For example,

int 1age; // invalid variables

• Variable names can't use whitespace. For example,


int my age; // invalid variables

Here, is we need to use variable names having more than one word,
use all lowercase letters for the first word and capitalize the first letter of
each subsequent word. For example, myAge .

• When creating variables, choose a name that makes sense. For


example, score , number , level makes more sense than variable names
such as s , n , and l .
• If you choose one-word variable names, use all lowercase letters. For
example, it's better to use speed rather than SPEED , or sPEED .

There are 4 types of variables in Java programming language:

• Instance Variables (Non-Static Fields)

• Class Variables (Static Fields)

• Local Variables

• Parameters

If you are interested to learn more about it now, visit Java Variable Types.

Java literals
Literals are data used for representing fixed values. They can be used directly
in the code. For example,

int a = 1;
float b = 2.5;
char c = 'F';

Here, 1 , 2.5 , and 'F' are literals.


Here are different types of literals in Java.

1. Boolean Literals

In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,

boolean flag1 = false;


boolean flag2 = true;

Here, false and true are two boolean literals.

2. Integer Literals

An integer literal is a numeric value(associated with numbers) without any


fractional or exponential part. There are 4 types of integer literals in Java:

1. binary (base 2)

2. decimal (base 10)

3. octal (base 8)

4. hexadecimal (base 16)


For example:

// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;

// decimal
int decNumber = 34;

// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary

In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts
with 0x.

Note: Integer literals are used to initialize variables of integer types


like byte , short , int , and long .

3. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponential form. For example,

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

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445*10^2
double myDoubleScientific = 3.445e2;
System.out.println(myDouble); // prints 3.4
System.out.println(myFloat); // prints 3.4
System.out.println(myDoubleScientific); // prints 344.5
}
}
Run Code

Note: The floating-point literals are used to initialize float and double type
variables.

4. Character Literals

Character literals are unicode character enclosed inside single quotes. For
example,

char letter = 'a';

Here, a is the character literal.


We can also use escape sequences as character literals. For
example, \b (backspace), \t (tab), \n (new line), etc.

5. String literals

A string literal is a sequence of characters enclosed inside double-quotes. For


example,

String str1 = "Java Programming";


String str2 = "Programiz";

Here, Java Programming and Programiz are two string literals.

Java Operators
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while * is also an operator used
for multiplication.
Operators in Java can be classified into 5 types:

1. Arithmetic Operators

2. Assignment Operators

3. Relational Operators

4. Logical Operators

5. Unary Operators

6. Bitwise Operators

1. Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables
and data. For example,

a + b;

Here, the + operator is used to add two variables a and b . Similarly, there are
various other arithmetic operators in Java.
Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


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

// declare variables
int a = 12, b = 5;

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Run Code

Output

a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2

In the above example, we have used + , - , and * operators to compute


addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a/b in our program. The / operator is the division operator.
If we use the division operator with two integers, then the resulting quotient
will also be an integer. And, if one of the operands is a floating-point number,
we will get the result will also be in floating-point.

In Java,

(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5

% Modulo Operator
The modulo operator % computes the remainder. When a=7 is divided by b=

4, the remainder is 3.

Note: The % operator is mainly used with integers.

2. Java Assignment Operators


Assignment operators are used in Java to assign values to variables. For
example,
int age;
age = 5;

Here, = is the assignment operator. It assigns the value on its right to the
variable on its left. That is, 5 is assigned to the variable age .

Let's see some more assignment operators available in Java.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example 2: Assignment Operators


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

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Run Code

Output

var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators


Relational operators are used to check the relationship between two
operands. For example,

// check if a is less than b


a < b;

Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false .

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false


<= Less Than or Equal To 3 <= 5 returns true

Example 3: Relational Operators


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

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}
Run Code

Note: Relational operators are used in decision making and loops.


4. Java Logical Operators
Logical operators are used to check whether an expression is true or false .

They are used in decision making.


Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and expression2 ar
AND) expression2 true

|| (Logical OR) expression1 || expression2 true if either expression1 or expression2 is true

! (Logical NOT) !expression true if expression is false and vice versa

Example 4: Logical Operators


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

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Run Code

Working of Program
• (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .

• (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .

• (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .

• (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .


• (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .

• !(5 == 3) returns true because 5 == 3 is false .

• !(5 > 3) returns false because 5>3 is true .

5. Java Unary Operators


Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:

Operator Meaning

+ Unary plus: not necessary to use since numbers are positive without using it

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Increment and Decrement Operators


Java also provides increment and decrement operators: ++ and -

- respectively. ++ increases the value of the operand by 1, while -- decrease it


by 1. For example,

int num = 5;

// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.

Example 5: Increment and Decrement Operators


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

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);

System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Run Code

Output

Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11

In the above program, we have used the ++ and -- operator as prefixes (++a,
--b). We can also use these operators as postfix (a++, b++).
There is a slight difference when these operators are used as prefix versus
when they are used as a postfix.

To learn more about these operators, visit increment and decrement


operators.

6. Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits.
For example,

Bitwise complement Operation of 35

35 = 00100011 (In Binary)

~ 00100011
________
11011100 = 220 (In decimal)

Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).
The various bitwise operators present in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND


^ Bitwise exclusive OR

These operators are not generally used in Java. To learn more, visit Java
Bitwise and Bit Shift Operators.

Other operators
Besides these operators, there are other additional operators in Java.

Java instanceof Operator

The instanceof operator checks whether an object is an instanceof a particular


class. For example,
class Main {
public static void main(String[] args) {

String str = "Programiz";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Run Code

Output

Is str an object of String? true

Here, str is an instance of the String class. Hence, the instanceof operator
returns true . To learn more, visit Java instanceof.
Java Ternary Operator

The ternary operator (conditional operator) is shorthand for the if-then-

else statement. For example,

variable = Expression ? expression1 : expression2

Here's how it works.

• If the Expression is true , expression1 is assigned to the variable .

• If the Expression is false , expression2 is assigned to the variable .

Let's see an example of a ternary operator.

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

int februaryDays = 29;


String result;

// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Run Code

Output

Leap year

In the above example, we have used the ternary operator to check if the year
is a leap year or not. To learn more, visit the Java ternary operator.
Now that you know about Java operators, it's time to know about the order in
which operators are evaluated. To learn more, visit Java Operator
Precedence.

Java Basic Input and Output


Java Output
In Java, you can simply use

System.out.println(); or

System.out.print(); or

System.out.printf();

to send output to standard output (screen).

Here,

• System is a class
• out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class , public , and static in
later chapters.
Let's take an example to output a line.

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

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


}
}
Run Code

Output:
Java programming is interesting.

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

Difference between println(), print() and printf()

• 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.
• printf() - It provides string formatting (similar to printf in C/C++
programming).

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");
}
}
Run Code

Output:

1. println
2. println
1. print 2. print

In the above example, we have shown the working of


the print() and println() methods. To learn about the printf() method, visit Java
printf().

Example: Printing Variables and Literals


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

Double number = -10.6;

System.out.println(5);
System.out.println(number);
}
}
Run Code

When you run the program, the output will be:

5
-10.6

Here, you can see that we have not used the quotation marks. It is because to
display integers, variables and so on, we don't use quotation marks.

Example: Print Concatenated Strings


class PrintVariables {
public static void main(String[] args) {
Double number = -10.6;

System.out.println("I am " + "awesome.");


System.out.println("Number = " + number);
}
}
Run Code

Output:

I am awesome.
Number = -10.6

In the above example, notice the line,

System.out.println("I am " + "awesome.");

Here, we have used the + operator to concatenate (join) the two strings: "I am

" and "awesome." .

And also, the line,

System.out.println("Number = " + number);

Here, first the value of variable number is evaluated. Then, the value is
concatenated to the string: "Number = " .

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;

To learn more about importing packages in Java, visit Java Import Packages.
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);

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


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

// closing the scanner object


input.close();
}
}
Run Code

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.

Note: We have used the close() method to close the object. It is recommended
to close the scanner object once the input is taken.

Example: Get float, double and String Input


import java.util.Scanner;

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

Scanner input = new Scanner(System.in);

// Getting float input


System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);

// Getting double input


System.out.print("Enter double: ");
double myDouble = input.nextDouble();
System.out.println("Double entered = " + myDouble);

// Getting String input


System.out.print("Enter text: ");
String myString = input.next();
System.out.println("Text entered = " + myString);
}
}
Run Code
Output:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!

As mentioned, there are other several ways to get input from the user. To
learn more about Scanner , visit Java Scanner.

Java Expressions, Statements and


Blocks
In previous chapters, we have used expressions, statements, and blocks
without much explaining about them. Now that you know about variables,
operators, and literals, it will be easier to understand these concepts.

Java Expressions
A Java expression consists of variables, operators, literals, and method calls.
To know more about method calls, visit Java methods. For example,

int score;
score = 90;

Here, score = 90 is an expression that returns an int . Consider another example,

Double a = 2.2, b = 3.4, result;


result = a + b - 3.4;

Here, a + b - 3.4 is an expression.

if (number1 == number2)
System.out.println("Number 1 is larger than number 2");

Here, number1 == number2 is an expression that returns a boolean value.


Similarly, "Number 1 is larger than number 2" is a string expression.

Java Statements
In Java, each statement is a complete unit of execution. For example,

int score = 9*5;

Here, we have a statement. The complete execution of this statement involves


multiplying integers 9 and 5 and then assigning the result to the variable score .

In the above statement, we have an expression 9 * 5. In Java, expressions are


part of statements.

Expression statements

We can convert an expression into a statement by terminating the expression


with a ; . These are known as expression statements. For example,

// expression
number = 10
// statement
number = 10;

In the above example, we have an expression number = 10 . Here, by adding a


semicolon ( ; ), we have converted the expression into a statement ( number =
10; ).

Consider another example,

// expression
++number
// statement
++number;

Similarly, ++number is an expression whereas ++number; is a statement.

Declaration Statements

In Java, declaration statements are used for declaring variables. For example,

Double tax = 9.5;

The statement above declares a variable tax which is initialized to 9.5 .

Note: There are control flow statements that are used in decision making and
looping in Java. You will learn about control flow statements in later chapters.

Java Blocks
A block is a group of statements (zero or more) that is enclosed in curly
braces { } . For example,
class Main {
public static void main(String[] args) {

String band = "Beatles";

if (band == "Beatles") { // start of block


System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}
Run Code

Output:

Hey Jude!

In the above example, we have a block if {....} .

Here, inside the block we have two statements:

• System.out.print("Hey ");

• System.out.print("Jude!");

However, a block may not have any statements. Consider the following
examples,

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

if (10 > 5) { // start of block

} // end of block
}
}
Run Code
This is a valid Java program. Here, we have a block if {...} . However, there is
no any statement inside this block.
class AssignmentOperator {
public static void main(String[] args) { // start of block

} // end of block
}
Run Code

Here, we have block public static void main() {...} . However, similar to the above
example, this block does not have any statement.

ava Comments
In computer programming, comments are a portion of the program that are
completely ignored by Java compilers. They are mainly used to help
programmers to understand the code. For example,

// declare and initialize two variables


int a =1;
int b = 3;

// print the output


System.out.println("This is output");

Here, we have used the following comments,

• declare and initialize two variables

• print the output

Types of Comments in Java


In Java, there are two types of comments:

• single-line comment

• multi-line comment

Single-line Comment

A single-line comment starts and ends in the same line. To write a single-line
comment, we can use the // symbol. For example,
// "Hello, World!" program example

class Main {
public static void main(String[] args) {
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}
Run Code

Output:

Hello, World!

Here, we have used two single-line comments:

• "Hello, World!" program example

• prints "Hello World!"

The Java compiler ignores everything from // to the end of line. Hence, it is
also known as End of Line comment.
Multi-line Comment

When we want to write comments in multiple lines, we can use the multi-line
comment. To write multi-line comments, we can use the /*....*/ symbol. For
example,

/* This is an example of multi-line comment.


* The program prints "Hello, World!" to the standard output.
*/

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

System.out.println("Hello, World!");
}
}
Run Code

Output:

Hello, World!

Here, we have used the multi-line comment:

/* This is an example of multi-line comment.


* The program prints "Hello, World!" to the standard output.
*/

This type of comment is also known as Traditional Comment. In this type of


comment, the Java compiler ignores everything from /* to */ .

Use Comments the Right Way


One thing you should always consider that comments shouldn't be the
substitute for a way to explain poorly written code in English. You should
always write well structured and self explaining code. And, then use
comments.

Some believe that code should be self-describing and comments should be


rarely used. However, in my personal opinion, there is nothing wrong with
using comments. We can use comments to explain complex algorithms, regex
or scenarios where we have to choose one technique among different
technique to solve problems.

Note: In most cases, always use comments to explain 'why' rather than 'how'
and you are good to go.
Java if...else Statement
In programming, we use the if..else statement to run a block of code among
more than one alternatives.
For example, assigning grades (A, B, C) based on the percentage obtained by
a student.

• if the percentage is above 90, assign grade A


• if the percentage is above 75, assign grade B
• if the percentage is above 65, assign grade C

1. Java if (if-then) 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

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");


}
}
Run Code

Output

Statement outside if block

In the program, number < 0 is false . Hence, the code inside the body of
the if statement is skipped.
Note: If you want to learn more about about test conditions, visit Java
Relational Operators and Java Logical Operators.

We can also use Java Strings as the test condition.


Example 2: Java if with String
class Main {
public static void main(String[] args) {
// create a string variable
String language = "Java";

// if statement
if (language == "Java") {
System.out.println("Best Programming Language");
}
}
}
Run Code

Output

Best Programming Language

In the above example, we are comparing two strings in the if block.

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

How the if...else statement works?

Working of Java if-else statements


Example 3: 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");


}
}
Run Code

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.

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.

How the if...else...if ladder works?


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

Example 4: 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.");
}
}
}
Run Code

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.

Note: Java provides a special operator called ternary operator, which is a


kind of shorthand notation of if...else...if statement. To learn about the ternary
operator, visit Java Ternary Operator.

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 5: 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);


}
}
Run Code

Output:

Largest Number: 4.5

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


make this easier.

However, in real-world applications, these values may come from user input
data, log files, form submission, etc.
Java switch Statement
The switch statement allows us to execute a block of code among many
alternatives.
Syntax:

switch (expression) {

case value1:
// code
break;

case value2:
// code
break;

...
...

default:
// default statements
}

How does the switch-case statement work?


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

Note: The working of the switch-case statement is similar to the Java


if...else...if ladder. However, the syntax of the switch statement is cleaner and
much easier to read and write.
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:
size = "Unknown";
break;

}
System.out.println("Size: " + size);
}
}
Run Code
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 .

Also Read: Create a Simple Calculator Using the Java switch Statement

Flowchart of switch Statement


Flow chart of the Java
switch statement

break Statement in Java switch...case


Notice that we have been using break in each case block.

...
case 29:
size = "Small";
break;
...

The break statement is used to terminate the switch-case statement. If break is


not used, all the cases after the matching case are also executed. For
example,
class Main {
public static void main(String[] args) {

int expression = 2;

// switch statement to check size


switch (expression) {
case 1:
System.out.println("Case 1");

// matching case
case 2:
System.out.println("Case 2");

case 3:
System.out.println("Case 3");

default:
System.out.println("Default case");
}
}
}
Run Code

Output

Case 2
Case 3
Default case
In the above example, expression matches with case 2 . Here, we haven't used
the break statement after each case.
Hence, all the cases after case 2 are also executed.
This is why the break statement is needed to terminate the switch-
case statement after the matching case. To learn more, visit Java break
Statement.

default Case in Java switch-case


The switch statement also includes an optional default case. It is executed
when the expression doesn't match any of the cases. For example,
class Main {
public static void main(String[] args) {

int expression = 9;

switch(expression) {

case 2:
System.out.println("Small Size");
break;

case 3:
System.out.println("Large Size");
break;

// default case
default:
System.out.println("Unknown Size");
}
}
}
Run Code

Output
Unknown Size

In the above example, we have created a switch-case statement. Here, the


value of expression doesn't match with any of the cases.
Hence, the code inside the default case is executed.

default:
System.out.println("Unknown Size);

Note: The Java switch statement only works with:


• Primitive data types: byte, short, char, and int
• Enumerated types
• String Class
• Wrapper Classes: Character, Byte, Short, and Integer.

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

for-each Loop Sytnax


The syntax of the Java for-each loop is:

for(dataType item : array) {


...
}

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 1: Print Array Elements


// print array elements

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

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

// for each loop


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

Output

3
9
5
-5

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


the numbers array one by one.
• In the first iteration, item will be 3.
• In the second iteration, item will be 9.
• In the third iteration, item will be 5.
• In the fourth iteration, item will be -5.
Example 2: Sum of Array Elements
// Calculate the sum of all elements of an array

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

// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;

// iterating through each element of the array


for (int number: numbers) {
sum += number;
}

System.out.println("Sum = " + sum);


}
}
Run Code

Output:

Sum = 19

In the above program, the execution of the for each loop looks as:
Iteration Variables

number = 3
1
sum = 0 + 3 = 3

number = 4
2
sum = 3 + 4 = 7

number = 5
3
sum = 7 + 5 = 12
number = -5
4
sum = 12 + (-5) = 7

number = 0
5
sum = 7 + 0 = 7

number = 12
6
sum = 7 + 12 = 19

As we can see, we have added each element of the numbers array to


the sum variable in each iteration of the loop.

for loop Vs for-each loop


Let's see how a for-each loop is different from a regular Java for loop.
1. Using for loop
class Main {
public static void main(String[] args) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

// iterating through an array using a for loop


for (int i = 0; i < vowels.length; ++ i) {
System.out.println(vowels[i]);
}
}
}
Run Code

Output:

a
e
i
o
u

2. Using for-each Loop


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

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

// iterating through an array using the for-each loop


for (char item: vowels) {
System.out.println(item);
}
}
}
Run Code

Output:

a
e
i
o
u

Here, the output of both programs is the same. However, the for-each loop is
easier to write and understand.
This is why the for-each loop is preferred over the for loop when working with
arrays and collections.

Java while and do...while Loop


In computer programming, loops are used to repeat a block of code. For
example, if you want to show a message 100 times, then you can use a loop.
It's just a simple example; you can achieve much more with loops.

In the previous tutorial, you learned about Java for loop. Here, you are going
to learn about while and do...while loops.
Java 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 (testExpression) {
// body of loop
}

Here,

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


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

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


To learn more about the conditions, visit Java relational and logical operators.

Flowchart of while loop


Flowchart of Java while loop

Example 1: 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++;
}
}
}
Run Code

Output

1
2
3
4
5

Here is how this program works.

Iteration Variable Condition: i <= n Action

i=1 1 is printed.
1st true
n=5 i is increased to 2.

i=2 2 is printed.
2nd true
n=5 i is increased to 3.

i=3 3 is printed.
3rd true
n=5 i is increased to 4.

i=4 4 is printed.
4th true
n=5 i is increased to 5.

i=5 5 is printed.
5th true
n=5 i is increased to 6.

i=6
6th false The loop is terminated
n=5

Example 2: Sum of Positive Numbers Only


// Java program to find the sum of positive numbers
import java.util.Scanner;

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

int sum = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// take integer input from the user


System.out.println("Enter a number");
int number = input.nextInt();

// while loop continues


// until entered number is positive
while (number >= 0) {
// add only positive numbers
sum += number;

System.out.println("Enter a number");
number = input.nextInt();
}

System.out.println("Sum = " + sum);


input.close();
}
}
Run Code

Output

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
In the above program, we have used the Scanner class to take input from the
user. Here, nextInt() takes integer input from the user.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the
total sum is displayed.

Java 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. For example,

do {
// body of loop
} while(textExpression);

Here,

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


evaluated.
2. If the textExpression evaluates to true , the body of the loop inside
the do statement is executed again.
3. The textExpression is evaluated once again.
4. If the textExpression evaluates to true , the body of the loop inside
the do statement is executed again.
5. This process continues until the textExpression evaluates to false . Then
the loop stops.
Flowchart of do...while loop

Flowchart of Java do while loop

Let's see the working of do...while loop.


Example 3: 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);
}
}
Run Code

Output

1
2
3
4
5

Here is how this program works.

Iteration Variable Condition: i <= n Action

i=1 1 is printed.
not checked
n=5 i is increased to 2.

i=2 2 is printed.
1st true
n=5 i is increased to 3.

i=3 3 is printed.
2nd true
n=5 i is increased to 4.

i=4 4 is printed.
3rd true
n=5 i is increased to 5.

i=5 5 is printed.
4th true
n=5 i is increased to 6.

i=6
5th false The loop is terminated
n=5
Example 4: Sum of Positive Numbers
// Java program to find the sum of positive numbers
import java.util.Scanner;

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

int sum = 0;
int number = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// do...while loop continues


// until entered number is positive
do {
// add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
} while(number >= 0);

System.out.println("Sum = " + sum);


input.close();
}
}
Run Code

Output 1

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
Here, the user enters a positive number, that number is added to
the sum variable. And this process continues until the number is negative.
When the number is negative, the loop terminates and displays the sum
without adding the negative number.
Output 2

Enter a number
-8
Sum is 0

Here, the user enters a negative number. The test condition will be false but
the code inside of the loop executes once.

Infinite while loop

If the condition of a loop is always true , the loop runs for infinite times (until
the memory is full). For example,

// infinite while loop


while(true){
// body of loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop


int count = 1;
do {
// body of loop
} while(count == 1)

In the above programs, the textExpression is always true . Hence, the loop
body will run for infinite times.
for and while loops
The for loop is used when the number of iterations is known. For example,

for (let i = 1; i <=5; ++i) {


// body of loop
}

And while and do...while loops are generally used when the number of iterations
is unknown. For example,

while (condition) {
// body of loop
}

Java break Statement


While working with loops, it is sometimes desirable to skip some statements
inside the loop or terminate the loop immediately without checking the test
expression.

In such cases, break and continue statements are used. You will learn about
the Java continue statement in the next tutorial.

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;

How break statement works?

Working
of Java break Statement

Example 1: Java break statement


class Test {
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);
}
}
}
Run Code

Output:

1
2
3
4

In the above program, we are using the for loop to print the value of i in each
iteration. To know how for loop works, visit the Java for loop. Here, notice the
statement,

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.

Example 2: Java break statement

The program below calculates the sum of numbers entered by the user until
user enters a negative number.
To take input from the user, we have used the Scanner object. To learn more
about Scanner , visit Java Scanner.
import java.util.Scanner;

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

Double number, sum = 0.0;

// create an object of Scanner


Scanner input = new Scanner(System.in);

while (true) {
System.out.print("Enter a number: ");

// takes double input from user


number = input.nextDouble();

// if number is negative the loop terminates


if (number < 0.0) {
break;
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}
Run Code

Output:

Enter a number: 3.2


Enter a number: 5
Enter a number: 2.3
Enter a number: 0
Enter a number: -4.5
Sum = 10.5

In the above program, the test expression of the while loop is always true . Here,
notice the line,
if (number < 0.0) {
break;
}

This means when the user input negative numbers, the while loop is
terminated.

Java break and Nested Loop


In the case of nested loops, the break statement terminates the innermost loop.

Working of break Statement with Nested


Loops
Here, the break statement terminates the innermost while loop, and control
jumps to the outer loop.

Labeled break Statement


Till now, we have used the unlabeled break statement. It terminates the
innermost loop and switch statement. However, there is another form of break
statement in Java known as the labeled break.

We can use the labeled break statement to terminate the outermost loop as
well.

Working of the labeled break


statement in Java
As you can see in the above image, we have used the label identifier to specify
the outer loop. Now, notice how the break statement is used ( break label; ).
Here, the break statement is terminating the labeled statement (i.e. outer loop).
Then, the control of the program jumps to the statement after the labeled
statement.
Here's another example:

while (testExpression) {
// codes
second:
while (testExpression) {
// codes
while(testExpression) {
// codes
break second;
}
}
// control jumps here
}

In the above example, when the statement break second; is executed,


the while loop labeled as second is terminated. And, the control of the program
moves to the statement after the second while loop.

Example 3: labeled break Statement


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

// the for loop is labeled as first


first:
for( int i = 1; i < 5; i++) {

// the for loop is labeled as second


second:
for(int j = 1; j < 3; j ++ ) {
System.out.println("i = " + i + "; j = " +j);

// the break statement breaks the first for loop


if ( i == 2)
break first;
}
}
}
}
Run Code

Output:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
In the above example, the labeled break statement is used to terminate the loop
labeled as first. That is,

first:
for(int i = 1; i < 5; i++) {...}

Here, if we change the statement break first; to break second; the program will
behave differently. In this case, for loop labeled as second will be terminated.
For example,
class LabeledBreak {
public static void main(String[] args) {

// the for loop is labeled as first


first:
for( int i = 1; i < 5; i++) {

// the for loop is labeled as second


second:
for(int j = 1; j < 3; j ++ ) {

System.out.println("i = " + i + "; j = " +j);

// the break statement terminates the loop labeled as second


if ( i == 2)
break second;
}
}
}
}
Run Code

Output:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2
Note: The break statement is also used to terminate cases inside
the switch statement. To learn more, visit the Java switch statement.

Java continue Statement


While working with loops, sometimes you might want to skip some statements
or terminate the loop. In such cases, break and continue statements are used.
To learn about the break statement, visit Java break. Here, we will learn about
the continue statement.

Java continue
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;

Note: The continue statement is almost always used in decision-making


statements (if...else Statement).
Working of Java continue statement

Working
of Java continue Statement

Example 1: 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);
}
}
}
Run Code

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. To know how for loop works, visit Java for loop. Notice the statement,

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.

Example 2: Compute the sum of 5 positive numbers


import java.util.Scanner;

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

Double number, sum = 0.0;


// create an object of Scanner
Scanner input = new Scanner(System.in);

for (int i = 1; i < 6; ++i) {


System.out.print("Enter number " + i + " : ");
// takes input from the user
number = input.nextDouble();

// if number is negative
// continue statement is executed
if (number <= 0.0) {
continue;
}

sum += number;
}
System.out.println("Sum = " + sum);
input.close();
}
}
Run Code

Output:

Enter number 1: 2.2


Enter number 2: 5.6
Enter number 3: 0
Enter number 4: -2.4
Enter number 5: -3
Sum = 7.8

In the above example, we have used the for loop to print the sum of 5 positive
numbers. Notice the line,

if (number < 0.0) {


continue;
}
Here, when the user enters a negative number, the continue statement is
executed. This skips the current iteration of the loop and takes the program
control to the update expression of the loop.

Note: To take input from the user, we have used the Scanner object. To learn
more, visit Java Scanner.

Java continue with Nested Loop


In the case of nested loops in Java, the continue statement skips the current
iteration of the innermost loop.

Working of Java continue statement


with Nested Loops
Example 3: continue with Nested Loop
class Main {
public static void main(String[] args) {

int i = 1, j = 1;

// outer loop
while (i <= 3) {

System.out.println("Outer Loop: " + i);

// inner loop
while(j <= 3) {

if(j == 2) {
j++;
continue;
}

System.out.println("Inner Loop: " + j);


j++;
}
i++;
}
}
}
Run Code

Output

Outer Loop: 1
Inner Loop: 1
Inner Loop: 3
Outer Loop: 2
Outer Loop: 3

In the above example, we have used the nested while loop. Note that we have
used the continue statement inside the inner loop.

if(j == 2) {
j++;
continue:
}

Here, when the value of j is 2, the value of j is increased and


the continue statement is executed.
This skips the iteration of the inner loop. Hence, the text Inner Loop: 2 is skipped
from the output.

Labeled continue Statement


Till now, we have used the unlabeled continue statement. However, there is
another form of continue statement in Java known as labeled continue.
It includes the label of the loop along with the continue keyword. For example,

continue label;

Here, the continue statement skips the current iteration of the loop specified
by label .
Working of the Java labeled continue
Statement
We can see that the label identifier specifies the outer loop. Notice the use of
the continue inside the inner loop.

Here, the continue statement is skipping the current iteration of the labeled
statement (i.e. outer loop). Then, the program control goes to the next
iteration of the labeled statement.

Example 4: labeled continue Statement


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

// outer loop is labeled as first


first:
for (int i = 1; i < 6; ++i) {

// inner loop
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)

// skips the current iteration of outer loop


continue first;
System.out.println("i = " + i + "; j = " + j);
}
}
}
}
Run Code

Output:

i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1

In the above example, the labeled continue statement is used to skip the current
iteration of the loop labeled as first .

if (i==3 || j==2)
continue first;

Here, we can see the outermost for loop is labeled as first ,

first:
for (int i = 1; i < 6; ++i) {..}

Hence, the iteration of the outer for loop is skipped if the value of i is 3 or the
value of j is 2.

Note: The use of labeled continue is often discouraged as it makes your code
hard to understand. If you are in a situation where you have to use
labeled continue , refactor your code and try to solve it in a different way to
make it more readable.
Java Arrays
An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create
an array of the string type that can store 100 names.

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of
values in a Java array is always fixed.

How to 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];

How to 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


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 .

How to 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]);
System.out.println("Fifth Element: " + age[4]);
}
}
Run Code

Output

Accessing Elements of Array:


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

In the above example, notice that we are using the index number to access
each element of the array.

We can use loops to access all the elements of the array at once.

Looping Through Array Elements


In Java, we can also loop through each element of the array. For example,

Example: Using For Loop


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

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

// loop through the array


// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
Run Code

Output

Using for Loop:


12
4
5

In the above example, we are using the for Loop in Java to iterate through
each element of the array. Notice the expression inside the loop,

age.length

Here, we are using the length property of the array to get the size of the array.
We can also use the for-each loop to iterate through the elements of an array.
For example,
Example: Using the for-each Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};

// loop through the array


// using for loop
System.out.println("Using for-each Loop:");
for(int a : age) {
System.out.println(a);
}
}
}
Run Code

Output

Using for-each Loop:


12
4
5

Example: Compute Sum and Average of Array


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

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};


int sum = 0;
Double average;

// access all elements using for each loop


// add each element in sum
for (int number: numbers) {
sum += number;
}

// get the total number of elements


int arrayLength = numbers.length;

// calculate the average


// convert the average from int to double
average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);


System.out.println("Average = " + average);
}
}
Run Code

Output:

Sum = 36
Average = 3.6

In the above example, we have created an array of named numbers . We have


used the for...each loop to access each element of the array.
Inside the loop, we are calculating the sum of each element. Notice the line,

int arrayLength = number.length;

Here, we are using the length attribute of the array to calculate the size of the
array. We then calculate the average using:

average = ((double)sum / (double)arrayLength);

As you can see, we are converting the int value into double . This is called type
casting in Java. To learn more about typecasting, visit Java Type Casting.

Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays.
However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a


multidimensional array is an array itself. For example,

double[][] matrix = {{1.2, 4.3, 4.0},


{4.1, -1.1}
};

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


dimensional array. To learn more, visit the Java multidimensional array.

Java Multidimensional Arrays


Before we learn about the multidimensional array, make sure you know
about Java 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,
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 .

How to 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},
};

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.

Initialization of 2-dimensional
Array
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);
}
}
Run Code
Output:

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

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).
Here, we are using the length attribute to calculate the length of each row.

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]);
}
}
}
}
Run Code

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,
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);
}
}
}
}
Run Code

Output:

-2

-4

-5

6
9

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.

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

// 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);
}
}
}
}
}
Run Code

Output:

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

Java Copy Arrays


In Java, we can copy one array into another. There are several techniques
you can use to copy arrays in Java.

1. Copying Arrays Using Assignment Operator


Let's take an example,

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

int [] numbers = {1, 2, 3, 4, 5, 6};


int [] positiveNumbers = numbers; // copying arrays

for (int number: positiveNumbers) {


System.out.print(number + ", ");
}
}
}
Run Code

Output:

1, 2, 3, 4, 5, 6

In the above example, we have used the assignment operator ( = ) to copy an


array named numbers to another array named positiveNumbers .

This technique is the easiest one and it works as well. However, there is a
problem with this technique. If we change elements of one array,
corresponding elements of the other arrays also change. For example,
class Main {
public static void main(String[] args) {

int [] numbers = {1, 2, 3, 4, 5, 6};


int [] positiveNumbers = numbers; // copying arrays

// change value of first array


numbers[0] = -1;

// printing the second array


for (int number: positiveNumbers) {
System.out.print(number + ", ");
}
}
}
Run Code

Output:

-1, 2, 3, 4, 5, 6

Here, we can see that we have changed one value of the numbers array. When
we print the positiveNumbers array, we can see that the same value is also
changed.
It's because both arrays refer to the same array object. This is because of the
shallow copy. To learn more about shallow copy, visit shallow copy.
Now, to make new array objects while copying the arrays, we need deep copy
rather than a shallow copy.

2. Using Looping Construct to Copy Arrays


Let's take an example:

import java.util.Arrays;
class Main {
public static void main(String[] args) {

int [] source = {1, 2, 3, 4, 5, 6};


int [] destination = new int[6];

// iterate and copy elements from source to destination


for (int i = 0; i < source.length; ++i) {
destination[i] = source[i];
}

// converting array to string


System.out.println(Arrays.toString(destination));
}
}
Run Code

Output:

[1, 2, 3, 4, 5, 6]

In the above example, we have used the for loop to iterate through each
element of the source array. In each iteration, we are copying elements from
the source array to the destination array.
Here, the source and destination array refer to different objects (deep copy).
Hence, if elements of one array are changed, corresponding elements of
another array is unchanged.

Notice the statement,

System.out.println(Arrays.toString(destination));

Here, the toString() method is used to convert an array into a string. To learn
more, visit the toString() method (official Java documentation).
3. Copying Arrays Using arraycopy() method
In Java, the System class contains a method named arraycopy() to copy arrays.
This method is a better approach to copy arrays than the above two.
The arraycopy() method allows you to copy a specified portion of the source
array to the destination array. For example,

arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

Here,

• src - source array you want to copy


• srcPos - starting position (index) in the source array
• dest - destination array where elements will be copied from the source
• destPos - starting position (index) in the destination array
• length - number of elements to copy
Let's take an example:

// To use Arrays.toString() method


import java.util.Arrays;

class Main {
public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2};

int[] n3 = new int[5];

// Creating n2 array of having length of n1 array


int[] n2 = new int[n1.length];

// copying entire n1 array to n2


System.arraycopy(n1, 0, n2, 0, n1.length);
System.out.println("n2 = " + Arrays.toString(n2));

// copying elements from index 2 on n1 array


// copying element to index 1 of n3 array
// 2 elements will be copied
System.arraycopy(n1, 2, n3, 1, 2);
System.out.println("n3 = " + Arrays.toString(n3));
}
}
Run Code

Output:

n2 = [2, 3, 12, 4, 12, -2]


n3 = [0, 12, 4, 0, 0]

In the above example, we have used the arraycopy() method,


• System.arraycopy(n1, 0, n2, 0, n1.length) - entire elements from the n1 array are
copied to n2 array
• System.arraycopy(n1, 2, n3, 1, 2) - 2 elements of the n1 array starting from
index 2 are copied to the index starting from 1 of the n3 array
As you can see, the default initial value of elements of an int type array is 0.

4. Copying Arrays Using copyOfRange() method


We can also use the copyOfRange() method defined in Java Arrays class to
copy arrays. For example,
// To use toString() and copyOfRange() method
import java.util.Arrays;

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

int[] source = {2, 3, 12, 4, 12, -2};

// copying entire source array to destination


int[] destination1 = Arrays.copyOfRange(source, 0, source.length);
System.out.println("destination1 = " + Arrays.toString(destination1));

// copying from index 2 to 5 (5 is not included)


int[] destination2 = Arrays.copyOfRange(source, 2, 5);
System.out.println("destination2 = " + Arrays.toString(destination2));
}
}
Run Code

Output

destination1 = [2, 3, 12, 4, 12, -2]


destination2 = [12, 4, 12]

In the above example, notice the line,

int[] destination1 = Arrays.copyOfRange(source, 0, source.length);

Here, we can see that we are creating the destination1 array and copying
the source array to it at the same time. We are not creating the destination1 array
before calling the copyOfRange() method. To learn more about the method,
visit Java copyOfRange.

5. Copying 2d Arrays Using Loop


Similar to the single-dimensional array, we can also copy the 2-dimensional
array using the for loop. For example,
import java.util.Arrays;

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

int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new int[source.length][];


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

// allocating space for each row of destination array


destination[i] = new int[source[i].length];

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


destination[i][j] = source[i][j];
}
}

// displaying destination array


System.out.println(Arrays.deepToString(destination));

}
}
Run Code

Output:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

In the above program, notice the line,

System.out.println(Arrays.deepToString(destination);

Here, the deepToString() method is used to provide a better representation of the


2-dimensional array. To learn more, visit Java deepToString().

Copying 2d Arrays using arraycopy()


To make the above code more simpler, we can replace the inner loop
with System.arraycopy() as in the case of a single-dimensional array. For
example,
import java.util.Arrays;
class Main {
public static void main(String[] args) {

int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new int[source.length][];

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

// allocating space for each row of destination array


destination[i] = new int[source[i].length];
System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);
}

// displaying destination array


System.out.println(Arrays.deepToString(destination));
}
}
Run Code

Output:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

Here, we can see that we get the same output by replacing the inner for loop
with the arraycopy() method.

You might also like