The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Vinit Kapoor, 2020-07-10 11:58:41

Java Programming

Java Programming

4.5Logical Operators

The logical operators || (conditional-OR) and && (conditional-AND) operate on
boolean expressions. Here's how they work.

Operator Description Example

|| conditional-OR: true if either of the boolean expression is true false ||
true is evaluated to true

&& conditional-AND: true if all boolean expressions are true false && true is
evaluated to false

Example 8: Logical Operators

class LogicalOperator {

public static void main(String[] args) {

int number1 = 1, number2 = 2, number3 = 9;

boolean result;

// At least one expression needs to be true for the result to be true

result = (number1 > number2) || (number3 > number1);

// result will be true because (number1 > number2) is true

System.out.println(result);

// All expression must be true from result to be true

result = (number1 > number2) && (number3 > number1);

// result will be false because (number3 > number1) is false

System.out.println(result);

}

}

4.6 Bitwise and Bit Shift Operators

To perform bitwise and bit shift operators in Java, these operators are used.

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

| Bitwise inclusive OR

4.7 Ternary Operator

Bitwise and Bit Shift Operators

To perform bitwise and bit shift operators in Java, these operators are used.Ternary
Operator

The conditional operator or ternary operator ?: is shorthand for the if-then-else
statement. The syntax of the conditional operator is:

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.

Example 9: Ternary Operator

class ConditionalOperator {

public static void main(String[] args) {

int februaryDays = 29;

String result;

result = (februaryDays == 28) ? "Not a leap year" : "Leap year";

System.out.println(result);

}

}

4.8 instanceof Operator
In addition to relational operators, there is also a type comparison operator
instanceof which compares an object to a specified type. For example,
Example 7: instanceof Operator
Here's an example of instanceof operator.
class instanceofOperator {

public static void main(String[] args) {
String test = "asdf";
boolean result;
result = test instanceof String;
System.out.println("Is test an object of String? " + result);

}
}
Output:
Is test an object of String? True

4.Conditional statement

4.1 If
Java if (if-then) Statement
In Java, the syntax of the if-then statement is:
if (expression) {

// statements
}
Here expression is a boolean expression. A boolean expression returns either true or
false.
if the expression is evaluated to true, statement(s) inside the body of if (statements
inside parenthesis) are executed
if the expression is evaluated to false, statement(s) inside the body of if are skipped
from execution
How if statement works?

Example 1: Java if Statement
class IfStatement {

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.");
}
System.out.println("This statement is always executed.");
}
}
Output:
The number is positive.
This statement is always executed.
In the above example, we have a variable named number. Here, the test expression
checks if the number is greater than 0 (number > 0).
Since the number is greater than 0. So 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 above program with the new value of the number, the output will be:
This statement is always executed.
Here, the value of number is less than 0. So, the test expression number > 0
evaluates to false. Hence, the body of if is executed.
4.2 If else
Example 1: Java if Statement
class IfStatement {
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.");
}
System.out.println("This statement is always executed.");

}
}
Output:
The number is positive.
This statement is always executed.
In the above example, we have a variable named number. Here, the test expression
checks if the number is greater than 0 (number > 0).
Since the number is greater than 0. So 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 above program with the new value of the number, the output will be:
This statement is always executed.
Here, the value of number is less than 0. So, the test expression number > 0
evaluates to false. Hence, the body of if is executed.

