Programming Java

Tasks studies - laboratory


Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko

Lab02 - Variable Types and Control Statements in Java

[1.] Variable Types in Java

Java is a strongly typed language, meaning that every value in Java has a well-defined type. There are two types of variables: object types and primitive types. Object types are defined by classes, whether they are user-implemented or come from libraries such as Java SE. Primitive types are built into the language and treated specifically. There are 8 primitive types: char, boolean, byte, short, int, long, float, and double.

The char type represents a single character (e.g., a letter). Variables of type char have values corresponding to any UTF-16 encoded character.

The boolean type represents logical values. A boolean variable can take one of two values: true or false.

The remaining primitive types are numeric. The types byte, short, int, and long are integer types representing whole numbers. A byte variable can hold values from -128 to 127. A short variable has a range from -32768 to 32767, an int variable from -2147483648 to 2147483647, and a long variable from -9223372036854775808 to 9223372036854775807.

The float and double types represent floating-point numbers. The float type holds single-precision values, while double represents double-precision values.

One of the most popular object types, aside from Object, is the String type, which represents a sequence of characters.

Example:

String a = "String type";

A specific type of object type is an array. An array type defines a sequence of elements of a fixed type. Array types are denoted by square brackets appended to the element type. For example, an array of int elements is denoted int[], and an array of String elements is denoted String[].

Example:

int[] vector;
int[] preinitializedVector = new int[] { 1, 2, 3, 4 };
int[][] twoDimMatrix = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } };
String[] arrayName = { "Ala", "Ela", "Ula", "Ola" };

[2.] Conditional Expressions in Java

2.1 if Statement

if (condition) {
  // Code executed conditionally
}

2.2 if-else Statement

if (condition) {
  // Code executed conditionally
} else {
  // Code executed alternatively
}

Example:

void isPositive(int x) {
  if (x > 0) {
    System.out.println("Number " + x + " is positive");
  } else {
    System.out.println("Number " + x + " is negative");
  }
}

2.3 Extended else-if Statement

if (condition) {
  // Code executed conditionally
} else if (secondCondition) {
  // Code executed when the second condition is true
} else {
  // Code executed alternatively
}

Example:

void isPositive(int x) {
  if (x > 0) {
    System.out.println("Number " + x + " is positive");
  } else if (x == 0) {
    System.out.println("Number " + x + " is zero");
  } else {
    System.out.println("Number " + x + " is negative");
  }
}

2.4 Ternary Operator

The ternary operator has the form condition ? value1 : value2.

Example: The code:

public String isEven(int x) {
  if (x % 2 == 0)
    return "even";
  else
    return "odd";
}

is equivalent to:

public String isEven(int x) {
  return x % 2 == 0 ? "even" : "odd";
}

2.5 switch Statement

switch (expression) {
  case value1:
    // Instructions for the variant
    break;
  case value2:
    // Instructions for the variant
    break;
  default:
    // Instructions for the default variant
}

Example:

public void oddOrEven(int x) {
  switch (x % 2) {
    case 0:
      System.out.println(x + " is even");
      break;
    case 1:
      System.out.println(x + " is odd");
      break;
    default:
      System.out.println("Unexpected case");
  }
}

The break statement ensures that after the condition is met and the code block is executed, subsequent blocks are not checked or executed.

[3.] Looping Constructs

3.1 while Loop

while (condition) {
  // Loop body
}

Example:

public void lowerThan(int num) {
  int x = 0;
  while (x < num) {
    System.out.println(x);
    x++;
  }
}

Note: A while loop may not execute its body even once if the initial condition is not satisfied.

3.2 do-while Loop

do {
  // Loop body
} while (condition);

Example:

public void lowerThan(int num) {
  int x = 0;
  do {
    System.out.println(x);
    x++;
  } while (x < num);
}

Note: A do-while loop always executes at least once because the condition is checked after the loop body.

3.3 for Loop

for (initialization; condition; increment) {
  // Loop body
}

Example:

public void lowerThan(int num) {
  for (int x = 0; x < num; x++) {
    System.out.println(x);
  }
}
public void decrementValue(int num) {
  for (int x = num; x >= 0; x--) {
    System.out.println(x);
  }
}

3.4 for-each Loop

for (variable : collection or array) {
  // Loop body
}

Example:

int[] myArray = { 1, 3, 5, 7, 11 };
for (int arrayElem : myArray) {
  System.out.print(arrayElem + " ");
}

3.5 break and continue Statements

The break statement immediately terminates the enclosing loop or switch statement. The continue statement skips the current iteration of a loop and continues with the next iteration.

Tasks:

Task 1:

Write a program to calculate the discriminant (delta) and roots of a quadratic equation.

Task 2:

Create a calculator that computes: addition, subtraction, multiplication, division, exponentiation, square roots, and trigonometric functions for a given angle. Use the Math library (e.g., Math.sin(2.5)).

Task 3:

Write a program to input 10 real numbers into an array. Implement the following functionalities using for loops:

a) Display the array from the first to the last index. b) Display the array from the last to the first index. c) Display elements at odd indices. d) Display elements at even indices.

Task 4:

Write a program to input 10 numbers and perform the following operations:

Task 5:

Create a program to display numbers from 20 to 0, excluding numbers {2, 6, 9, 15, 19}. Use the continue statement to implement the exclusions.

Task 6:

Write a program that continuously asks the user for integers. The loop should terminate if the user inputs a negative number. Use the break statement to exit the infinite loop.

Task 7:

Write a program to input n numbers and sort them using bubble sort or insertion sort. Display the sorted numbers on the console.