• Java Program to Print Fibonacci Series

    In this Java program, we will learn how to print the Fibonacci series using both a traditional Java approach and Java 8 features.

    The Fibonacci series is a sequence in which each number is the sum of the previous two numbers.

    For example:

    0 1 1 2 3 5 8 13 21 34

    1. Normal Java Program

    import java.util.Scanner;
    
    public class FibonacciSeries {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the number of terms: ");
            int n = sc.nextInt();
            int first = 0;
            int second = 1;
            System.out.println("Fibonacci Series:");
            for (int i = 1; i <= n; i++) {
                System.out.print(first + " ");
                int next = first + second;
                first = second;
                second = next;
            }
            sc.close();
        }
    }

    Output

    Enter the number of terms: 10
    Fibonacci Series:
    0 1 1 2 3 5 8 13 21 34

    Explanation

    The program starts with two numbers:

    int first = 0;
    int second = 1;

    Inside the for loop, the next Fibonacci number is calculated by adding the previous two numbers:

    int next = first + second;

    The values are then updated:

    first = second;
    second = next;

    This process continues until the requested number of terms is printed.


    2. Java 8 Program to Print Fibonacci Series

    Java 8 introduced the Stream API, which can be used to generate a Fibonacci series in a more functional programming style.

    import java.util.Scanner;
    import java.util.stream.Stream;
    
    public class FibonacciJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the number of terms: ");
            int n = sc.nextInt();
            System.out.println("Fibonacci Series:");
            Stream.iterate(
                    new long[]{0, 1},
                    f -> new long[]{f[1], f[0] + f[1]}
            )
            .limit(n)
            .forEach(f -> System.out.print(f[0] + " "));
            sc.close();
        }
    }

    Output

    Enter the number of terms: 10
    Fibonacci Series:
    0 1 1 2 3 5 8 13 21 34

    Explanation of Java 8 Program

    The Java 8 version uses Stream.iterate() to generate Fibonacci numbers.

    Stream.iterate(
        new long[]{0, 1},
        f -> new long[]{f[1], f[0] + f[1]}
    )

    The array stores two consecutive Fibonacci numbers.

    For every iteration:

    • The first value becomes the second value.
    • The second value becomes the sum of the two previous values.

    The limit(n) method controls how many Fibonacci terms are generated:

    .limit(n)

    Finally, forEach() prints each generated value:

    .forEach(f -> System.out.print(f[0] + " "));

    Here, f -> is a Java 8 lambda expression.

    Difference Between Normal Java and Java 8

    FeatureNormal JavaJava 8
    Approachfor loopStream API
    Java 8 featureNoStream.iterate()
    Lambda expressionNoYes
    Easy for beginnersYesModerate
    PerformanceSimple and efficientMore functional style

    Which Approach Should You Use?

    For beginners and general-purpose Java programming, the normal for loop approach is recommended because it is easier to understand and maintain.

    The Java 8 version is useful for learning how the Stream API and lambda expressions can be applied to sequence generation.

    Conclusion

    The Fibonacci series is a common Java programming problem used in coding interviews and programming exercises. The traditional approach uses a loop and variables, while the Java 8 approach demonstrates how Streams and Lambda expressions can generate the same sequence.

  • Java Program to Check Whether a Number is Odd or Even Without Using the Modulus Operator

    In this Java program, we will learn how to check whether a number is odd or even without using the modulus (%) operator.

    The program uses the bitwise AND (&) operator. In binary representation, an even number always has 0 as its least significant bit, while an odd number has 1.

    1. Normal Java Program

    import java.util.Scanner;
    
    public class OddEvenWithoutOperator {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            if ((number & 1) == 0) {
                System.out.println(number + " is Even");
            } else {
                System.out.println(number + " is Odd");
            }
            sc.close();
        }
    }

    Output

    Enter a number: 10
    10 is Even

    Explanation

    The expression:

    number & 1

    checks the least significant bit of the number.

    For example:

    10 = 1010
     1 = 0001
    -----------
    &   0000

    Since the result is 0, 10 is even.

    For an odd number:

    11 = 1011
     1 = 0001
    -----------
    &   0001

    The result is 1, so 11 is odd.


    2. Java 8 Program

    In Java 8, we can use a lambda expression with the Function functional interface to perform the same operation.

    import java.util.Scanner;
    import java.util.function.Function;
    
    public class OddEvenJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            Function<Integer, String> checkOddEven =
                    n -> (n & 1) == 0 ? "Even" : "Odd";
            System.out.println(number + " is " + checkOddEven.apply(number));
            sc.close();
        }
    }

    Output

    Enter a number: 15
    15 is Odd

    Explanation of Java 8 Program

    The Java 8 version uses the functional interface:

    Function<Integer, String>

    The lambda expression performs the odd/even check:

    n -> (n & 1) == 0 ? "Even" : "Odd"

    The ternary operator returns "Even" when the result of (n & 1) is 0; otherwise, it returns "Odd".

    The function is executed using:

    checkOddEven.apply(number)

    Difference Between Normal Java and Java 8

    FeatureNormal JavaJava 8
    Approachif-elseLambda expression
    Modulus %Not usedNot used
    Bitwise operator&&
    Java 8 featureNoFunction + Lambda
    Beginner friendlyYesMore advanced

    Important Note

    The phrase “without operator” can be interpreted in different ways.

    The programs above do not use the modulus (%) operator, which is the usual meaning of this Java programming question. They do use the bitwise AND (&) operator.

    If the requirement is to check odd/even without using any arithmetic or bitwise operator at all, a different approach is required.

    Conclusion

    Using (number & 1) is an efficient way to determine whether an integer is odd or even without using the modulus operator. The normal Java version is easier for beginners, while the Java 8 version demonstrates the use of lambda expressions and functional interfaces

  • Java Program to Check Whether a Number is Odd or Even

    In this Java program, we will learn how to check whether a given number is odd or even using the modulo (%) operator.

    1. Normal Java Program

    import java.util.Scanner;
    
    public class OddEven {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            if (number % 2 == 0) {
                System.out.println(number + " is Even");
            } else {
                System.out.println(number + " is Odd");
            }
    
            sc.close();
        }
    }

    Output

    Enter a number: 10
    10 is Even

    Explanation

    The modulo operator % returns the remainder after division.

    number % 2

    If the remainder is 0, the number is even. Otherwise, the number is odd.


    2. Java 8 Program

    Java 8 introduced features such as Lambda expressions and functional interfaces. We can use a lambda expression to perform the odd/even check.

    import java.util.Scanner;
    import java.util.function.Function;
    
    public class OddEvenJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            Function<Integer, String> checkOddEven =
                    n -> n % 2 == 0 ? "Even" : "Odd";
            System.out.println(number + " is " + checkOddEven.apply(number));
            sc.close();
        }
    }

    Output

    Enter a number: 15
    15 is Odd

    Explanation

    In the Java 8 version, we use the Function<T, R> functional interface:

    Function<Integer, String>

    The lambda expression:

    n -> n % 2 == 0 ? "Even" : "Odd"

    checks whether the number is divisible by 2.

    The ternary operator:

    condition ? valueIfTrue : valueIfFalse

    returns "Even" when the condition is true; otherwise, it returns "Odd".

    The result is obtained using:

    checkOddEven.apply(number)

    Difference Between Normal Java and Java 8

    FeatureNormal JavaJava 8
    Approachif-elseLambda expression
    Operator%%
    InputScannerScanner
    Java VersionAll common versionsJava 8+
    ComplexitySimpleSlightly more advanced
    Best for beginnersYesGood for learning Java 8

    Conclusion

    The normal if-else approach is recommended for beginners because it is simple and easy to understand. The Java 8 version demonstrates how a lambda expression and functional interface can be used for the same task.

  • Java Program to Find the Largest Number Among Three Numbers

    In this Java program, we will learn how to find the largest number among three numbers entered by the user using the if-else statement.

    Java Program

    import java.util.Scanner;
    
    public class LargestAmongThree {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int num1 = sc.nextInt();
            System.out.print("Enter second number: ");
            int num2 = sc.nextInt();
            System.out.print("Enter third number: ");
            int num3 = sc.nextInt();
            int largest;
            if (num1 >= num2 && num1 >= num3) {
                largest = num1;
            } else if (num2 >= num1 && num2 >= num3) {
                largest = num2;
            } else {
                largest = num3;
            }
            System.out.println("Largest number = " + largest);
            sc.close();
        }
    }

    Output

    Enter first number: 25
    Enter second number: 40
    Enter third number: 15
    Largest number = 40

    Explanation

    The program accepts three numbers from the user using the Scanner class.

    The if-else if-else statement compares the three numbers:

    if (num1 >= num2 && num1 >= num3)

    If num1 is greater than or equal to both other numbers, it is the largest.

    Similarly, the program checks num2. If neither num1 nor num2 is the largest, then num3 is considered the largest.

    The && operator is used to check multiple conditions at the same time.

    Key Points

    • Scanner is used to accept input from the user.
    • if-else is used to compare three numbers.
    • The && logical operator combines multiple conditions.
    • The program works with Java 8 and later versions.

    Conclusion

    This Java program demonstrates how to compare three numbers and find the largest number using conditional statements.

    Using Java 8

    For Java 8, you can write it using the Math.max() method. This is shorter and cleaner than multiple if-else statements.

    Java 8: Program to Find the Largest Among Three Numbers

    import java.util.Scanner;
    
    public class LargestAmongThree {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int num1 = sc.nextInt();
            System.out.print("Enter second number: ");
            int num2 = sc.nextInt();
            System.out.print("Enter third number: ");
            int num3 = sc.nextInt();
            int largest = Math.max(num1, Math.max(num2, num3));
            System.out.println("Largest number = " + largest);
            sc.close();
        }
    }

    Output

    Enter first number: 25
    Enter second number: 40
    Enter third number: 15
    Largest number = 40

    Explanation

    Java provides the Math.max() method to find the larger of two numbers.

    Math.max(num2, num3)

    First, it finds the larger value between num2 and num3. Then that result is compared with num1:

    Math.max(num1, Math.max(num2, num3))

    This gives the largest number among all three numbers.

  • Java Program for Addition of Two Numbers

    In this Java program, we will learn how to add two numbers entered by the user and display their sum using the Scanner class.

    Java Program

    import java.util.Scanner;
    
    public class AdditionOfTwoNumbers {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int num1 = sc.nextInt();
            System.out.print("Enter second number: ");
            int num2 = sc.nextInt();
            int sum = num1 + num2;
            System.out.println("Sum = " + sum);
            sc.close();
        }
    }

    Output

    Enter first number: 25
    Enter second number: 15
    Sum = 40

    Explanation

    The program uses the Scanner class to accept two numbers from the user.

    int num1 = sc.nextInt();
    int num2 = sc.nextInt();

    The + operator is then used to add the two numbers:

    int sum = num1 + num2;

    Finally, the result is displayed using System.out.println().

    Key Points

    • Scanner is used to read numbers from the user.
    • The + operator performs addition.
    • The result is stored in the sum variable.
    • System.out.println() displays the final result.

    Conclusion

    This simple Java program demonstrates how to take two numbers as input, perform addition, and display the result.

  • Java Program to Print the Multiplication Table of a Number

    In this Java program, we will learn how to print the multiplication table of a given number using a for loop.

    Java Program

    import java.util.Scanner;
    
    public class MultiplicationTable {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int num = sc.nextInt();
            for (int i = 1; i <= 10; i++) {
                System.out.println(num + " x " + i + " = " + (num * i));
            }
            sc.close();
        }
    }

    Output

    Enter a number: 5
    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50

    Explanation

    The program first takes a number from the user using the Scanner class.

    int num = sc.nextInt();

    A for loop is then used to generate the multiplication table from 1 to 10:

    for (int i = 1; i <= 10; i++)

    Inside the loop, the number is multiplied by the current value of i:

    num * i

    The result is displayed using System.out.println().

    Key Points

    • Scanner is used to read input from the user.
    • A for loop generates the multiplication table.
    • The table is printed from 1 to 10.
    • The multiplication result is calculated using the * operator.

    Conclusion

    This simple Java program demonstrates how to use user input, a for loop, and arithmetic multiplication to generate a multiplication table.

    2. Java 8 Program

    import java.util.Scanner;
    import java.util.stream.IntStream;
    
    public class MultiplicationTable {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            IntStream.rangeClosed(1, 10)
                     .forEach(i -> System.out.println(
                             number + " x " + i + " = " + (number * i)
                     ));
            sc.close();
        }
    }

    Output

    Enter a number: 5
    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50

    Explanation

    The program first accepts a number from the user using the Scanner class.

    int number = sc.nextInt();

    Java 8’s IntStream.rangeClosed() is then used to generate numbers from 1 to 10:

    IntStream.rangeClosed(1, 10)

    The forEach() method processes each number in the stream:

    .forEach(i -> System.out.println(
        number + " x " + i + " = " + (number * i)
    ));

    Here, the lambda expression i -> is a Java 8 feature. For every value of i, the program multiplies it by the input number and prints the result.

    Key Points

    • IntStream is part of the Java 8 Stream API.
    • rangeClosed(1, 10) generates numbers from 1 through 10.
    • forEach() processes each value.
    • Lambda expressions are used to print the multiplication table.
    • The program is compatible with Java 8 and later versions.

    Conclusion

    This Java 8 program demonstrates how Streams and Lambda expressions can be used to generate a multiplication table in a concise and modern way.

  • Java Program to Print a Semicolon Without Using a Semicolon

    In this Java program, we will learn how to print a semicolon (;) without using a semicolon anywhere in the program.

    This is a common Java programming puzzle and interview question that demonstrates how Java expressions can be used inside control statements.

    Java Program

    public class PrintSemicolon {
        public static void main(String[] args) {
            if (System.out.printf("%c", 59) != null) {
            }
        }
    }

    Output

    ;

    Explanation

    The ASCII value of the semicolon character (;) is 59.

    ;  →  ASCII value = 59

    We use the following statement:

    System.out.printf("%c", 59)

    The %c format specifier tells printf() to print the value as a character. Therefore, 59 is printed as the semicolon character.

    The interesting part is that we don’t write the printf() call as a normal statement. Instead, we place it inside an if condition:

    if (System.out.printf("%c", 59) != null) {
    }

    An if condition is an expression and does not require a semicolon at the end. printf() returns a PrintStream object, so its result can be compared with null.

    As a result, the semicolon is printed without using a semicolon to terminate the statement.

    Key Points

    • The ASCII value of ; is 59.
    • %c is used to print a character.
    • System.out.printf() returns a PrintStream object.
    • The printf() call is placed inside an if condition.
    • The program contains no semicolon character (;) in the source code.

    Note: This is a programming puzzle rather than a recommended coding practice. In normal Java programs, semicolons should be used wherever the Java syntax requires them.

  • Write a Java Program to execute program without main() method.

    Yes. In Java, we can write a class without explicitly defining a main() method. For example, using a static initializer block:

    In older Java versions, you could use a static block:

    class JavaKnowledgeBase{
        static {
            System.out.println("Java Knowledge Base");
            System.exit(0);
        }
    }

    Traditionally, this could execute the static block when the class is initialized, but modern Java versions require a main method when launching a class directly. So this is not a reliable way to run a standalone program on current Java versions.

    How does this work?

    Step 1: Class loading

    When Java loads the Demo class, it initializes its static members.

    Step 2: Static block executes this code

    static {
        System.out.println("Java Knowledge Base");
    }

    runs during class initialization.

    Step 3: Output

    You get:

    Java Knowledge Base

    Step 4: System.exit(0)

    System.exit(0);

    terminates the JVM normally after printing.

    ⚠️ Important for modern Java

    This trick is version-dependent and should not be used as a normal Java program technique. In modern Java, launching a class with java Demo expects a valid application entry point (main, subject to the Java version’s launch rules).

    So if this is an interview question, you can say:

    “Yes, a class can contain executable code in a static initializer without declaring main(), but whether it can be launched directly without main() depends on the Java version. The traditional static-block trick is mainly a historical example.”

    So how do we write it in Java 21?

    The normal Java 21 program is still:

    class JavaKnowledgeBase {
        public static void main(String[] args) {
            System.out.println("Java Knowledge Base");
        }
    }

    However, Java 21 has a preview feature that allows simpler entry-point syntax. For example:

    class JavaKnowledgeBase {
        void main() {
            System.out.println("Java Knowledge Base");
        }
    }

    But you need to enable the preview feature when compiling/running.

    javac --enable-preview --release 21 JavaKnowledgeBase.java
    java --enable-preview JavaKnowledgeBase