4.3 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 (expression1) {

// codes

}
else if(expression2) {

// codes
}
else if (expression3) {

// codes
}
.
.
else {

// codes
}
Here, if statements are executed from the top towards the bottom. As soon as the
test expression is true, codes inside the body of that the if statement is executed.
Then, the control of the program jumps outside the if-else-if ladder.
If all test expressions are false, codes inside the body of else is executed.
Example 3: Java if..else..if Statement
class Ladder {

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

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

}
}
}
Output:
The number is 0.
In the above example, we are checking whether the number is positive, negative or
zero. Here, we have two test expressions:
number > 0 - checks if the number is greater than 0
number < 0 - checks if the number is less than 0
Here, the value of number is 0. So both the test expression evaluates to false. Hence
the statement inside the body of else is executed.
4.4 Nested if..else Statement
In Java, it is also possible to if..else statements inside a if..else statement. It's called
nested if...else statement.
Here's a program to find largest of 3 numbers:
Example 4: Nested if...else Statement
class Number {
public static void main(String[] args) {

// declaring double type variables
Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
// 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) {

largestNumber = n1;

}

else {
largestNumber = n3;

}
}
else {

// if..else statement inside else block
// checks if n2 is greater than or equal to n3
if (n2 >= n3) {

largestNumber = n2;
}
else {

largestNumber = n3;
}
}
System.out.println("The largest number is " + largestNumber);
}
}
Output:
The largest number is 4.5
4.5 Switch statement
In Java, we have used the if..else..if ladder to execute a block of code among
multiple blocks. However, the syntax of if...else...if ladders are too long.
Hence, we can use the switch statement as a substitute for long if...else...if ladders.
The use of switch statements makes our code more readable.
The syntax of the switch statement is:
switch (variable/expression) {

case value1:
// statements of case1
break;

case value2:
// statements of case2
break;
.. .. ...
.. .. ...

default:
// default statements

}
The switch statement evaluates the expression (mostly variable) and compares it
with values (can be expressions) of each case label.

Now, if the value matches a certain case label, then all the statements of the
matching case label are executed.
For example, if the variable/expression is equal to value2. In this case, all statements
of that matching case (statements of case2) are executed.
Notice, the use of break statements in each case. The break statement is used to
terminate the execution of the switch statement.
It is important because if break is not used all the statements after the matching case
are executed in sequence until the end of the switch statement.

Flowchart of switch Statement

Example 1: Java switch statement
class Main {

public static void main(String[] args) {
int week = 4;
String day;
// switch statement to check day
switch (week) {

case 1:
day = "Sunday";
break;

case 2:
day = "Monday";
break;

case 3:
day = "Tuesday";
break;

// match the value of week
case 4:

day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println("The day is " + day);

}
}

Output:
The day is Wednesday
Example 2: Making Calculator using the switch statement
The program below takes three inputs from the user: one operator and 2 numbers.
Based on the operator provided by the user, it performs the calculation on the
numbers. Then the result is displayed on the screen.
Before you go through the program, make sure you know about Java Scanner to
take input from the user.
import java.util.Scanner;
class Main {

public static void main(String[] args) {
char operator;
Double number1, number2, result;
// create an object of Scanner class
Scanner scanner = new Scanner(System.in);
System.out.print("Enter operator (either +, -, * or /): ");
// ask user to enter operator
operator = scanner.next().charAt(0);
System.out.print("Enter number1 and number2 respectively: ");
// ask user to enter numbers
number1 = scanner.nextDouble();
number2 = scanner.nextDouble();
switch (operator) {
// performs addition between numbers
case '+':

result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;

// performs subtraction between numbers
case '-':

result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break;

// performs multiplication between numbers
case '*':

result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;

// performs division between numbers
case '/':

result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;

}
}

}

5.Loops

5.1 for loop
Java for Loop
The syntax of for Loop in Java is:
for (initialization; testExpression; update)
{

// codes inside for loop's body
}
Working of for loop
The initialization expression is executed only once.
Then, the test expression is evaluated. Here, test expression is a boolean
expression.
If the test expression is evaluated to true,
Codes inside the body of for loop is executed.
Then the update expression is executed.
Again, the test expression is evaluated.
If the test expression is true, codes inside the body of for loop is executed and
update expression is executed.
This process goes on until the test expression is evaluated to false.
If the test expression is evaluated to false, for loop terminates.

for Loop Flowchart

Example 1: for Loop
// Program to print a sentence 10 times
class Loop {

public static void main(String[] args) {
for (int i = 1; i <= 10; ++i) {
System.out.println("Line " + i);
}

}
}
Output
Line 1
Line 2

Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
In the above example, we have
initialization expression: int i = 1.e
test expression: i <=10
update expression: ++i
Here, initially, the value of i is 1. So the test expression evaluates to true for the first
time. Hence, the print statement is executed. Now the update expression is
evaluated.
Each time the update expression is evaluated, the value of i is increased by 1. Again,
the test expression is evaluated. And, the same process is repeated.
This process goes on until i is 11. When i is 11, the test expression (i <= 10) is false
and the for loop terminates.
To learn more about test expression and how it is evaluated, visit relational and
logical operators.
Example 2: for Loop
// Program to find the sum of natural numbers from 1 to 1000.
class Number {

public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; ++i) {
sum += i; // sum = sum + i
}

System.out.println("Sum = " + sum);
}
}
Output:
Sum = 500500
6.2 For each loop
Difference between for loop and for-each loop
To know why the for-each loop is preferred over for loop while working with arrays, let's see
the following example.
Here the example shows how we can iterate through elements of an array using the
standard for loop.
class ForLoop {
public static void main(String[] args) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < vowels.length; ++ i) {

System.out.println(vowels[i]);
}
}
}
Output:
a
e
i
o
u
Now we will perform the same task using the for-each loop.
class AssignmentOperator {
public static void main(String[] args) {

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

// foreach loop
for (char item: vowels) {

System.out.println(item);
}
}
}
Output:
a
e
i
o
u
Here, we can see that the output of both the program is the same.
When we carefully analyze both the program, we can notice that the for-each loop is easier
to write and makes our code more readable. This is the reason it is called enhanced for loop.
Hence, it is recommended to use the enhanced for loop over the standard for loop whenever
possible.
Let's first look at the syntax of for each loop:
for(data_type item : collections) {
...
}
Here,
collection - a collection or array that you have to loop through.
item - a single item from the collections.
How for-each loop works?
Here's how the for-each loop works in Java. For each iteration, the for-each loop
iterates through each item in given collections or arrays (collections),
stores each item in a variable (item)
and executes the body of the loop.

