Basic Simple Java Programs

Simple Java Programs for Beginners Example: If you’re looking to get into coding, learning Java is a great place to start. It’s a stable and popular programming language that can be used in many different industries. And once you know how to code in Java, it becomes easier to reuse that code for other purposes.

In this article, we will explore some of the Simple Java Programs to understand the fundamentals of basic Java programming. Java is a versatile language that can be used to build a variety of applications. In order to code in Java, everything must be contained within a class. Once you have created your class, you can save it with a .java extension.

Coding-related questions are common in interviews, so it is beneficial to have a strong foundation in the basics of Java programming. In order to increase your coding skills or knowledge, you can check this Simple Java Program for Beginners with Examples and output.

Post Type:Java Programs For Beginners
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Basic Simple Java Programs

Basic Simple Java Programs

How do you write a text file using Java Selenium with an example program?

package com.selenium.mix;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteTextFile {
   public static void main(String[] args) throws IOException 
   {
      // TODO Auto-generated method stub
      File f=new File("G:\\Git_Base_Folder\\softwaretestingblog\\Selenium\\src\\com\\selenium\\mix\\Selenium Text");
      FileWriter fw=new FileWriter(f);
      BufferedWriter bw=new BufferedWriter(fw);
      bw.write("Welcome to My Testing Blof");
      bw.newLine();
      bw.write("www.softwareteastingblog.in");
      bw.close();
   }
}
package com.java.Softwaretestingblog;
class ab
{
   public void a()
   {
      System.out.println("Inside Method A");
   }
}
public class ParentReference extends ab
{
   public void a()
   {
      System.out.println("Inside Overriding Method A");
   }
   public void b()
   {
      System.out.println("Inside Method B");
   }
   @SuppressWarnings("unused")
   public static void main(String[] args) 
   {
      //ab obj=new ab();
      //obj.a();
      ab abc=new ParentReference();
      abc.a();
      ParentReference abx=new ParentReference();
      //abx.a();
      //abx.b();
      //ParentReference aby=new ab();
   }
}

Execution: The Parent Reference Final output link

Output:

Inside Overriding Method A
package com.java.Softwaretestingblog;
public class RemoveSpaceInASentence {
   public static void main(String[] args) {
      // Remove Spaces Java Program
      String str = "For More Testing Interview Questions Visit Software Testing Blog  ";
      System.out.println("Entered  String:- "+str);
      //1. Using replaceAll() Method
      String strWithoutSpace = str.replaceAll("\\s", "");
      System.out.println("Remove Space With Using Replaceall Method:- "+strWithoutSpace);         
//Output : ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog

      //2. Without Using replaceAll() Method
      char[] strArray = str.toCharArray();
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < strArray.length; i++)
      {
         if( (strArray[i] != ' ') && (strArray[i] != '\t') )
         {
            sb.append(strArray[i]);
         }
      }
      System.out.println("After Remove The Space From The Sentence:- "+sb);           //Output : CoreJavajspservletsjdbcstrutshibernatespring
   }
}

Output:

Entered String:- For More Testing Interview Questions Visit Software Testing Blog
Remove Space With Using Replaceall Method:- ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog
After Remove The Space From The Sentence:- ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog
package com.java.Softwaretestingblog;
public class WideningExample 
{
   public static void main(String[] args) 
{
      // TODO Auto-generated method stub
      //Conversion lower ro higher is called wideining
      //byte->short->int->float->long->double
      int i = 100; 

      //automatic type conversion
      long l = i; 

      //automatic type conversion
      float f = l; 
      System.out.println("Int value "+i);
      System.out.println("Long value "+l);
      System.out.println("Float value "+f);
   }
}

Output:

Int value 100
Long value 100
Float value 100.0

How to Find First Repeated & Non-Repeated Character In Java?

