Skip to content

Commit de7fd1f

Browse files
Merge pull request #8 from shivkushwaha1511/shivkushwaha1511-patch-1
Update java-programs.md
2 parents a44f2c8 + b12e9f9 commit de7fd1f

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

Diff for: java-programs.md

+48-2
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,55 @@ Output
8484
<b><a href="#">↥ back to top</a></b>
8585
</div>
8686

87-
#### Q. Write a program to generate random numbers between the given range?
87+
## Q. Write a program to generate random numbers between the given range?
8888

89-
*ToDo*
89+
**Approach**
90+
1. Get the Min and Max which are the specified range.
91+
1. Call the nextInt() method of ThreadLocalRandom class (java.util.concurrent.ThreadLocalRandom) and specify the Min and Max value as the parameter as
92+
`ThreadLocalRandom.current().nextInt(min, max + 1);`
93+
1. Return the received random value
94+
95+
```java
96+
// Java program to generate a random integer
97+
// within this specific range
98+
99+
import java.util.concurrent.ThreadLocalRandom;
100+
101+
class GFG {
102+
103+
public static int getRandomValue(int Min, int Max)
104+
{
105+
106+
// Get and return the random integer
107+
// within Min and Max
108+
return ThreadLocalRandom
109+
.current()
110+
.nextInt(Min, Max + 1);
111+
}
112+
113+
// Driver code
114+
public static void main(String[] args)
115+
{
116+
117+
int Min = 1, Max = 100;
118+
119+
System.out.println("Random value between "
120+
+ Min + " and " + Max + ": "
121+
+ getRandomValue(Min, Max));
122+
}
123+
}
124+
125+
```
126+
127+
**Input**
128+
```
129+
Input: Min = 1, Max = 10
130+
```
131+
132+
**Output**
133+
```
134+
Random value between 1 and 100: 35
135+
```
90136

91137
## Q. Write a java program to swap two string variables without using temp variable?
92138
**Approach**

0 commit comments

Comments
 (0)