Java How To Generate Random Numbers
How To Generate a Random Number You can use Math.random() method to generate a random number. Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
How To Generate a Random Number You can use Math.random() method to generate a random number. Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Square Root of a Number You can use Math.sqrt() to find the square root of a number: Example Find the square root of 64: Math.sqrt(64);
Find Out if a Number is Positive or Negative Find out if a number is even or odd: Example int myNum = 10; // Is this a positive or negative number? if (myNum > 0) { System.out.println(“The value is a…
Check Whether a Number is Even or Odd Find out if a number is even or odd: Example int number = 5; // Find out if the number above is even or odd if (number % 2 == 0) {…
Area of Rectangle The area of a rectangle can be found by multiplying the length of the rectangle by the width: Example int length = 5; int width = 2; int area = length * width; System.out.println(“Area of rectangle: “…
Loop Through an Enum The enum type has a values() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum: Example enum Level { LOW, MEDIUM,…
Loop Through a HashMap Loop through the items of a HashMap with a for-each loop. Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:
Loop Through an ArrayList Loop through the elements of an ArrayList: Example public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add(“Volvo”); cars.add(“BMW”); cars.add(“Ford”); cars.add(“Mazda”); for (String i : cars) { System.out.println(i); } }…
How To Find the Smallest Element in an Array Create a program that finds the lowest age among different ages: Example // An array storing different ages int ages[] = {20, 22, 18, 35, 48, 26, 87, 70}; // Create…