JAVA basic code snippets
Here's a basic Java code snippet that prints "Hello, World!" to the console:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}When you run this code, it will output "Hello, World!" to the console.
This is a very basic example of Java code, but it illustrates some key concepts in the language, such as:
- Defining a class using the
public classkeyword. - Defining a method within a class using the
public statickeywords. - Using the
System.out.println()method to print a string to the console.
Java code to calculate prime number
Get Data Sequel’s stories in your inbox
Join Medium for free to get updates from this writer.
public class PrimeNumberCalculator {
public static void main(String[] args) {
int num = 7;
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + “ is a prime number.”);
} else {
System.out.println(num + “ is not a prime number.”);
}
}
}
In this code, we first define the number we want to check for primality (in this case, 7), and a boolean flag that will be set to true if the number is prime, and false otherwise.
We then check if the number is less than or equal to 1, which is not a prime number. If so, we set isPrime to false.
If the number is greater than 1, we loop through all numbers from 2 up to the square root of the number. If any of these numbers divide the original number with no remainder, then the number is not prime, and we set isPrime to false. We then exit the loop using the break statement.
Finally, we output whether the number is prime or not using a simple if-else statement.
Note that this is a very basic prime number calculator, and there are more efficient algorithms for calculating primes, especially for very large numbers.










