-
Math.random():
Java's Math.random() method returns a random double value between 0.0 (inclusive) and 1.0 (exclusive).
Illustration / Sample Code:
double randomValue = Math.random();
System.out.println("Random value between 0.0 and 1.0: " + randomValue);
-
Getting user input from the command-line:
Java provides the Scanner class to read user input from the command-line.
Illustration / Sample Code:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}
-
Loops:
Loops in Java allow you to execute a block of code repeatedly until a specified condition is met. Common types of loops include for, while, and do-while.
Illustration / Sample Code:
// for loop
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
// Output: 1 2 3 4 5
// while loop
int count = 1;
while (count <= 5) {
System.out.print(count + " ");
count++;
}
// Output: 1 2 3 4 5
// do-while loop
int num = 1;
do {
System.out.print(num + " ");
num++;
} while (num <= 5);
// Output: 1 2 3 4 5
-
Casting primitives from a large size to a smaller size:
Casting allows you to convert a value of one data type to another. When casting from a larger data type to a smaller one, you may risk losing precision.
Illustration / Sample Code:
int largeNumber = 123456;
byte smallNumber = (byte) largeNumber;
System.out.println("Large Number: " + largeNumber);
System.out.println("Small Number: " + smallNumber);
In the above code snippet, we cast an int (larger) to a byte (smaller). The value of largeNumber is 123456, but after casting, the value of smallNumber will be limited to the range of a byte (-128 to 127).
-
Converting string to an int:
In Java, you can convert a string to an integer using the Integer.parseInt() method.
Illustration / Sample Code:
String numberString = "42";
int number = Integer.parseInt(numberString);
System.out.println("Number: " + number);
In the above code, the string "42" is converted to an integer using Integer.parseInt(). The resulting number is 42, which can now be used for numeric calculations.