Show List

Java operators, control structures and arrays

Java operators are used to perform operations on values and variables. Some of the most common operators in Java include:

  1. Arithmetic operators: Used to perform arithmetic operations, such as addition, subtraction, multiplication, and division. For example:
int x = 10 + 20;
  1. Relational operators: Used to compare values and determine the relationship between them. For example:
if (x > 20) {
   System.out.println("x is greater than 20");
}
  1. Logical operators: Used to perform logical operations, such as AND and OR, on boolean values. For example:
if (x > 20 && y < 30) {
   System.out.println("x is greater than 20 and y is less than 30");
}

Control structures are used to control the flow of execution in a Java program. Some of the most common control structures in Java include:

  1. if-else statements: Used to execute a block of code if a condition is true, and another block of code if the condition is false. For example:
if (x > 20) {
   System.out.println("x is greater than 20");
} else {
   System.out.println("x is not greater than 20");
}
  1. for loops: Used to repeat a block of code a specified number of times. For example:
for (int i = 0; i < 10; i++) {
   System.out.println(i);
}
  1. while loops: Used to repeat a block of code while a condition is true. For example:
int i = 0;
while (i < 10) {
   System.out.println(i);
   i++;
}
Arrays in Java are used to store multiple values of the same data type. For example:
int[] numbers = {1, 2, 3, 4, 5};
In this example, numbers is an array of type int that stores 5 values. Arrays are indexed, meaning that each element in an array can be accessed by its index, which is a zero-based integer value. For example:
System.out.println(numbers[2]);
This will output 3, which is the value stored at index 2 in the numbers array.

    Leave a Comment


  • captcha text