Let's make it clear through an example.
Example: for-each loop
The program below calculates the sum of all elements of an integer array.
class EnhancedForLoop {

public static void main(String[] args) {
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);

}
}
Output:
Sum = 19
In the above program, the execution of the for-each loop looks as:
Iteration Value
1 number = 3 and sum = 0 + 3 = 3
2 number = 4 and sum = 3 + 4 = 7
3 number = 5 and sum = 7 + 5 = 12
4 number = -5 and sum = 12 + (-5) = 7
5 number = 0 and sum = 7 + 0 = 7
6 number = 12 and sum = 7 + 12 = 19
You can see during each iteration, the for-each loop
iterates through each element in the numbers array
stores it in the number variable
and executes the body, i.e. adds the number to sum

6.3 while loop
The syntax of while loop in Java is:
while (testExpression) {

// codes inside the body of while loop
}
How while loop works?
In the above syntax, the test expression inside parenthesis is a boolean expression. If the
test expression is evaluated to true,
statements inside the while loop are executed.
then, the test expression is evaluated again.
This process goes on until the test expression is evaluated to false. If the test expression is
evaluated to false,
the while loop is terminated.
Flowchart of while Loop

Example 1: while Loop
// Program to print line 10 times
class Loop {

public static void main(String[] args) {
int i = 1;

while (i <= 10) {
System.out.println("Line " + i);
++i;

}
}
}
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
In the above example, we have a test expression (i <= 10). It checks whether the value of i is
less than or equal to 10.
Here initially, the value of i is 1. So the test expression evaluates to true for the first time.
Hence, the print statement inside while loop is executed.
Inside while loop notice the statement
++i;
This statement increases the value of i by 1 in each iteration. After 10 iterations, the value of
i will be 11. Then, the test expression (i <= 10) evaluates to false and while loop terminates.
To learn more about test expression and how it is evaluated, visit Java Relational Operator
and Java Logical Operator.
Example 2: Java while Loop
// Program to find the sum of natural numbers from 1 to 100.
class AssignmentOperator {

public static void main(String[] args) {
int sum = 0, i = 100;
while (i != 0) {
sum += i; // sum = sum + i;
--i;
}
System.out.println("Sum = " + sum);

}
}
Output:
Sum = 5050
Here, we have two variables named sum and i whose initial values are 0 and 100
respectively.
In each iteration of the while loop,
the sum variable is assigned value: sum + i
the value of i is decreased by 1
6.4 Do while loop
The do...while loop is similar to while loop with one key difference. The body of
do...while loop is executed for once before the test expression is checked.
Here is the syntax of the do...while loop.
do {

// codes inside body of do while loop
} while (testExpression);
How do...while loop works?
The body of do...while loop is executed once (before checking the test expression).
Only then, the test expression is checked.
If the test expression is evaluated to true, codes inside the body of the loop are
executed, and the test expression is evaluated again. This process goes on until the
test expression is evaluated to false.
When the test expression is false, the do..while loop terminates.

