Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

https://www.programiz.

com/java-programming/multidimensional-array
https://www.youtube.com/watch?v=rRFjmAtCQMY (important link)
Example 1: Java if Statement
class IfStatement {
public static void main(String[] args) {

int number = 10;

if (number > 0) {
System.out.println("Number is positive.");
}
System.out.println("This statement is always executed.");
}
}

When you run the program, the output will be:

Number is positive.

This statement is always executed.

Example 2: Java if else Statement


class IfElse {
public static void main(String[] args) {
int number = 10;

if (number > 0) {
System.out.println("Number is positive.");
}
else {
1|P ag e
System.out.println("Number is not positive.");
}

System.out.println("This statement is always executed.");


}
}

When you run the program, the output will be:

Number is positive.

This statement is always executed.

Example 1: Check whether an alphabet is vowel or


consonant using if..else statement
public class VowelConsonant {

public static void main(String[] args) {

char ch = 'i';

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )


System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");

}
}

2|P ag e
Example 1: Check whether a number is even or odd
using if...else statement
import java.util.Scanner;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

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


int num = reader.nextInt();

if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}

Example 2: Check whether a number is even or odd


using ternary operator
import java.util.Scanner;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

3|P ag e
System.out.print("Enter a number: ");
int num = reader.nextInt();

String evenOdd = (num % 2 == 0) ? "even" : "odd";

System.out.println(num + " is " + evenOdd);

}
}

Example 3: Java if..else..if Statement


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

int number = 0;

if (number > 0) {
System.out.println("Number is positive.");
}
else if (number < 0) {
System.out.println("Number is negative.");
}
else {
System.out.println("Number is 0.");
}
}
}

When you run the program, the output will be:

4|P ag e
Number is 0.

Example 1: Java switch statement


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

int week = 4;
String day;

switch (week) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";

5|P ag e
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println(day);
}
}

When you run the program, the output will be:

Wednesday

Example2: Simple Calculator using switch Statement


import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);


System.out.print("Enter two numbers: ");

// nextDouble() reads the next double from the keyboard


double first = reader.nextDouble();
double second = reader.nextDouble();

6|P ag e
System.out.print("Enter an operator (+, -, *, /): ");
char operator = reader.next().charAt(0);

double result;

switch(operator)
{
case '+':
result = first + second;
break;

case '-':
result = first - second;
break;

case '*':
result = first * second;
break;

case '/':
result = first / second;
break;

// operator doesn't match any case constant (+, -, *, /)


default:
System.out.printf("Error! operator is not correct");
return;
}

System.out.printf("%.1f %c %.1f = %.1f", first, operator, second,


result);
}
}

7|P ag e
Repetitive /Loops
_________________________________________________
• A loop can be used to tell a program to execute statements repeatedly.
• Java has four Loop control structures
– The While Loop
– The Do-while Loop
– For Loop
– For each or enhanced for loop
– Nested Loop

 The while Loop


A while loop executes statements repeatedly while the condition is true.
The syntax for the while loop is:
while (condition)
{
Statement(s);
}
Example

public class Loop


{
public static void main(String[] args)
{
int i = 0;
while(i < 10)
{
System.out.println("Hello World");
i++; //i = i + 1
}
}
} OUTPUT

8|P ag e
 The do-while Loop
– A do-while loop is the same as a while loop except that it executes the loop body first and then checks
the loop condition.
– The do-while loop is a variation of the while loop.
– Its syntax is:
do
{
Statement(s);
} while(condition);

Example
public class LoopW
{
public static void main(String[] args)
{
int i = 0;
do
{
System.out.println(i);
i++;
} while (i<5);
}
}

The output of the program:

9|P ag e
 The for Loop
– A for loop has a concise syntax for writing loops.
– In general, the syntax of a for loop is:

for (initialization; condition; increment)


{
Statement(s);
}
Example

public class LoopW


{
public static void main(String[] args)
{
for(int i = 0; i <= 5; i++)
System.out.println(i);
}
}
Output

10 | P a g e
 for-each Loop or enhanced for loop
– Java supports a convenient for loop, known as a for-each loop, which enables you to
traverse the array sequentially without using an index variable.
– The syntax for a for-each loop is:
for (elementType element: arrayRefVar)
{
// Process the element
}