package com.softwaretestingblog.programs;
import java.util.HashMap;
import java.util.Scanner;
public class Non_Repeated_Character {
   static void firstRepeatedNonRepeatedChar(String inputString)
   {
      //Creating a HashMap containing char as a key and occurrences as a value
      HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
      //Converting inputString to char array
      char[] strArray = inputString.toCharArray();
      //Checking each char of strArray
      for (char c : strArray)
      {
         if(charCountMap.containsKey(c))
         {
            //If char is present in charCountMap, incrementing it's count by 1
            charCountMap.put(c, charCountMap.get(c)+1);
         }
         else
         {
            //If char is not present in charCountMap,
            //adding this char in charCountMap with 1 as it's value
            charCountMap.put(c, 1);
         }
      }
      //checking for first non-repeated character
      for (char c : strArray)
      {
         if (charCountMap.get(c) == 1)
         {
            System.out.println("First Non-Repeated Character In '"+inputString+"' is '"+c+"'");
            break;
         }
      }
      //checking for first repeated character
      for (char c : strArray)
      {
         if (charCountMap.get(c) > 1)
         {
            System.out.println("First Repeated Character In '"+inputString+"' is '"+c+"'");

            break;
         }
      }
   }
   public static void main(String[] args)
   {
      @SuppressWarnings("resource")
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the string :");
      String input = sc.next();
      firstRepeatedNonRepeatedChar(input);
   }
}
package com.java.Softwaretestingblog;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Axy
{ 
   @SuppressWarnings("unused")
   private void cube(String n)
   {
      System.out.println(n);
   } 
}
public class Reflection_APIEx {
   public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
      // TODO Auto-generated method stub
      @SuppressWarnings("rawtypes")
      Class c=Axy.class; 
      Object obj=c.newInstance(); 

      @SuppressWarnings("unchecked")
      Method m=c.getDeclaredMethod("cube",new Class[]{String.class}); 
      m.setAccessible(true); 
      m.invoke(obj,"SoftwareTestingBlog");
   }
}
Output:
SoftwareTestingBlog

Simple Java Program Object With Example?

package com.java.Softwaretestingblog;
class top
{
   int b=20;
   void m1()
   {
      System.out.println("Inside Super Class");
   }
}
public class DifferentialObject {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      new top();
      new top().b=30;
      //System.out.println(b); //Differential Objects Can't be Outside
      top obj=new top();
      obj.b=30;
      System.out.println("The Value Of B:- "+obj.b);
   }
}

Output:

The Value Of B:- 30
package com.softwaretestingblog.programs;
public class PairOfElementsInArray {
   static void findThePairs(int inputArray[], int inputNumber)
   {
      System.out.println("Pairs of elements whose sum is "+inputNumber+" are : ");
      for (int i = 0; i < inputArray.length; i++)
      {
         for (int j = i+1; j < inputArray.length; j++)
         {
            if(inputArray[i]+inputArray[j] == inputNumber)
            {
               System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
            }
         }
      }
   }
   public static void main(String[] args)
   {
      findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);
      /*findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);
        findThePairs(new int[] {12, 13, 40, 15, 8, 10, -15}, 25);
        findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);*/
   }
}

Output:

Pairs of elements whose sum is 10 are :
4 + 6 = 10
5 + 5 = 10
-10 + 20 = 10
package com.java.Softwaretestingblog;
import java.util.HashSet;
public class FindDistinctElement {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashSet<Price> lhm = new HashSet<Price>();
      lhm.add(new Price("Banana", 20));
      lhm.add(new Price("Apple", 40));
      lhm.add(new Price("Orange", 30));
      for(Price pr:lhm){
         System.out.println(pr);
      }
      Price duplicate = new Price("Banana", 20);
      System.out.println("inserting duplicate object...");
      lhm.add(duplicate);
      System.out.println("After insertion:");
      for(Price pr:lhm){
         System.out.println(pr);
      }
   }
}
class Price{
   private String item;
   private int price;
   public Price(String itm, int pr){
      this.item = itm;
      this.price = pr;
   }
   public int hashCode(){
      System.out.println("In hashcode");
      int hashcode = 0;
      hashcode = price*20;
      hashcode += item.hashCode();
      return hashcode;
   }
   public boolean equals(Object obj){
      System.out.println("In equals");
      if (obj instanceof Price) {
         Price pp = (Price) obj;
         return (pp.item.equals(this.item) && pp.price == this.price);
      } else {
         return false;
      }
   }
   public String getItem() {
      return item;
   }
   public void setItem(String item) {
      this.item = item;
   }
   public int getPrice() {
      return price;
   }
   public void setPrice(int price) {
      this.price = price;
   }
   public String toString(){
      return "item: "+item+"  price: "+price;
   }
}