Flowchart of do...while Loop

Example 3: do...while Loop
The program below calculates the sum of numbers entered by the user until user
enters 0.

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

public static void main(String[] args) {
Double number, sum = 0.0;
// creates an object of Scanner class
Scanner input = new Scanner(System.in);
do {
// takes input from the user
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0); // test expression

System.out.println("Sum = " + sum);
}
}
Output:
Enter a number: 2.5
Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0
6.5 break
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 d in the
next chapter.
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?

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);
}
}
}
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);
}
}
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;
}
6.6 Continue
The continue statement in Java skips the current iteration of a loop (for, while, do...while,
etc) and the control of the program moves to the end of the loop. And, the test expression of
a loop is evaluated.
In the case of for loop, the update statement is executed before the test expression.
The continue statement is almost always used in decision-making statements (if...else
Statement). It's syntax is:
continue;

How continue statement works?

Example 1: Java continue statement
class Test {

public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
// if value of i is between 4 and 9, continue is executed
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}

}
}
Output:

1
2
3
4
9
10
In the above program, we are using for loop to print the value of i in each iteration. To know
how for loop works, visit Java for loop. Here, notice the statement,
if (i > 5 && i < 9) {

continue;
}
This means when the value of i becomes more than 4 and less then 9, the print statement
inside the loop is skipped. Hence we get the output with values 5, 6, 7, and 8 skipped.
Example 2: Java continue statement
The program below calculates the sum of 5 positive numbers entered by the user. If the user
enters negative number or zero, it is skipped from the calculation.
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 AssignmentOperator {

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 a number: ");
// takes double type input from the user
number = input.nextDouble();
// if number is negative, the iteration is skipped
if (number <= 0.0) {

continue;
}
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
Enter a number: 2.2
Enter a number: 5.6
Enter a number: 0
Enter a number: -2.4
Enter a number: -3
Sum = 7.8
In the above program, notice the line,
if (number < 0.0) {
continue;
}

6.7 Difference

1) Difference
1) Break and continue

break continue

A break can appear in A continue can appear only in loop (for, while, do)

both switch and loop (for, while, do) statements.

statements.

A break causes the switch or loop A continue doesn't terminate the loop, it causes the
statements to terminate the moment loop to go to the next iteration. All iterations of the
it is executed. Loop or switch ends loop are executed even if continue is encountered.
abruptly when break is encountered. The continue statement is used to skip statements in

the loop that appear after the continue.

The break statement can be used in The continue statement can appear only in loops.
both switch and loop statements. You will get an error if this appears in switch

statement.

When a break statement is When a continue statement is encountered, it gets
encountered, it terminates the block the control to the next iteration of the loop.
and gets the control out of
the switch or loop.

A break causes the innermost A continue inside a loop nested within
enclosing loop or switch to be exited a switch causes the next loop iteration.
immediately.

2) While and do while

WHILE DO-WHILE
Statement(s) is executed atleast once,
Condition is checked first then thereafter condition is checked.
statement(s) is executed.
At least once the statement(s) is executed.
It might occur statement(s) is executed Semicolon at the end of while.
zero times, If condition is false. while(condition);

No semicolon at the end of while.
while(condition)

WHILE DO-WHILE

If there is a single statement, brackets are Brackets are always required.
not required.

Variable in condition is initialized before variable may be initialized before or within
the execution of loop. the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do { statement(s); }
{ statement(s); } while(condition);

