Module in Cc103 Intermediate Programming Java
Module in Cc103 Intermediate Programming Java
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.
Note: You can use our online Java compiler to run Java programs.
Output
Hello, World!
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.
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:
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.
• Every valid Java Application must have a class definition that matches
the filename (class name and file name should be same).
• The compiler executes the codes starting from the main function.
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.
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.
... .. ...
speedLimit = 90;
Don't worry about it for now. Just remember that we can't do something like
this:
... .. ...
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,
System.out.println(AGE); // prints 25
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 .
• 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';
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,
2. Integer Literals
1. binary (base 2)
3. octal (base 8)
// 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.
3. Floating-point Literals
class Main {
public static void main(String[] args) {
// 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,
5. 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
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
// 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 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.
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 .
= 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;
// create variables
int a = 4;
int var;
Output
var using =: 4
var using +=: 8
var using *=: 32
Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false .
// 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
&& (Logical expression1 && true only if both expression1 and expression2 ar
AND) expression2 true
// && 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 .
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
int num = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
// 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);
// 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.
~ 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
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.
Output
Here, str is an instance of the String class. Hence, the instanceof operator
returns true . To learn more, visit Java instanceof.
Java Ternary Operator
class Java {
public static void main(String[] args) {
// 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.
System.out.println(); or
System.out.print(); or
System.out.printf();
Here,
• System is a class
• out is a public static field: it accepts output data.
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) {
Output:
Java programming is interesting.
Output:
1. println
2. println
1. print 2. print
System.out.println(5);
System.out.println(number);
}
}
Run Code
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.
Output:
I am awesome.
Number = -10.6
Here, we have used the + operator to concatenate (join) the two strings: "I am
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.
class Input {
public static void main(String[] args) {
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.
class Input {
public static void main(String[] args) {
As mentioned, there are other several ways to get input from the user. To
learn more about Scanner , visit Java Scanner.
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;
if (number1 == number2)
System.out.println("Number 1 is larger than number 2");
Java Statements
In Java, each statement is a complete unit of execution. For example,
Expression statements
// expression
number = 10
// statement
number = 10;
// expression
++number
// statement
++number;
Declaration Statements
In Java, declaration statements are used for declaring variables. For example,
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) {
Output:
Hey Jude!
• 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) {
} // 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,
• 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!
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,
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Run Code
Output:
Hello, World!
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 (condition) {
// statements
}
Output
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.
// if statement
if (language == "Java") {
System.out.println("Best Programming Language");
}
}
}
Run Code
Output
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 .
Output
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 .
If we run the program with the new value of number , the output will be:
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.
int number = 0;
Output
The number is 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.
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
Output:
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
}
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
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;
Also Read: Create a Simple Calculator Using the Java switch Statement
...
case 29:
size = "Small";
break;
...
int expression = 2;
// 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.
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
default:
System.out.println("Unknown Size);
Here,
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
Output
3
9
5
-5
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
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
Output:
a
e
i
o
u
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.
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,
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
Output
1
2
3
4
5
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
class Main {
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter a number");
number = input.nextInt();
}
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.
do {
// body of loop
} while(textExpression);
Here,
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
Output
1
2
3
4
5
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;
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.
If the condition of a loop is always true , the loop runs for infinite times (until
the memory is full). For example,
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,
And while and do...while loops are generally used when the number of iterations
is unknown. For example,
while (condition) {
// body of loop
}
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;
Working
of Java break Statement
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.
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) {
while (true) {
System.out.print("Enter a number: ");
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Run Code
Output:
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.
We can use the labeled break statement to terminate the outermost loop as
well.
while (testExpression) {
// codes
second:
while (testExpression) {
// codes
while(testExpression) {
// codes
break second;
}
}
// control jumps here
}
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) {
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
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;
Working
of Java continue Statement
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
9
10
In the above program, we are using the for loop to print the value of i in each
iteration. To know how for loop works, visit Java for loop. Notice the statement,
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.
class Main {
public static void main(String[] args) {
// 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:
In the above example, we have used the for loop to print the sum of 5 positive
numbers. Notice the line,
Note: To take input from the user, we have used the Scanner object. To learn
more, visit Java Scanner.
int i = 1, j = 1;
// outer loop
while (i <= 3) {
// inner loop
while(j <= 3) {
if(j == 2) {
j++;
continue;
}
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:
}
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.
// inner loop
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)
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;
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.
Here, the above array cannot store more than 100 names. The number of
values in a Java array is always fixed.
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;
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or
length of the array is 10.
In Java, we can declare and allocate the memory of an array in one single
statement. For example,
Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java,
using the index number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
• If the size of an array is n , then the last element of the array will be at
index n-1 .
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
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.
// create an array
int[] age = {12, 4, 5};
Output
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};
Output
Output:
Sum = 36
Average = 3.6
Here, we are using the length attribute of the array to calculate the size of the
array. We then calculate the average using:
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.
Let's take another example of the multidimensional array. This time we will be
creating a 3-dimensional array. For example,
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
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},
};
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
Output:
1
-2
3
-4
-5
6
9
7
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
Output:
-2
-4
-5
6
9
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
class Main {
public static void main(String[] args) {
Output:
1, 2, 3, 4, 5, 6
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) {
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.
import java.util.Arrays;
class Main {
public static void main(String[] args) {
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.
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,
Here,
class Main {
public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2};
Output:
class ArraysCopy {
public static void main(String[] args) {
Output
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.
class Main {
public static void main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
}
}
Run Code
Output:
System.out.println(Arrays.deepToString(destination);
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
Output:
Here, we can see that we get the same output by replacing the inner for loop
with the arraycopy() method.