Basic Java Programs for Beginners: Ever enjoyed solving puzzles or unraveling mysteries? Coding is a lot like that – a journey of logical thinking and problem-solving. Basic Java programs act as your training ground for honing these skills.Â
As you progress, you’ll find yourself deciphering challenges, breaking them down into logical steps, and orchestrating your code to provide solutions. Each program becomes a puzzle to solve, and you, my friend, are the coder-detective piecing it all together.
Imagine writing a letter and getting a response. Basic Java programs take you beyond the one-way street of code execution. They introduce you to user interaction, where your code engages in a dialogue with the person interacting with it. Whether it’s reading input, processing it, and generating output, this interaction brings your code to life. Suddenly, your code isn’t just lines on a screen; it’s a conversational partner in the digital realm.
Basic Java Programs for Beginners Overview
Ah, the allure of coding – a world where lines of text translate into digital wonders. If you’re dipping your toes into the coding pool, you’ve probably heard the whispers about Java. Well, buckle up, because we are about to guide you through the enchanting realm of Basic Java Programs, where the journey begins, and the magic unfolds.
Highlights:
- Introduction to Basic Java Programs: The content sets the stage by likening coding to solving puzzles or unraveling mysteries, portraying it as a journey of logical thinking and problem-solving. Basic Java programs are presented as the training ground for honing these skills, where each program becomes a puzzle for the coder to solve, fostering an environment of engagement and exploration.
- Interactive Learning Experience: Basic Java programs are described as more than just lines of code; they facilitate interaction between the code and the user, bringing the code to life. By engaging in a dialogue with the user through input, processing, and output, these programs transcend the traditional one-way street of code execution, offering an interactive learning experience that enhances understanding and retention.
- Initiation with “Hello, World!”: The iconic “Hello, World!” program is highlighted as the initiation point for beginners into the world of Java programming. With just a few lines of code, beginners make their code come alive, marking the beginning of their journey into the mystical language of Java and signaling their entry into the coding cosmos.
- Logic Building and Problem Solving: Basic Java programs serve as a training ground for logic building, akin to navigating a maze of logical challenges. Through these programs, beginners learn to think step by step, break down problems, and craft solutions, ultimately transforming into proficient code maestros adept at deciphering complex challenges.
- Diverse Array of Programs: The content showcases a diverse array of basic Java programs suitable for beginners, ranging from calculator programs and factorial calculations to palindrome checks and pattern printing. Each program is accompanied by its output, providing practical examples for learners to grasp Java concepts and applications effectively.
1) Hello, World!Â
Picture this: you’re about to write your first line of code, and it’s not just any code – it’s the legendary “Hello, World!” program. It’s like the universal greeting in the coding cosmos. With just a few lines, you’re not merely saying hello; you’re making your code come alive. This tiny program is your initiation into the mystical language of Java.
2) Cracking the Code
Now, before you get jittery about the coding world, let me reassure you – Java’s syntax is like learning a new language. Basic Java Programs are your Rosetta Stone. They unravel the grammar of the coding language, teaching you how to speak Java fluently. It’s not just about typing; it’s about understanding the secret sauce that makes your code dance to your commands.
3) Logic Building
Ever enjoyed solving puzzles? Coding is like navigating a maze of logical challenges. Basic Java Programs are your training ground for logic building. They teach you to think step by step, break down problems, and craft solutions. It’s not about memorizing; it’s about training your brain to dance with logic, turning you into a code maestro.
Basic Java Programs for Beginners With Outputs
Below are some basic Java programs suitable for beginners, along with their outputs:
1) Calculator Program in Java:
import java.util.Scanner;
public class Calculator {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.print(“Enter first number: “);
 double num1 = scanner.nextDouble();
 System.out.print(“Enter second number: “);
 double num2 = scanner.nextDouble();
 System.out.print(“Enter operator (+, -, *, /): “);
 char operator = scanner.next().charAt(0);
 double result;
 switch (operator) {
 case ‘+’:
 result = num1 + num2;
 break;
 case ‘-‘:
 result = num1 – num2;
 break;
 case ‘*’:
 result = num1 * num2;
 break;
 case ‘/’:
 if (num2 != 0) {
 result = num1 / num2;
 } else {
 System.out.println(“Error! Division by zero is not allowed.”);
 return;
 }
 break;
 default:
 System.out.println(“Error! Invalid operator.”);
 return;
 }
 System.out.println(“Result: ” + result);
 }
}
Output:
Enter first number: 10
Enter second number: 5
Enter operator (+, -, *, /): *
Result: 50.0
2) Factorial Program using Recursion:
public class Factorial {
 public static void main(String[] args) {
 int num = 5;
 int factorial = factorial(num);
 System.out.println(“Factorial of ” + num + ” is: ” + factorial);
 }
 static int factorial(int n) {
 if (n == 0 || n == 1) {
 return 1;
 }
 return n * factorial(n – 1);
 }
}
Output:
Factorial of 5 is: 120
3) Fibonacci Series Program:
public class Fibonacci {
 public static void main(String[] args) {
 int n = 10;
 int a = 0, b = 1, c;
 System.out.print(“Fibonacci Series up to ” + n + ” terms: “);
 for (int i = 1; i <= n; ++i) {
 System.out.print(a + ” “);
 c = a + b;
 a = b;
 b = c;
 }
 }
}
Output:
Fibonacci Series up to 10 terms: 0 1 1 2 3 5 8 13 21 34
4) Palindrome Program in Java:
public class Palindrome {
 public static void main(String[] args) {
 String str = “radar”;
 if (isPalindrome(str)) {
 System.out.println(str + ” is a palindrome.”);
 } else {
 System.out.println(str + ” is not a palindrome.”);
 }
 }
 static boolean isPalindrome(String str) {
 int left = 0, right = str.length() – 1;
 while (left < right) {
 if (str.charAt(left) != str.charAt(right)) {
 return false;
 }
 left++;
 right–;
 }
 return true;
 }
}
Output:
radar is a palindrome.
5) Permutation and Combination Program:
public class PermutationCombination {
 public static void main(String[] args) {
 int n = 5, r = 3;
 System.out.println(“Permutation: ” + permutation(n, r));
 System.out.println(“Combination: ” + combination(n, r));
 }
 static int permutation(int n, int r) {
 return factorial(n) / factorial(n – r);
 }
 static int combination(int n, int r) {
 return factorial(n) / (factorial(r) * factorial(n – r));
 }
 static int factorial(int n) {
 if (n == 0 || n == 1) {
 return 1;
 }
 return n * factorial(n – 1);
 }
}
Output:
Permutation: 60
Combination: 10
6) Pattern Programs in Java:
public class PatternPrograms {
 public static void main(String[] args) {
 int rows = 5;
 System.out.println(“Pattern 1:”);
 pattern1(rows);
 System.out.println(“\nPattern 2:”);
 pattern2(rows);
 }
 static void pattern1(int rows) {
 for (int i = 1; i <= rows; i++) {
 for (int j = 1; j <= i; j++) {
 System.out.print(j + ” “);
 }
 System.out.println();
 }
 }
 static void pattern2(int rows) {
 for (int i = rows; i >= 1; i–) {
 for (int j = 1; j <= i; j++) {
 System.out.print(j + ” “);
 }
 System.out.println();
 }
 }
}
Output:
Pattern 1:
1Â
1 2Â
1 2 3Â
1 2 3 4Â
1 2 3 4 5Â
Pattern 2:
1 2 3 4 5Â
1 2 3 4Â
1 2 3Â
1 2Â
1Â
7) String Reverse Program in Java:
public class StringReverse {
 public static void main(String[] args) {
 String str = “Hello, World!”;
 System.out.println(“Original String: ” + str);
 String reversed = reverseString(str);
 System.out.println(“Reversed String: ” + reversed);
 }
 static String reverseString(String str) {
 StringBuilder reversed = new StringBuilder();
 for (int i = str.length() – 1; i >= 0; i–) {
 reversed.append(str.charAt(i));
 }
 return reversed.toString();
 }
}
Output:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
8) Mirror Inverse Program in Java:
public class MirrorInverse {
 public static void main(String[] args) {
 int[] arr = {1, 4, 2, 3, 5};
 if (isMirrorInverse(arr)) {
 System.out.println(“The array is mirror inverse.”);
 } else {
 System.out.println(“The array is not mirror inverse.”);
 }
 }
 static boolean isMirrorInverse(int[] arr) {
 for (int i = 0; i < arr.length; i++) {
 if (arr[arr[i]] != i) {
 return false;
 }
 }
 return true;
 }
}
Output:
The array is mirror inverse.
9) Binary Search Program in Java:
public class BinarySearch {
 public static void main(String[] args) {
 int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
 int key = 6;
 int index = binarySearch(arr, key);
 if (index != -1) {
 System.out.println(“Element ” + key + ” found at index ” + index);
 } else {
 System.out.println(“Element not found.”);
 }
 }
 static int binarySearch(int[] arr, int key) {
 int left = 0, right = arr.length – 1;
 while (left <= right) {
 int mid = left + (right – left) / 2;
 if (arr[mid] == key) {
 return mid;
 }
 if (arr[mid] < key) {
 left = mid + 1;
 } else {
 right = mid – 1;
 }
 }
 return -1;
 }
}
Output:
Element 6 found at index 5
10) HeapSort Program in Java:
import java.util.Arrays;
public class HeapSort {
 public static void main(String[] args) {
 int[] arr = {12, 11, 13, 5, 6, 7};
 heapSort(arr);
 System.out.println(“Sorted array: ” + Arrays.toString(arr));
 }
 static void heapSort(int[] arr) {
 int n = arr.length;
 for (int i = n / 2 – 1; i >= 0; i–) {
 heapify(arr, n, i);
 }
 for (int i = n – 1; i > 0; i–) {
 int temp = arr[0];
 arr[0] = arr[i];
 arr[i] = temp;
 heapify(arr, i, 0);
 }
 }
 static void heapify(int[] arr, int n, int i) {
 int largest = i;
 int left = 2 * i + 1;
 int right = 2 * i + 2;
 if (left < n && arr[left] > arr[largest]) {
 largest = left;
 }
 if (right < n && arr[right] > arr[largest]) {
 largest = right;
 }
 if (largest != i) {
 int temp = arr[i];
 arr[i] = arr[largest];
 arr[largest] = temp;
 heapify(arr, n, largest);
 }
 }
}
Output:
Sorted array: [5, 6, 7, 11, 12, 13]
11) Removing Elements from ArrayList:
import java.util.ArrayList;
public class RemoveElementsFromArrayList {
 public static void main(String[] args) {
 ArrayList<Integer> list = new ArrayList<>();
 list.add(1);
 list.add(2);
 list.add(3);
 list.add(4);
 System.out.println(“Original ArrayList: ” + list);
 list.remove(2);
 System.out.println(“After removing element at index 2: ” + list);
 }
}
Output:
Original ArrayList: [1, 2, 3, 4]
After removing element at index 2: [1, 2, 4]
12) HashMap Program in Java:
import java.util.HashMap;
public class HashMapExample {
 public static void main(String[] args) {
 HashMap<String, Integer> map = new HashMap<>();
 map.put(“John”, 25);
 map.put(“Alice”, 30);
 map.put(“Bob”, 28);
 System.out.println(“Age of Alice: ” + map.get(“Alice”));
 }
}
Output:
Age of Alice: 30
13) Circular LinkedList Program in Java:
class Node {
 int data;
 Node next;
 Node(int d) {
 data = d;
 next = null;
 }
}
public class CircularLinkedList {
 Node head;
 void addToEnd(int data) {
 Node newNode = new Node(data);
 if (head == null) {
 head = newNode;
 newNode.next = head;
 } else {
 Node temp = head;
 while (temp.next != head) {
 temp = temp.next;
 }
 temp.next = newNode;
 newNode.next = head;
 }
 }
 void display() {
 if (head == null) {
 System.out.println(“List is empty”);
 return;
 }
 Node temp = head;
 do {
 System.out.print(temp.data + ” “);
 temp = temp.next;
 } while (temp != head);
 }
 public static void main(String[] args) {
 CircularLinkedList list = new CircularLinkedList();
 list.addToEnd(1);
 list.addToEnd(2);
 list.addToEnd(3);
 list.display();
 }
}
Output:
1 2 3
14) Java DataBase Connectivity Program:
import java.sql.*;
public class JDBCExample {
 public static void main(String[] args) {
 String url = “jdbc:mysql://localhost:3306/mydatabase”;
 String username = “root”;
 String password = “password”;
 try {
 Connection connection = DriverManager.getConnection(url, username, password);
 Statement statement = connection.createStatement();
 ResultSet resultSet = statement.executeQuery(“SELECT * FROM mytable”);
 while (resultSet.next()) {
 int id = resultSet.getInt(“id”);
 String name = resultSet.getString(“name”);
 System.out.println(“ID: ” + id + “, Name: ” + name);
 }
 resultSet.close();
 statement.close();
 connection.close();
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }
}
15) Transpose of a Matrix Program in Java:
public class MatrixTranspose {
 public static void main(String[] args) {
 int[][] matrix = {
 {1, 2, 3},
 {4, 5, 6},
 {7, 8, 9}
 };
 int[][] transpose = new int[matrix[0].length][matrix.length];
 for (int i = 0; i < matrix.length; i++) {
 for (int j = 0; j < matrix[0].length; j++) {
 transpose[j][i] = matrix[i][j];
 }
 }
 System.out.println(“Original Matrix:”);
 printMatrix(matrix);
 System.out.println(“Transpose Matrix:”);
 printMatrix(transpose);
 }
 static void printMatrix(int[][] matrix) {
 for (int i = 0; i < matrix.length; i++) {
 for (int j = 0; j < matrix[0].length; j++) {
 System.out.print(matrix[i][j] + ” “);
 }
 System.out.println();
 }
 }
}
Output:
Original Matrix:
1 2 3Â
4 5 6Â
7 8 9Â
Transpose Matrix:
1 4 7Â
2 5 8Â
3 6 9
16) Stack Implementation in Java:
import java.util.*;
public class StackImplementation {
 public static void main(String[] args) {
 Stack<Integer> stack = new Stack<>();
 stack.push(1);
 stack.push(2);
 stack.push(3);
 System.out.println(“Stack elements:”);
 while (!stack.isEmpty()) {
 System.out.println(stack.pop());
 }
 }
}
Output:
Stack elements:
3
2
1
17) Queue Implementation in Java:
import java.util.*;
public class QueueImplementation {
 public static void main(String[] args) {
 Queue<Integer> queue = new LinkedList<>();
 queue.offer(1);
 queue.offer(2);
 queue.offer(3);
 System.out.println(“Queue elements:”);
 while (!queue.isEmpty()) {
 System.out.println(queue.poll());
 }
 }
}
Output:
Queue elements:
1
2
3
18) Binary Search Tree (BST) Implementation in Java:
class TreeNode {
 int data;
 TreeNode left;
 TreeNode right;
 TreeNode(int data) {
 this.data = data;
 left = right = null;
 }
}
public class BinarySearchTree {
 TreeNode root;
 void insert(int data) {
 root = insertRec(root, data);
 }
 TreeNode insertRec(TreeNode root, int data) {
 if (root == null) {
 root = new TreeNode(data);
 return root;
 }
 if (data < root.data) {
 root.left = insertRec(root.left, data);
 } else if (data > root.data) {
 root.right = insertRec(root.right, data);
 }
 return root;
 }
 void inOrderTraversal(TreeNode root) {
 if (root != null) {
 inOrderTraversal(root.left);
 System.out.print(root.data + ” “);
 inOrderTraversal(root.right);
 }
 }
 public static void main(String[] args) {
 BinarySearchTree bst = new BinarySearchTree();
 bst.insert(50);
 bst.insert(30);
 bst.insert(20);
 bst.insert(40);
 bst.insert(70);
 bst.insert(60);
 bst.insert(80);
 System.out.println(“In-order traversal of the BST:”);
 bst.inOrderTraversal(bst.root);
 }
}
Output:
In-order traversal of the BST:
20 30 40 50 60 70 80
Recommended Technical Course
- Full Stack Development Course
- Generative AI Course
- DSA C++ Course
- Data Analytics Course
- Python DSA Course
- DSA Java Course
Benefits of Learning Basic Java Programs For Beginners
Learning basic Java programs as a beginner offers numerous benefits that serve as a solid foundation for further advancement in Java programming and software development. Some key benefits include:
- Understanding Core Programming Concepts: Basic Java programs introduce beginners to fundamental programming concepts such as variables, data types, operators, conditional statements, loops, arrays, and functions. By mastering these concepts, beginners develop a strong understanding of how programs work and how to manipulate data.
- Building Problem-Solving Skills: Practicing basic Java programs challenges beginners to think critically and solve problems efficiently. They learn how to break down complex problems into smaller, more manageable tasks, design algorithms, and implement solutions using Java syntax and constructs.
- Gaining Confidence in Coding: As beginners write and execute their first Java programs, they gain confidence in their coding abilities. With each successful program they create, they become more comfortable with Java syntax, programming logic, and the development environment. This confidence motivates them to tackle more challenging programming tasks.
- Preparing for Advanced Concepts: Basic Java programs lay the groundwork for learning advanced Java concepts and techniques. Once beginners grasp the basics, they can delve into topics such as object-oriented programming, data structures, algorithms, graphical user interfaces (GUIs), web development, and more. A solid understanding of basic Java programs is essential for mastering these advanced topics.
- Exploring Career Opportunities: Java is one of the most widely used programming languages in the software industry, powering applications across various domains, including web development, mobile app development, enterprise software, and big data analytics. By learning basic Java programs, beginners open doors to a wide range of career opportunities in software development, IT consulting, cybersecurity, and other tech-related fields.
- Enhancing Analytical and Logical Thinking: Writing Java programs requires analytical and logical thinking skills. Beginners learn how to analyze problems, identify patterns, develop algorithms, and implement solutions step by step. These problem-solving skills are valuable not only in programming but also in various aspects of life and professional work.
- Joining a Thriving Community: Java has a large and vibrant community of developers, educators, and enthusiasts who actively share knowledge, resources, and support. By learning basic Java programs, beginners can connect with this community through online forums, coding communities, meetups, and workshops. They can seek guidance, ask questions, collaborate on projects, and learn from others’ experiences, accelerating their learning journey.
Overall, learning basic Java programs provides beginners with a solid foundation in programming fundamentals, problem-solving skills, and confidence to pursue further learning and career opportunities in the dynamic field of software development.
Basic Java Programs for Beginners FAQ's
How can beginners benefit from practicing basic Java programs?
Practicing basic Java programs helps beginners:
Understand core programming concepts and principles
Improve problem-solving skills and logical thinking
Gain familiarity with Java syntax, keywords, and constructs
Build confidence in writing and debugging Java code
Prepare for more advanced Java programming challenges and projects
Lay a solid foundation for pursuing a career in software development or computer science.
Where can beginners find resources for learning basic Java programs?
Beginners can find resources for learning basic Java programs from various sources, including:
Online tutorials and courses (e.g., Codecademy, Udemy, Coursera)
Java programming books for beginners
Java programming forums and communities (e.g., Stack Overflow, Reddit)
Educational websites and blogs dedicated to Java programming
Practice websites and coding platforms offering Java programming challenges and exercises.
How should beginners approach practicing basic Java programs?
Beginners should start by understanding the problem statement or task given in each program. They should then break down the problem into smaller steps, design a solution using pseudocode or flowcharts, and gradually translate it into Java code.
What are basic Java programs for beginners?
Basic Java programs for beginners are simple programs designed to introduce fundamental concepts of Java programming, such as variables, data types, loops, conditional statements, arrays, and functions. These programs typically cover basic operations like arithmetic calculations, string manipulation, pattern printing, and simple data structures.
Why are basic Java programs important for beginners?
Basic Java programs serve as building blocks for understanding more complex Java concepts. They help beginners grasp the syntax and structure of the Java programming language, develop problem-solving skills, and gain confidence in writing code.