Java Basic Programs
Java is a widely used programming language appreciated by developers for its flexibility, readability, and robustness. If you are beginning your journey into Java programming, certain basic programs may seem intimidating. This article provides clear explanations and code examples of common Java programs.
Hello World Program
The classic "Hello World" program in Java prints the text "Hello, World!" to the console. Here is the code:
Java
This program contains a class named HelloWorld
with a main
method. The println
method outputs the text to the console. Running this program displays the greeting.
Adding Two Numbers
Adding two numbers together is a common program in Java. This helps you understand basic arithmetic operations. Below is the code for adding two numbers:
Java
In this program, we declare two integer variables num1
and num2
, add them, and then print the result.
Check Prime Number
How do you determine if a number is prime? A prime number is greater than 1 and has no positive divisors other than 1 and itself. This program checks for prime numbers:
Java
In this program, we check if the number is less than or equal to 1. If so, it is not prime. If not, we iterate from 2 to half of the number to find divisors.
Fibonacci Series
The Fibonacci series is a famous mathematical sequence where each number is the sum of the two preceding ones. Here is a Java program to generate the Fibonacci series:
Java
This program specifies the number of terms in the Fibonacci series and calculates each term by summing the two preceding terms.
Reverse a Number
Reversing a number changes the order of its digits. Here is a Java program to reverse a given number:
Java
In this program, we use a while loop to extract the last digit of the number, append it to the reversed number, and remove that digit from the original number.
You have now explored various basic Java programs. Practicing these examples will help strengthen your coding skills. Programming combines creativity and logic in problem-solving.