Basic Java code example: Java Language is one of the favourite languages for developers. Since its development by Sun Micro System, it’s been gaining popularity in building software applications loaded with features. Due to such high demand for Java developers, skilled Java developers are always in demand by top IT companies. Cracking coding interviews is important to get into these companies. This article consists of crucial basic Java code examples.
Basic Java Code Example: Insights
Everybody wants to learn programming quickly. But that is not how it operates. Learning coding requires a lot of practice and practice. One must develop their problem-solving skills while solving coding questions to enhance their programming skills.
Java is an object-oriented programming language widely preferred by major tech companies. Hence, they are always in demand. Big IT firms are constantly searching for a talented Java developer to join their team and create exceptional applications.
Also Read: AWT And Swing In Java: Difference Between Them
Basic Java Code Example: Important Interview Program Code
We will provide some Basic Java Code examples with their optimal solutions for reference. Check out some frequently asked Java Interview questions during interviews below.
Example 1. Write a basic Java Code Example for the Fibonacci series in Java.
Ans: In the Fibonacci series, the sum of the previous two numbers equals the next. You can also use recursion to write the Java code for the Fibonacci Series.
Basic Java Code Example: Fibonacci Series in Java |
class FibonacciExample {
static int first = 0, sec = 1, third = 0; static void Fibonacci(int count) { if (count > 0) { third = first + second; first = second; second = third; System.out.print(” ” + third); Fibonacci(count – 1); } } public static void main(String args[]) { int count = 5; System.out.print(n1 + ” ” + n2); // Printing 0 and 1 Fibonacci(count – 2); // It is (n-2) because two numbers from the start is already printed. } } |
Output
0 1 1 2 3 5 |
Example 2. Write basic Java Code examples for palindromes.
Ans: Palindrome numbers are groups of numbers or strings that will be the same even after reversing. Such as 151, 343, 152, etc.
Basic Java Code Example: Palindromes in Java |
import java.util.Scanner;
public class PalindromeExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a string: “); String inputString = scanner.nextLine(); if (isPalindrome(inputString)) { System.out.println(“The entered string is a palindrome.”); } else { System.out.println(“The given string is not a palindrome.”); } scanner.close(); } static boolean isPalindrome(String str) { int length = str.length(); for (int i = 0; i < length / 2; i++) { if (str.charAt(i) != str.charAt(length – 1 – i)) { return false; } } return true; } } |
Output
Enter a string:
151 The given string is a palindrome. |
Example 3. Write basic Java Code examples for calculating factorial of a number.
Ans: The factorization of a number is the product of all positive integer in a descending order of integers. It is denoted by n! For example, 5! = 5x4x3x2x1 = 120
Basic Java Code Example: Factorial in Java |
import java.util.Scanner;
public class FactJava { public static void main(String[] args) { // To read user input, create a Scanner object. Scanner scanner = new Scanner(System.in); // Prompt the user to enter a non-negative integer System.out.print(“Enter a non-negative integer: “); // Read the entered integer int number = scanner.nextInt(); // Check if the entered number is non-negative if (number < 0) { System.out.println(“Please enter a non-negative integer.”); } else { // Calculate and display the factorial long factorial = calculateFactorial(number); System.out.println(“Factorial of ” + number + ” is: ” + factorial); } // Close the scanner in order to free up resources scanner.close(); } // Recursive method to calculate factorial private static long calculateFactorial(int n) { if (n == 0 || n == 1) { return 1; } else { return n * calculateFactorial(n – 1); } } } |
Output
Please enter a non-negative integer:
5 Factorial of 5 is 120 |
Example 4. Write Java code example to check if the given number is an armstrong number
Ans: An armstrong number is a number whose sum of digits to the power of number of digits in the number is equal to the original number. It is also popularly referred to as Plus Perfect or Narcissistic number.
Basic Java Code Example: Armstrong number in Java |
import java.util.Scanner;
public class ArmstrongNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); if (isArmstrong(number)) { System.out.println(“The given number”+ number + ” is an Armstrong number.”); } else { System.out.println(“The given number” + number + ” is not an Armstrong number.”); } } // Indicates if a given number is an Armstrong number static boolean isArmstrong(int num) { int originalNum, rem, result = 0, n = 0; originalNum = num; // Count the number of digits while (originalNum != 0) { originalNum /= 10; ++n; } originalNum = num; // Determine the sum of the nth power of each digit. while (originalNum != 0) { rem = originalNum % 10; res += Math.pow(rem, n); originalNum /= 10; } // Confirm that the result matches the original, first number. return res == num; } } |
Output
Enter a number:
371 The given number 371 is an Armstrong number. |
Example 5. Write Java code example to reverse a number in Java.
Ans: We can reverse a number in Java using modulo operator and loops.
Basic Java Code Example: Reverse a number in Java |
import java.util.Scanner;
public class ReverseNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); int reversedNumber = reverseNumber(number); System.out.println(“Reversed number: ” + reversedNumber); scanner.close(); } static int reverseNumber(int num) { int reversedNum = 0; while (num != 0) { int digit = num % 10; reversedNum = reversedNum * 10 + digit; num /= 10; } return reversedNum; } } |
Output
Enter a number:
13455 Reversed number: 55431 |
Example 6. Write a basic Java code example to print the ASCII value in Java.
Ans: ASCII values stand for American Standard Code for Information Interchange. It consists of a total of 128 characters each having an associated numerical value.
Basic Java Code Example: Print ASCII value in Java |
public class AsciiValueCode{
public static void main(String[] args) { System.out.println(“ Enter a character:” Char ch = scanner.next().charAt(0); printValues(char); } static void printValues(char character) { int asciiValue = (int) character; System.out.println(“The ASCII Value of the given character + “is:” + asciiValue); } } } |
Output
Enter a character:
A The ASCII Value of the given character A is: 65 |
Example 7. Write a basic Java Program code to check whether an alphabet is Vowel or consonant.
Ans: There are a total of five vowels, a,e,i,o and u, and the rest of them are consonants in English alphabet. Let us develop a program that determines whether a given variable is a vowel or consonant.
Basic Java Code Example: Check vowel or consonant in Java |
public class CheckVowelConsonant{
public static void main(String[] args) { System.out.println(“Enter a character:”) char ch = scanner.next().charAt(0); if(ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’ ) System.out.println(ch + ” is a vowel”); else System.out.println(ch + ” is a consonant”); } } |
Output
Enter a character:
E E is a vowel F F is a consonant |
Example 8. Write a Java code example to find the root of a quadratic equation.
Ans: The standard quadratic equation is given by ax2 + bx + c = 0. We can calculate the root of a quadratic equation using the formula given below.
x = (-b ± √(b2-4ac)) / (2a) |
Now, let us write a Java code to print the roots of the given quadratic equation.
Basic Java Code Example: Find the root of Quardatic Equation |
public class Main {
public static void main(String[] args) { // value x, y, and z double x = 2.3, y = 4, z = 5.6; double rt1, rt2; // calculate the determinant (y2 – 4xz) double determinant = y * y – 4 * x * z; // check if the given determinant is greater than 0 if (determinant > 0) { // two real and distinct roots rt1 = (-y + Math.sqrt(determinant)) / (2 * x); rt2 = (-y – Math.sqrt(determinant)) / (2 * x); System.out.format(“root1 = %.2f and root2 = %.2f”, rt1, rt2); } // check if the given determinant is equal to 0 else if (determinant == 0) { // two real and equal roots // determinant is equal to 0 // so -y + 0 == -y rt1 = rt2 = -y / (2 * x); System.out.format(“rt1 = rt2 = %.2f;”, rt1); } // if the given determinant is less than zero else { // roots are complex number and distinct double real = -y / (2 * x); double imaginary = Math.sqrt(-determinant) / (2 * x); System.out.format(“root1 = %.2f+%.2fi”, real, imaginary); System.out.format(“\nroot2 = %.2f-%.2fi”, real, imaginary); } } } |
Example 9. Write a Java program code to find the GCD of two given numbers.
Ans: GCD stands for Greatest Common Divisor, which is the largest number that can exactly divide both of the given numbers. Let us use Euclidean algorithm to find the GCD of two given numbers.
Basic Java Code Example: Find the GCD of two numbers |
import java.util.Scanner;
public class GCDCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the first number: “); int num1 = scanner.nextInt(); System.out.print(“Enter the second number: “); int num2 = scanner.nextInt(); int gcd = findGCD(num1, num2); System.out.println(“GCD of ” + num1 + ” and ” + num2 + ” is: ” + gcd); scanner.close(); } static int findGCD(int a, int b) { // Using Euclidean algorithm while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } } |
Output
Enter the first number:
15 Enter the second number: 12 GCD of 15 and 12 is: 3 |
Example 10. Write a basic Java code example to find the largest element of an array.
Ans: Let us use a simple implementation using Java to find the largest element inside an array.
Basic Java Code Example: Find the largest element of an array |
import java.util.Scanner;
public class Largest{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the size of the array: “); int size = scanner.nextInt(); // Set up an array with the specified size. int[] array = new int[size]; System.out.println(“Enter the elements of the array:”); // Input array elements for (int i = 0; i < size; i++) { System.out.print(“Element ” + (i + 1) + “: “); array[i] = scanner.nextInt(); } int largestElement = findLargestElement(array); System.out.println(“The largest element in the array is: ” + largestElement); scanner.close(); } static int findLargestElement(int[] arr) { int max = arr[0]; // Iterate through the array to determine which element is the largest for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } } |
Output
Enter the size of the array:
5 Enter the elements of the array: 12 9 98 114 22 The largest element in the array is: 114 |
Java Programming with DSA Course
Enrol in our Decode Java with DSA Course to master Java programming along with data structure and algorithms. For individuals who wish to pursue successful careers as software developers, Java developers, software engineers, etc., this course is a fantastic all-inclusive package. With this course, you will also get perks such as relevant industry-level projects, assignments, quizzes, course completion certificates, hundred percent placement assistance, etc. Know more about our Java course at @pwskills.com.
For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group
Basic Java Code Example FAQs
How long does it take to learn Java?
There is no definite time duration for learning programming. Your level of consistency and practice will determine this. Keep on building your problem-solving skills and practice more and more questions to master Java Programming
How do you write Java simple code?
Write a simple Hello World program in Java using the steps given below.
public class HelloWorld{
public static void main (String[] argos){
System.out.println(“Hello World!”);
}
}
Why learn Java basic Syntax?
Knowledge of Java basic syntax is crucial to learning and coding in Java language. It consists of rules and commands which will help you write Java codes.