Java is an object-oriented programming language independent of platforms and provides a high degree of efficiency and reliability. It is employed in the development of numerous applications.
It is important to clarify important concepts related to Java programming for interviews. Some crucial topics are arrays, strings, trees, graphs, dynamic programming, etc. This article consists of basic Java program code to help you start your preparation for your next Java interview.
Basic Java Program Code: Practice is the Key
Learning to code can be a little tricky, as it cannot be said how much time it will take to learn programming. However, practising is crucial to mastering programming. People who want to be Java programmers must solve a good number of programming questions.
Also, remember, do not just solve. Grasp the concept and understand the logic working behind it. This article consists of basic to advanced programming problems that programmers at different levels must practice and solve.
Also Read: Basic Java Code Examples: For Interviews, Basic & Beginners
Basic Java Program Code: What is the importance of Upskilling
Learning new skills and concepts is crucial in this era where technology is everything. Learning new skills and upscaling yourself will help you adapt and develop according to the latest developments. If someone has an ideal job, just depending on it and not improving can be fatal. Constant learning and moving forward are important for effective career growth.
Candidates who constantly improve their skills and keep learning have a greater chance of quick promotion and career growth opportunities. Companies also value skilled employees and don’t want to lose them easily. You can get good opportunities and packages based on your skills and easily compensate for your offers in front of the companies.
Basic Java Program Code: Importance of Optimised Code
For someone who is just starting with Java programming, optimising code is not the first priority. The initial phase of learning programming is to learn the basics and fundamentals of the language you choose. Start with learning Java syntax. Start understanding the logic of the problem you are given. After building the logic, try to code yourself without any help from any resources.
Practice is the main key to learning programming. After understanding the logic of a problem, try implementing a brute force approach and then move toward optimising your code gradually. Interviewers often ask you to optimize your code during interviews. However, you will first start with basic brute force code. Building an optimised code is the responsibility of a software developer to utilise resources effectively and increase productivity.
Also Read: AWT And Swing In Java: Difference Between Them
Basic Java Program Code: Java Basic Programs for Interviews
Let us check some beginner-level programming that are frequently asked during tech interviews to assess your basic understanding of Java. Candidates must be familiar with these basic Java program code at the first stage of learning Java programming.
Q1. Write a program to print the Java ‘Hello World!” program.
Ans: The Hello World is the first program you will learn to write in Java. Check the code to print ‘Hello World’ using Java program in the table below.
Basic Java Program Code: Hello World Program |
// FileName : “HelloWorld.java”.
class HelloWorld { // Prints “Hello, World!” public static void main(String args[]) { System.out.println(“Hello World!”); } } |
Output
HelloWorld! |
Q2. Write a Java Program to get input from the user.
Ans: Check the code in the table below.
Basic Java Program Code: Get input from the user in Java |
import java.util.Scanner;
public class UserInputExample { public static void main(String[] args) { // Create a Scanner object to receive input from the user Scanner scanner = new Scanner(System.in); // Prompt to get input from user in Java System.out.print(“Enter your name: “); // Read the user’s input as a String String userName = scanner.nextLine(); // Display the input System.out.println(“Hello, ” + userName + “!”); // Close the scanner to release used resources scanner.close(); } } |
Output
Enter your name:
Ankit Hello Ankit! |
Q3. Write a program in Java to swap two numbers.
Ans: Check the basic Java Program code to swap given two numbers in the table below.
Basic Java Program Code: Swap two numbers using Java |
public class SwapVariables {
public static void main(String[] args) { // Declare and initialize two variables int firstNumber = 5; int secondNumber = 10; System.out.println(“Before swapping:”); System.out.println(“First Number: ” + firstNumber); System.out.println(“Second Number: ” + secondNumber); // Swap the values using a temp variable int temp = firstNumber; firstNumber = secondNumber; secondNumber = temp; System.out.println(“\nAfter swapping:”); System.out.println(“First Number: ” + firstNumber); System.out.println(“Second Number: ” + secondNumber); } } First Number: 10 SecondNumber: 5 |
Q4. Write a program in Java to check if a given integer is even or odd?
Ans: Check the brute force approach for checking whether a given integer value is even or odd.
Basic Java Program Code: Even or Odd |
import java.util.Scanner;
public class CheckEvenOdd{ public static void main(String[] args) { // Create a Scanner object to get user input Scanner scanner = new Scanner(System.in); // Prompt the user to enter an integer System.out.print(“Enter an integer: “); // Read the entered integer int number = scanner.nextInt(); // Check if the number is even or odd using brute force if (isEven(number)) { System.out.println(“The given integer”+number+ ” is an even number.”); } else { System.out.println(“The given integer”+number + ” is an odd number.”); } // Close the scanner scanner.close(); } // Brute force method to check if a number is even private static boolean isEven(int num) { return num % 2 == 0; } } |
Output
Enter an integer:
68 The given integer 68 is an even Number. |
Q5. Write a Java program to calculate the LCM of two numbers.
Ans: LCM (Least Common Multiple) is the largest number that can divide both the given numbers. Let us write Java code to find the LCM of two given numbers.
Basic Java Program Code: LCM of two numbers |
public class Main {
public static void main(String[] args) { System.out.print(“Enter the first integer: “); int x = scanner.nextInt(); System.out.print(“Enter the second integer: “); int y = scanner.nextInt(); // maximum number between x and y is stored in LCM lcm = (x > y) ? x : y; // Always true while(true) { if( lcm % x == 0 && lcm % y == 0 ) { System.out.printf(“The LCM of %d and %d: %d.”, x, y, lcm); break; } ++lcm; } } } |
Output
Enter the first integer:
5 Enter the second integer: 12 The LCM of 5 and 12: 60 |
Q6. Write a Java program to print the factorial of a number.
Ans: Check the basic Java program code to calculate the factorial of a number.
Basic Java Program Code: Factorial of a number |
import java.util.Scanner;
public class FactJava { public static void main(String[] args) { // Create a Scanner object to read input from the user 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 to release 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); } } } |
Q7. Write a Java program to convert decimal number to binary expression.
Ans:
Basic Java Program Code: Convert to binary integer |
import java.util.Scanner;
public class DecimalToBinaryConverter { public static void main(String[] args) { // Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Prompt the user to enter a decimal number System.out.print(“Enter a decimal number: “); // Read the entered decimal number int decimalNumber = scanner.nextInt(); // Convert decimal to binary using a brute-force approach String binaryRepresentation = convertDecimalToBinary(decimalNumber); // Display the binary representation System.out.println(“Binary representation of ” + decimalNumber + ” is: ” + binaryRepresentation); // Close the scanner to release resources scanner.close(); } // Brute-force method to convert decimal to binary private static String convertDecimalToBinary(int decimal) { StringBuilder binary = new StringBuilder(); while (decimal > 0) { binary.insert(0, decimal % 2); // Divide the decimal number by 2 for the next iteration decimal /= 2; } // We need to handle when the input is 0. if (binary.length() == 0) { binary.append(0); } return binary.toString(); } } |
Q8. Write a Java program to perform linear search.
Ans: Linear search is a simple and effective searching algorithm. Its time complexity is O(N) where N is the size of the array.
Basic Java Program Code: Linear Search in Java |
public class LinearSearch {
public static void main(String args[]){ int array[] = {12, 4, 19, 11, 22, 14, 10}; int size = array.length; int value = 11; for (int i=0 ;i< size-1; i++){ if(array[i]==value){ System.out.println(“Element found at index:”+ i); } else{ System.out.println(“Element not found”); } } } } |
Output
Element found at index: 3 |
Q9. Write a Java program to implement binary search.
Ans: Binary searching is a searching technique which can be easily implemented on a sorted array. Its time complexity is O(logN), where N is the size of array.
Basic Java Program Code: Binary Search in Java |
class Solution { int binarysearch(int arr[], int n, int k) { int start=0; int end=n-1; int mid; while(start<=end){ mid=(start+end)/2; if(arr[mid]==k) return mid; else if(arr[mid]>k) end= mid-1; else start = mid+1; } return -1; }} |
Q10. Write a basic Java program code to sort an array.
Ans: Java consists of a predefined sort method that can easily be used to sort an array. Beginners can use it to sort a given array.
Basic Java Program Code: Sort an array in Java |
import java.util.Arrays;
class SortArray { public static void main(String args[]) { int[] arr = { 5, -6, 13, 6, 87, -43, 112 }; System.out.println(“The original array is: “); for (int element : arr) { System.out.print(element + ” “); } Arrays.sort(arr); System.out.println(“\nThe sorted array is: “); for (int element : arr) { System.out.print(element + ” “); } } } |
Output
The original array is:
5, -6, 13, 6, 87, -43, 112 The sorted array is: -43, -6, 5, 6, 87, 112 |
Q11. Write a Java program to check if a string/number is palindrome or not.
Ans: The table below consists of a code to check whether a given number is palindrome.
Basic Java Program Code: Check Palindrome |
class Main {
public static void main(String[] args) { String str = “Rotor”, reverseStr = “”; int strLength = str.length(); for (int i = (strLength – 1); i >=0; –i) { reverseStr = reverseStr + str.charAt(i); } if (str.toLowerCase().equals(reverseStr.toLowerCase())) { System.out.println(str + ” is a Palindrome String.”); } else { System.out.println(str + ” is not a Palindrome String.”); } } } |
Output
Rotor is a palindrome String. |
Q12. Write a Java program code to check whether a number is prime.
Ans: The basic Java code to check whether a number is prime or not is given in the table below. The function isPrime helps to check if a given number is prime or not. If it is prime it returns 1 otherwise 0.
Basic Java Program Code: Check Prime |
class Solution{
static int isPrime(int N){ // code here int isPrime=1; if(N == 0 || N == 1){ isPrime=0; } for(int i=2; i<= Math.sqrt(N); i++){ if(N%i == 0){ isPrime=0; } } return isPrime; } } |
Learn Java Programming with Data Structure
Hurry! Step your career ahead with our Decode Java with DSA Course to master Java Programming along with Data structures and Algorithms. The course is a complete package to start your career as a Java developer. Learn major skills of the hour with industry-recognized certifications, placement assistance, 7+ real-time projects, and much more. Know more only at @pwskills.com
For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group
Basic Java Program Code FAQs
What are some basic Java program codes?
Some of the beginner Java programs that beginners must start learning Java programs with are prime numbers, factorial numbers, linear search, palindrome numbers, etc. These questions are frequently asked during the interview to assess the basic knowledge of candidates.
What is Java Basic Syntax?
Java basic syntax is the guidelines and command format that need to be followed to code in Java. Every programming language has its own syntax, which the computer understands. Programmers need to stick to the syntax while coding.
Is Java easy for beginners?
Java is a well-versed language that can be learned through practice and proper learning. If you are patient and disciplined, learning any programming language would be easy. Java is a very popular language used by most developers worldwide. Hence, it is not impossible to master. Keep learning.
What are some of the Java IDEs available online?
Some of the best Java IDEs are Eclipse, NetBeans. Android Studio, PW Lab, JEdit, etc.