Basic Java Programming Examples and Solutions
Introduction
Java is a versatile programming language used for building various applications, from simple web pages to complex enterprise systems. Mastering its fundamentals is crucial for any aspiring programmer. This guide explores common Java programming examples and their solutions, providing insights into essential concepts and techniques.
1. Printing “Hello, World!”
Problem: Display the message “Hello, World!” on the console.
Solution:
Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld
declares a class namedHelloWorld
.public static void main(String[] args)
is the main method, the program’s entry point.System.out.println()
prints the message to the console.
2. Finding the Sum of Two Numbers
Problem: Take two numbers as input and calculate their sum.
Solution:
Java
import java.util.Scanner;
public class SumOfTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("Sum of the numbers: " + sum);
}
}
3. Checking for Even or Odd Numbers
Problem: Determine whether a given number is even or odd.
Solution:
Java
import java.util.Scanner;
public class EvenOddChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
4. Finding the Largest Number among Three
Problem: Identify the largest number among three given numbers.
Solution:
Java
import java.util.Scanner;
public class LargestNumberFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// ... (Prompt for and read three numbers)
// Find the largest number using conditional statements
// ...
}
}
5. Swapping Two Numbers
Problem: Exchange the values of two variables without using a temporary variable.
Solution:
Java
// ... (Declare and initialize two variables)
// Swap the values using arithmetic operations
// ...
Additional Examples and Solutions
- Calculating factorials
- Finding prime numbers
- Reversing a string
- Sorting numbers or strings
- Generating patterns like pyramids or stars
- Working with arrays
- Implementing basic data structures like linked lists or stacks
Conclusion
These basic Java programming examples provide a foundation for understanding core concepts like variables, data types, operators, control flow, input/output, and more. By practicing and experimenting with these examples, you’ll gain confidence in writing Java code and prepare for more advanced programming tasks.