Example
public class includehelp {
public static void main(String[] args)
{
int array[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Demonstration of for-each loop");

for (int i : array)


System.out.println(i);
}
}

Output

5. Nested Loops
– A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner loops

11 | P a g e
6. Jumping Statements  Example using continue
 The break and continue keywords provide additional controls in a loop
 The continue statement skips the current iteration of a loop (for, while, and do...while loop).

 How continue statement works?

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

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


if (i > 4 && i < 9) //skip this iteration and then continue
{
continue;
}
System.out.println(i);
}
}
}
Output

When you run the program, the output will be:

1
2
3
4
9
10

12 | P a g e
Example 1: Java break statement
 How break statement works?
 The break statement terminates the loop immediately, and the control of the program moves to
the next statement following the loop

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

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


if (i == 5) {
break;
}
System.out.println(i);
}
}
}
When you run the program, the output will be:

1
2
3
4

13 | P a g e
METHODS IN JAVA
__________________________________________________________
 Modularize the tasks of the program or structure the program.

 Functions separate the concept (what is done) from the implementation (how it is
done).
Note:-( ) Denotes for creating method

Methods of Scanner class


Here, we are discussing some of the important methods of Scanner class, which are used to
design a Java program with user input. The methods are:
1) int nextInt()
It is used to read an integer value from the keyboard.
2) int nextFloat()
It is used to read a float value from the keyboard.
3) long nextLong()
It is used to read a long value from the keyboard.
4) String next()
It is used to read string value from the keyboard.

next() method in java

1. It is a method of Scanner class in java.


2. next() method can read input till the space (i.e. it will print words till the space and whenever it gets
space it stops working and give the result till the space).
3. With the help of next() method we can't read those words which contain space itself (If we do then
we will get irrelevant results).
4. In other words next() method can take input till space and ends input of getting space.
5. In next() method it places the cursor in the same line after reading the input.
6. In next() its escaping sequence is space not ('\n').

14 | P a g e
nextLine() method in java

1. It is a method of Scanner class in java.


2. nextLine() method can read input till the line change (i.e. it will print words till the line change or
press enter or '\n' and whenever it gets '\n' or press enter it stops working and give the result of
whole line until press enter or line change).
3. With the help of nextLine() method Also we can read those words which contain spaces itself .
4. In other words nextLine() method can take input till the line change or new line and ends input of
getting '\n' or press enter.
5. In nextLine() method it places the cursor in the new or next line after reading the input.
6. In nextLine() its escaping sequence is '\n' or press enter not space.

Defining a Method:
– A method definition consists of its method name, parameters, return value type, and body.
– The syntax for defining a method is:

modifier returnValueType methodName(list of parameters)


{
// Method body;
}

15 | P a g e
Example
Sum of two integer number using method

EXERCISE
Maximum of two number using method in java

Method overloading
16 | P a g e
__________________________________________________________
 Two or more METHODS can have the same name but different parameters.
 Process of using the same name for two or more METHODS.
 Used so that a programmer does not have to remember multiple METHOD names.

Array in Java
 Array is a collection of similar type of elements that have contiguous memory location.
 Java array is an object that contains elements of similar data type. We can store fixed of elements
on a java array.
 Array in java is index based, first element of the array is stored at 0 index.
 An array is a container that holds data (values) of one single type. For example, you can
create an array that can hold 100 values of int type.

17 | P a g e
 One-dimensional arrays.
How to declare an array?
Here's how you can declare an array in Java:

datatype age [ ]

How to initialize arrays in Java?


In Java, you can initialize arrays during declaration or you can initialize (or change
values) later in the program as per your requirement.

Initialize an Array During Declaration

Here's how you can initialize an array during declaration.

18 | P a g e
int age []= {12, 4, 5, 2, 5};

This statement creates an array and initializes it during declaration.

The length of the array is determined by the number of values provided which is separated by commas. In
our example, the length of age array is 5.

How to access array elements?


 Note: when initializing an array, we can provide fewer values than the array elements.
E.g. int a [5] = {10, 2, 3}; in this case the compiler sets the remaining elements to zero.

You can easily access and alter array elements by using its numeric index. Let's take an
example.

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

int[] age = new int[5];

age[2] = 14;

age[0] = 34;

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


System.out.println("Element at index " + i +": " + age[i]);

19 | P a g e
}
}
}

When you run the program, the output will be:

Element at index 0: 34
Element at index 1: 0
Element at index 2: 14
Element at index 3: 0
Element at index 4: 0

 How to print elements of array.


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

int age []= {12, 4, 5, 2, 5};

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


System.out.println("Element at index " + i +": " + age[i]);
}
}
}

When you run the program, the output will be:

Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5

Example: Java arrays


The program below computes sum and average of values stored in an array of type int.

20 | P a g e
Exercise

Display the sum of 1 up to 5 in the array name of day.


#include <iostream.h>
#include<conio.h>
int day [ ] = {1, 2, 3, 4, 5}; //output is 15
int i, sum=0;
void main ()
{
for ( i=0 ; i<=4 ; i++ )
{
sum += day[i];//sum=sum+day[i];
}
cout << “result=”<<sum;
getch();
}

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

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


int sum = 0;
Double average;

for (int number: numbers) {


sum += number;
}

int arrayLength = numbers.length;

// Change sum and arrayLength to double as average is in double


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

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


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

When you run the program, the output will be:

Sum = 36
Average = 3.6

21 | P a g e
Multidimensional Arrays

In Java, you can declare an array of arrays known as multidimensional array. Here's an
example to declare and initialize multidimensional array.

Double matrix [][]= {{1.2, 4.3, 4.0}, {4.1, -1.1}};

Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of
type int.

How to initialize a 2d array in Java?


Here's an example to initialize a 2d array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

Initialize Array an integer elements of 1, 2, 3, 10, 20,30 to A[2] [3].

22 | P a g e
Or int A[2][3] ={1, 2, 3, 10, 20, 30}
Accessing Two-Dimensional Array Elements
(How to read and print elements)

Exercise
What is output the “ff” code fragment?

 Exercise

Create the 2 by 3 dimensional array elements of 1,2,8,3,3,5

23 | P a g e
Initializing arrays with input values.
__________________________________________________________

Exercise
Write a c++ program that accepts 2*2 array and print the given array Element.
The following loop initializes the array with user input values:

import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + "
columns: ");
for(int row = 0; row <matrix.length; row++){
for(int column = 0; column <matrix[0].length; column++){
matrix[row][column] = input.nextInt();
}
}

24 | P a g e
25 | P a g e
String Processing
• The classes String, StringBuilder, and StringBuffer, StringTokenizer are used for
processing strings.
• The String Class
– A string is a sequence of characters.
– In many languages, strings are treated as an array of characters, but in Java
a string is treated as an object.
A String object is immutable: Its content cannot be changed once the string is created.

Syntax for creating string


– You can create a string object using
• A string literal or
• An array of characters.
Using String literal
– String message = "Welcome to Java”;
Using array of characters.
– For example, the following statements create the string "Good Day”:
char wish [ ] = {'G' , 'o' , 'o' , 'd' , ' ' , 'D’ , 'a' , 'y
The StringBuilder and StringBuffer Classes
 The StringBuilder and StringBuffer classes are similar to the String class except that the String
class is immutable String object is fixed once the string is created
 StringBuilder and StringBuffer are more flexible than String.
 You can add, insert, or append new contents into StringBuilder and StringBuffer objects, whereas
the value of a String object is fixed once the string is createdthey are Mutable means one can
change the value of the object .
 Use StringBuffer if the class might be accessed by multiple tasks concurrently.
 Using StringBuilder is more efficient if it is accessed by just a single task.

26 | P a g e
StringTokenizer Class
• The StringTokenizer class allows an application to break a string into tokens.
• When you read a sentence, your mind breaks it into tokens—individual words and
punctuation marks that convey meaning to you.
• Tokens are separated from one another by delimiters, typically white-space characters
such as space, tab, newline and comma.

27 | P a g e
Loop lab Exercise
Write a Java program that takes a number as input and prints its multiplication table up to 10.

Test Data:-
Input a number: 8

import java.util.Scanner;

public class Exercise7 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);

System.out.print("Input a number: ");


int num1 = in.nextInt();

for (int i=0; i< 10; i++)


{
System.out.println(num1 + " x " + (i+1) + " = " +
(num1 * (i+1)));
}
}

28 | P a g e
NESTED FOR LOOP LAB EXERCISE
https://www.youtube.com/watch?v=m6gfX-siSdY (Java pattern)
https://www.youtube.com/watch?v=iL_tcbdwL-0 (Triangle pattern)

29 | P a g e

You might also like