Output:

In hashcode
In hashcode
In hashcode
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20
inserting duplicate object...
In hashcode
In equals
After insertion:
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20
package com.java.Softwaretestingblog;
import java.util.Scanner;
public class SumOfDigits {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Scanner in=new Scanner(System.in);
      System.out.println("Enter the number");
      int sum=0,n,a;
      n=in.nextInt();
      while(n>0)
      {
         a=n%10;
         n=n/10;
         sum=sum+a;
      }
      System.out.println("Sum of digits=" +sum);
   }
}

Output:

Enter the number: 1254
Sum of digits=12
package com.java.interviewFAQ;
import java.io.IOException;
public class RunExeFiles 
{
   public static void main(String[] args) throws IOException 
   {
      Runtime.getRuntime().exec("C:\\Windows\\notepad.exe");
   }
}

package com.softwaretestingo.array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MergeTwoArrayWithUniqueValues 
{
	/**
	 * Create Unique Array By Merging
	 * Two Arrays
	 * @param args
	 */
	public static void main(String[] args) 
	{
	// Arrays provided
        String[] array1 = {"Ava", "Emma", "Olivia"};
        String[] array2 = {"Olivia", "Sophia", "Emma"};
        
        // HashSet to store unique elements from both arrays
        Set<String> mergedArray = new HashSet<>();
        
        // Adding elements from array1 to the HashSet
        for (String element : array1) 
        {
        	mergedArray.add(element);
        }
        
        // Adding elements from array2 to the HashSet
        for (String element : array2) 
        {
        	mergedArray.add(element);
        }
        
        // Convert HashSet to array
        String[] outputArray = mergedArray.toArray(new String[0]);
        
        // Output the result
        System.out.println("First Array: "+Arrays.toString(array1));
        System.out.println("Second Array: "+Arrays.toString(array2));
        System.out.println("Merged Array: "+Arrays.toString(outputArray));
	}
}

Output:

First Array: [Ava, Emma, Olivia]
Second Array: [Olivia, Sophia, Emma]
Merged Array: [Olivia, Ava, Emma, Sophia]

package com.softwaretestingo.array;
public class FindLargestPalindromeStringFromArray 
{
	public static void main(String[] args) 
	{
		// Input array of strings
		String[] array = { "aaa", "aba", "adda", "acdea", "aeda" };

		// Variable to store the largest palindrome
		String largestPalindrome = "";

		// Iterate through each string in the array
		for (String str : array) 
		{
			// Check if the string is a palindrome
			if (isPalindrome(str)) 
			{
				// Update largest palindrome if the current string is larger
				if (str.length() > largestPalindrome.length()) 
				{
					largestPalindrome = str;
				}
			}
		}

		// Output the largest palindrome found
		System.out.println("The biggest palindrome is: " + largestPalindrome);
	}

	// Function to check if a string is a palindrome
	public static boolean isPalindrome(String str) 
	{
		int left = 0;
		int right = str.length() - 1;

		// Iterate through the string from both ends
		while (left < right) 
		{
			// If characters at both ends are different, it's not a palindrome
			if (str.charAt(left) != str.charAt(right)) 
			{
				return false;
			}
			left++;
			right--;
		}
		// If the loop completes without returning false, the string is a palindrome
		return true;
	}
}

Output:

The biggest palindrome is: adda

package com.softwaretestingo.collectedpgms.numbers;
public class NumberReplaceMent 
{
	public static void main(String[] args) 
	{
		for (int i = 1; i <= 100; i++) 
		{
			// Check if the number ends with 3 or is divisible by 3
			if (i % 10 == 3) 
			{
				System.out.print("Car" + ", ");
			}
			// Check if the number is divisible by 5
			else if (i % 10 == 5) 
			{
				System.out.print("Bus" + ", ");
			}
			// If none of the above conditions are met, print the number itself
			else 
			{
				System.out.print(i + ", ");
			}
		}
	}
}