3) For loop,while loop.do while loop

Sr. For loop While loop Do while loop
No

1. Syntax: For(initialization; Syntax: While(condition), { Syntax: Do { . Statements; }
condition;updating), { .
Statements; } . Statements; . } While(condition);

2. It is known as entry It is known as entry It is known as exit
controlled loop controlled loop. controlled loop.

3. If the condition is not true If the condition is not true Even if the condition is not
first time than control will first time than control will true for the first time the
never enter in a loop never enter in a loop. control will enter in a loop.

Sr. For loop While loop Do while loop
No

4. There is no semicolon; after There is no semicolon; There is semicolon; after
the condition in the syntax
the condition in the syntax of after the condition in the of the do while loop.

the for loop. syntax of the while loop.

5. Initialization and updating is Initialization and updating Initialization and updating is

the part of the syntax. is not the part of the not the part of the syntax

syntax.

4) If else and switch

BASIS FOR IF-ELSE SWITCH
COMPARISON

Basic Which statement will be Which statement will be executed

executed depend upon the is decided by user.

output of the expression

inside if statement.

Expression if-else statement uses switch statement uses single
multiple statement for expression for multiple choices.
multiple choices.

Testing if-else statement test for switch statement test only for
equality as well as for

BASIS FOR IF-ELSE SWITCH
COMPARISON

logical expression. equality.

Evaluation if statement evaluates switch statement evaluates only
integer, character, pointer character or integer value.
or floating-point type or
boolean type.

Sequence of Either if statement will be switch statement execute one
Execution
executed or else statement case after another till a break

is executed. statement is appeared or the end

of switch statement is reached.

Default Execution If the condition inside if If the condition inside switch

statements is false, then by statements does not match with

default the else statement any of cases, for that instance the

is executed if created. default statements is executed if

created.

Editing It is difficult to edit the if- It is easy to edit switch cases as,
else statement, if the they are recognized easily.
nested if-else statement is
used.

7 – Arrays

7.1 Introduction to Array
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we
need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
7.2 Types of array
There are two types of array.

1) Single Dimensional Array
2) Multidimensional Array

1) Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40

50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.

//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5

2) Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;

arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445

7.3 Array and Methods
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])

min=arr[i];
System.out.println(min);
}

public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Output:

3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array
//to method.
public class TestAnonymousArray{

//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Output:
10
22
44
66
Returning Array from the Method
We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}

Output:
10
30
50
90
60
7.4 ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the
array in negative, equal to the array size or greater than the array size while traversing the
array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

7.5 Copying and cloning
We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
Example of Copying an Array in Java
//Java Program to copy a source array into a destination array in Java
class TestArrayCopyDemo {

public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));

}
}
Output:
caffein
Cloning an Array in Java
Since, Java array implements the Cloneable interface, we can create the clone of the
Java array. If we create the clone of a single-dimensional array, it creates the deep
copy of the Java array. It means, it will copy the actual value. But, if we create the

clone of a multidimensional array, it creates the shallow copy of the Java array which
means it copies the references.
//Java Program to clone the array
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);
System.out.println("Printing clone of the array:");
int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);
System.out.println("Are both equal?");
System.out.println(arr==carr);
}}
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5

Are both equal?
False

8 – Strings

8.1 Introduction to String
Java String
In Java, string is basically an object that represents sequence of char values. An
array of characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc
What is String in java
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a
string object.
How to create a string object?
There are two ways to create String object:
By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:

String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s
will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
strings
example
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
Once string object is created its data or state can't be changed but a new string
object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){

String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed
but a new object is created with sachintendulkar. That is why string is known as
immutable.

But if we explicitely assign it to the reference variable, it will refer to "Sachin
Tendulkar" object.For example:
class Testimmutablestring1{
public static void main(String args[]){

String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object
is not modified.

Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the
value of the object, it will be affected to all the reference variables. That is why string
objects are immutable in java.
8.2 Methods of string class
We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method),
reference matching (by == operator) etc.
There are three ways to compare string in java:
By equals() method
By = = operator
By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares
values of string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){

String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}


Click to View FlipBook Version