Output:

1, 2, Car, 4, Bus, 6, 7, 8, 9, 10, 11, 12, Car, 14, Bus, 16, 17, 18, 19, 20, 21, 22, Car, 24, Bus, 26, 27, 28, 29, 30, 31, 32, Car, 34, Bus, 36, 37, 38, 39, 40, 41, 42, Car, 44, Bus, 46, 47, 48, 49, 50, 51, 52, Car, 54, Bus, 56, 57, 58, 59, 60, 61, 62, Car, 64, Bus, 66, 67, 68, 69, 70, 71, 72, Car, 74, Bus, 76, 77, 78, 79, 80, 81, 82, Car, 84, Bus, 86, 87, 88, 89, 90, 91, 92, Car, 94, Bus, 96, 97, 98, 99, 100, 

package com.softwaretestingo.collectedpgms.strings;
import java.util.Arrays;
public class SortCharacters 
{
	public static void main(String[] args) 
	{
		// Input string
		String input = "aBcA1bC2";

		// Variables to store groups
		StringBuilder lowerCase = new StringBuilder();
		StringBuilder upperCase = new StringBuilder();
		StringBuilder numbers = new StringBuilder();

		// Separate characters into groups
		for (char ch : input.toCharArray()) 
		{
			if (Character.isLowerCase(ch)) 
			{
				lowerCase.append(ch);
			} else if (Character.isUpperCase(ch)) 
			{
				upperCase.append(ch);
			} else if (Character.isDigit(ch)) 
			{
				numbers.append(ch);
			}
		}

		// Sort each group
		char[] lowerCaseArray = lowerCase.toString().toCharArray();
		char[] upperCaseArray = upperCase.toString().toCharArray();
		char[] numbersArray = numbers.toString().toCharArray();

		Arrays.sort(lowerCaseArray);
		Arrays.sort(upperCaseArray);
		Arrays.sort(numbersArray);

		// Concatenate sorted groups
		String result = new String(lowerCaseArray) + new String(upperCaseArray) + new String(numbersArray);

		// Output the result
		System.out.println("Original String: " + input);
		System.out.println("Final Output: " + result);
	}
}

Output:

Original String: aBcA1bC2
Final Output: abcABC12

package com.softwaretestingo.collectedpgms.strings;
public class SumOfNumbers 
{
	public static void main(String[] args) 
	{
		// Input string
		String input = "1a b23c de45f";

		// Variable to store the sum
		int sum = 0;

		// Variable to store the current number
		StringBuilder currentNumber = new StringBuilder();

		// Iterate through each character in the input string
		for (char ch : input.toCharArray()) 
		{
			// Check if the character is a digit
			if (Character.isDigit(ch)) 
			{
				// Append the digit to the current number
				currentNumber.append(ch);
			}
			else 
			{
				// If the current number is not empty, add it to the sum and reset it
				if (currentNumber.length() > 0) 
				{
					sum += Integer.parseInt(currentNumber.toString());
					currentNumber.setLength(0); // Reset the current number
				}
			}
		}

		// Add the last number if it exists
		if (currentNumber.length() > 0) 
		{
			sum += Integer.parseInt(currentNumber.toString());
		}

		// Output the sum
		System.out.println("Original String Is: "+input);
		System.out.println("Sum of numbers: " + sum);
	}
}

Output:

Original String Is: 1a b23c de45f
Sum of numbers: 69

package com.softwaretestingo.collectedpgms.strings;
public class CaesarCipher_ShiftKLetters 
{
	public static void main(String[] args) 
	{
		// Input string
		String input = "HELLO";

		// Key for Caesar cipher
		int key = 3;

		// Variable to store the encrypted string
		StringBuilder output = new StringBuilder();

		// Iterate through each character in the input string
		for (char ch : input.toCharArray()) 
		{
			// Check if the character is a letter
			if (Character.isLetter(ch)) 
			{
				// Determine whether to shift the letter up or down the alphabet
				char base = Character.isUpperCase(ch) ? 'A' : 'a';
				// Apply the Caesar cipher encryption
				char encryptedChar = (char) (((ch - base + key) % 26) + base);
				// Append the encrypted character to the output
				output.append(encryptedChar);
			} 
			else 
			{
				// If the character is not a letter, append it to the output as is
				output.append(ch);
			}
		}

		// Output the encrypted string
		System.out.println("Input: "+input);
		System.out.println("After Shiffting each character " + key +" letters");
		System.out.println("Output: " + output.toString());
	}
}

Output:

Input: HELLO
After Shiffting each character 3 letters
Output: KHOOR

package com.softwaretestingo.collectedpgms.array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicatesFromArray 
{
	public static void main(String[] args) 
	{
		// Input array
		int[] input = { 5, 2, 6, 8, 6, 7, 5, 2, 8 };

		// HashSet to store unique elements
		Set<Integer> uniqueElements = new HashSet<>();

		// Add elements from the input array to the HashSet
		for (int num : input) 
		{
			uniqueElements.add(num);
		}

		// Convert HashSet back to array
		int[] output = new int[uniqueElements.size()];
		int index = 0;
		for (int num : uniqueElements) 
		{
			output[index++] = num;
		}

		// Sort the output array (optional, if you want the output to be sorted)
		Arrays.sort(output);

		// Output the unique elements
		System.out.println("Original Array: " + Arrays.toString(input));
		System.out.println("Output String: " + Arrays.toString(output));
	}
}

Output:

Original Array: [5, 2, 6, 8, 6, 7, 5, 2, 8]
Output String: [2, 5, 6, 7, 8]
package com.softwaretestingo.interviewprograms;

import java.util.ArrayList;
import java.util.List;

public class InterviewPrograms_112_ReverseAlphabetOnlyByKeepingDigitsAsItIs {
	/**
	 * 
	 * Input: test1234epam6789 Output: tset1234mape6789
	 * 
	 * URL: https://www.softwaretestingo.com/core-java-tutorial/
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		String str = "test1234epam6789";
		// tset1234mape6789
		StringBuilder sb = new StringBuilder();
		StringBuilder word = new StringBuilder();

		for (int i = 0; i < str.length(); i++) 
		{
			char ch = str.charAt(i);
			if (Character.isLetter(ch)) 
			{
				word.append(ch);
			} 
			else
			{
				sb.append(reverse(word.toString()));
				sb.append(ch);
				word.setLength(0);
			}
		}
		System.out.println("Input: "+str);
		System.out.println("Output: "+sb);
	}

	public static String reverse(String str)
	{
		String rev = "";
		for (int i = 0; i < str.length(); i++) 
		{
			rev = str.charAt(i) + rev;
		}
		return rev;
	}
}

Sharing some important programs asked in SDET/automation testing interviews:

  • Reversal of String.
  • Reverse each word of a string
  • String palindrome
  • Duplicate elements in an array
  • The second largest element in an array
  • Anagram program
  • Find the missing number in an array
  • Find the first repeated character in the given string
  • Easy Star pattern programs
  • Reverse string with preserving the position of spaces
  • Segregate binary 0 and 1 Array
  • Matrix multiplication in Java
  • Swap two numbers without using a third variable
  • Armstrong number
  • Factorial program
  • Palindrome number
  • Fibonacci series
  • Prime number

How to read/parse JSON array using Java
How to read/write from Excel sheet using Java
How to read/write from a file using Java

Conclusion:

This Java interview questions and answers tutorial will help you crack your next Java interview. We’ve covered Simple Java program questions and answers that are frequently asked by interviewers. With this guide, you’ll be ready to tackle any question thrown your way.

If you’re struggling with these Java programs, please leave a comment below. In addition to this article on Simple Java Programs for Beginners, if you come across any other interview questions, please let us know in the comment section, and we’ll update the article accordingly.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment