Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Print Upper Star Triangle Pattern
Next article icon

Java Program to Print Reverse Pyramid Star Pattern

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Approach:

1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object.

2. Now run two loops

  • Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,
    • Run an inner loop from 1 to 'i-1'
    • Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)

Illustration:

Input: number = 7   Output:  *************  ***********   *********    *******     *****      ***       *

Methods: We can print a reverse pyramid star pattern using the following methods:

  1. Using while loop
  2. Using for loop
  3. Using do-while loop

Example 1: Using While Loop

Java
// Java program to Print Reverse Pyramid Star Pattern // Using While loop  // Importing input output classes import java.io.*;  // Main class class GFG {      // Main driver method     public static void main(String[] args)     {         // Declaring and initializing variable to         // Size of the pyramid         int number = 7;          int i = number, j;          // Nested while loops         // Outer loop          // Till condition holds true         while (i > 0) {             j = 0;              // Inner loop             // Condition check             while (j++ < number - i) {                 // Print whitespaces                 System.out.print(" ");             }              j = 0;              // Inner loop             // Condition check             while (j++ < (i * 2) - 1) {                 // Print star                 System.out.print("*");             }              // By now, we reach end of execution for one row             // so next line             System.out.println();              // Decrementing counter because we want to print             // reverse of pyramid             i--;         }     } } 

Output
*************  ***********   *********    *******     *****      ***       *

Steps to solve this problem:

1. Initialize the size of the pyramid 'number =7' and the variables 'i' and 'j'.

2. The outer loop will run through rows of the pyramid with 'i' starting from number and decrementing by 1 in each iteration.

3. First inner loop will start to print the gaps in each row with 'j' starting from 'i' and incrementing by 1 until it reaches number.

4. Now start second inner loop with 'j' starting at 1 and increment it by 1 until it reaches (2 * i - 1) to print the stars in each row.

5. Print new line to end each row, then repeat steps 3 through 5 until the outer loop ends.

Example 2: Using for Loop

Java
// Java program to print reverse pyramid star pattern // Using for loop import java.io.*;  class GFG{      public static void main (String[] args)  {          // Size of the pyramid     int number = 7;     int i, j;          // Outer loop handle the number of rows     for(i = number; i >= 1; i--)     {                  // Inner loop print space         for(j = i; j < number; j++)         {             System.out.print(" ");         }                  // Inner loop print star         for(j = 1; j <= (2 * i - 1); j++)         {             System.out.print("*");         }                  // Ending line after each row         System.out.println("");     }  } } 

Output
*************  ***********   *********    *******     *****      ***       *

Example 3: Using do-while Loop

Java
// Java program to Print Reverse Pyramid Star Pattern // Using do-while loop  // Importing input output classes import java.io.*;  // Main Class public class GFG {      // Main driver method     public static void main(String[] args)     {         // Declare and initialize variable to         // Size of the pyramid         int number = 7;          int i = number, j;          // Outer loop iterate until i > 0 is false         do {             j = 0;              // First inner do-while loop             do {                  // Prints space until j++ < number - i is                 // false                 System.out.print(" ");             } while (j++ < number - i);             j = 0;              // Second inner do-while loop              // Inner loop prints star             // until j++ < i * 2 - 2 is false             do {                  // print star                 System.out.print("*");             }              while (j++ < i * 2 - 2);              // Print whitespace             System.out.println("");         }          // while of outer 'do-while' loop         while (--i > 0);     } } 

Output
 *************   ***********    *********     *******      *****       ***        *

Complexity Analysis :

Time Complexity : O(N^2)

Space Complexity : O(1)


Next Article
Java Program to Print Upper Star Triangle Pattern

A

ankita_saini
Improve
Article Tags :
  • Java
  • Java Programs
Practice Tags :
  • Java

Similar Reads

    Java Programs - Java Programming Examples
    In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
    8 min read

    Java Basic Programs

    How to Read and Print an Integer Value in Java?
    The given task is to take an integer as input from the user and print that integer in Java. To read and print an integer value in Java, we can use the Scanner class to take input from the user. This class is present in the java.util package.Example input/output:Input: 357Output: 357Input: 10Output:
    3 min read
    Ways to Read Input from Console in Java
    In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassBuffered Reader Class is the classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an I
    5 min read
    Java Program to Multiply two Floating-Point Numbers
    The float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of the Float class can hold a single float value. The task is to multiply two Floating point
    1 min read
    Java Program to Swap Two Numbers
    Problem Statement: Given two integers m and n. The goal is simply to swap their values in the memory block and write the java code demonstrating approaches.Illustration:Input : m=9, n=5Output : m=5, n=9 Input : m=15, n=5Output : m=5, n=15Here 'm' and 'n' are integer valueApproaches:There are 3 stand
    6 min read
    Java Program to Add Two Binary Strings
    When two binary strings are added, then the sum returned is also a binary string. Example: Input : x = "10", y = "01" Output: "11"Input : x = "110", y = "011" Output: "1001" Explanation: 110 + 011 =1001Approach 1: Here, we need to start adding from the right side and when the sum returned is more th
    3 min read
    Java Program to Add two Complex Numbers
    Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last. General form fo
    3 min read
    Java Program to Check if a Given Integer is Odd or Even
    A number that is divisible by 2 and generates a remainder of 0 is called an even number. All the numbers ending with 0, 2, 4, 6, and 8 are even numbers. On the other hand, number that is not divisible by 2 and generates a remainder of 1 is called an odd number. All the numbers ending with 1, 3, 5,7,
    7 min read
    Java Program to Find the Largest of three Numbers
    Problem Statement: Given three numbers x, y, and z of which aim is to get the largest among these three numbers.Example: Input: x = 7, y = 20, z = 56Output: 56 // value stored in variable zFlowchart For Largest of 3 numbers:Algorithm to find the largest of three numbers:1. Start2. Read the three num
    4 min read
    Java Program to Find LCM of Two Numbers
    LCM (i.e. Least Common Multiple) is the largest of the two stated numbers that can be divided by both the given numbers. In this article, we will write a program to find the LCM in Java Java Program to Find the LCM of Two NumbersThe easiest approach for finding the LCM is to Check the factors and th
    2 min read
    Java Program to Find GCD or HCF of Two Numbers
    GCD (i.e. Greatest Common Divisor) or HCF (i.e. Highest Common Factor) is the largest number that can divide both the given numbers. Example: HCF of 10 and 20 is 10, and HCF of 9 and 21 is 3.Therefore, firstly find all the prime factors of both the stated numbers, then find the intersection of all t
    2 min read
    Java Program to Display All Prime Numbers from 1 to N
    For a given number N, the purpose is to find all the prime numbers from 1 to N.Examples: Input: N = 11Output: 2, 3, 5, 7, 11Input: N = 7Output: 2, 3, 5, 7 Approach 1:Firstly, consider the given number N as input.Then apply a for loop in order to iterate the numbers from 1 to N.At last, check if each
    4 min read
    Java Program to Find if a Given Year is a Leap Year
    Leap Year contains 366 days, which comes once every four years. In this article, we will learn how to write the leap year program in Java. Facts about Leap YearEvery leap year corresponds to these facts : A century year is a year ending with 00. A century year is a leap year only if it is divisible
    5 min read
    Java Program to Check Armstrong Number between Two Integers
    A positive integer with digits p, q, r, s…, is known as an Armstrong number of order n if the following condition is fulfilled. pqrs... = pn + qn + rn + sn +....Example: 370 = 3*3*3 + 7*7*7 + 0 = 27 + 343 + 0 = 370Therefore, 370 is an Armstrong number. Examples: Input : 100 200 Output :153 Explanati
    2 min read
    Java Program to Check If a Number is Neon Number or Not
    A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range. Illustration: Case 1: Input : 9 Output : Given number 9 is Neon number Explanation : square of 9=9*9=81; sum of digit of square : 8+1=9(which
    3 min read
    Java Program to Check Whether the Character is Vowel or Consonant
    In this article, we are going to learn how to check whether a character is a vowel or a consonant. So, the task is, for any given character, we need to check if it is a vowel or a consonant. As we know, vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ and all the other characters (i.e. ‘b’, ‘c’, ‘d’, ‘f’ …..) are
    4 min read
    Java Program for Factorial of a Number
    The factorial of a non-negative integer is multiplication of all integers smaller than or equal to n. In this article, we will learn how to write a program for the factorial of a number in Java.Formulae for Factorialn! = n * (n-1) * (n-2) * (n-3) * ........ * 1 Example:6! == 6*5*4*3*2*1 = 720. 5! ==
    3 min read
    Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
    For a given positive integer N, the purpose is to find the value of F2 + F4 + F6 +………+ F2n till N number. Where Fi indicates the i'th Fibonacci number. The Fibonacci Series is the numbers in the below-given integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ……Examples: Input: n = 4 Output: 3
    4 min read
    Java Program to Calculate Simple Interest
    Simple interest is a quick method of calculating the interest charge on a loan. Simple interest is determined by multiplying the daily interest rate by the principal by the number of days that elapse between payments. Simple interest formula is given by:Simple Interest = (P x T x R)/100 Where, P is
    2 min read
    Java Program for compound interest
    Compound Interest formula: Formula to calculate compound interest annually is given by: Compound Interest = P(1 + R/100)t Where, P is principal amount R is the rate and T is the time span Example: Input : Principal (amount): 1200 Time: 2 Rate: 5.4 Output : Compound Interest = 1333.099243 Java Code J
    1 min read
    Java Program to Find the Perimeter of a Rectangle
    A Rectangle is a quadrilateral with four right angles (90°). In a rectangle, the opposite sides are equal. A rectangle with all four sides equal is called a Square. A rectangle can also be called as right angled parallelogram. Rectangle In the above rectangle, the sides A and C are equal and B and D
    2 min read

    Java Pattern Programs

    Java Program to Print Right Triangle Star Pattern
    In this article, we will learn about printing Right Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Right Triangle Star Pattern: Java import java.io.*; // Java code to demonstrate right star triangle public class GeeksForGeeks { // Function to demonstrate printin
    5 min read
    Java Program to Print Left Triangle Star Pattern
    In this article, we will learn about printing Left Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Left Triangle Star Pattern: Java import java.io.*; // java program for left triangle public class GFG { // Function to demonstrate printing pattern public static vo
    5 min read
    Java Program to Print Pyramid Number Pattern
    Here we are getting a step ahead in printing patterns as in generic we usually play with columnar printing in the specific row keep around where elements in a row are either added up throughout or getting reduced but as we move forward we do start playing with rows which hold for outer loop in our p
    2 min read
    Java Program to Print Reverse Pyramid Star Pattern
    Approach: 1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object. 2. Now run two loops Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,Run an inner loop from 1 to 'i-1'Ru another inner loo
    4 min read
    Java Program to Print Upper Star Triangle Pattern
    The upper star triangle pattern means the base has to be at the bottom and there will only be one star to be printed in the first row. Here is the issue that will arise is what way we traverse be it forward or backward we can't ignore the white spaces, so we are not able to print a star in the first
    2 min read
    Java Program to Print Mirror Upper Star Triangle Pattern
    The pattern has two parts - both mirror reflections of each other. The base of the triangle has to be at the bottom of the imaginary mirror and the tip at the top. Illustration: Input: size = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    5 min read
    Java Program to Print Downward Triangle Star Pattern
    Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like * * * * * * * * * * Example Java // Java Program to Print Lower Star Triangle Pattern // Main
    2 min read
    Java Program to Print Mirror Lower Star Triangle Pattern
    In this article, we are going to learn how to print mirror lower star triangle patterns in Java. Illustration: Input: number = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Methods: We can print mirror lower star triangle pa
    5 min read
    Java Program to Print Star Pascal’s Triangle
    Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.In this article, we will look into the process of printing Pascal's tri
    4 min read
    Java Program to Print Diamond Shape Star Pattern
    In this article, we are going to learn how to print diamond shape star patterns in Java. Illustration: Input: number = 7 Output: * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** * Methods: When it comes to pattern printing we do opt for standard ways of
    6 min read
    Java Program to Print Square Star Pattern
    Here, we will implement a Java program to print the square star pattern. We will print the square star pattern with diagonals and without diagonals. Example: ********************** * * * * * * * * * * * * ********************** Approach: Step 1: Input number of rows and columns. Step 2: For rows of
    4 min read
    Java Program to Print Pyramid Star Pattern
    This article will guide you through the process of printing a Pyramid star pattern in Java. 1. Simple pyramid pattern Java import java.io.*; // Java code to demonstrate Pyramid star patterns public class GeeksForGeeks { // Function to demonstrate printing pattern public static void PyramidStar(int n
    5 min read
    Java Program to Print Spiral Pattern of Numbers
    In Java, printing a spiral number is a very common programming task, which helps us to understand loops and array manipulation in depth. In this article, we are going to print a spiral pattern of numbers for a given size n.What is a Spiral Pattern?A spiral pattern is a sequence of numbers arranged i
    3 min read

    Java Conversion Programs

    Java Program to Convert Binary to Octal
    A Binary (base 2) number is given, and our task is to convert it into an Octal (base 8) number. There are different ways to convert binary to decimal, which we will discuss in this article.Example of Binary to Octal Conversion:Input : 100100Output: 44Input : 1100001Output : 141A Binary Number System
    5 min read
    Java Program to Convert Octal to Decimal
    Octal numbers are numbers with 8 bases and use digits from 0-7. This system is a base 8 number system. The decimal numbers are the numbers with 10 as their base and use digits from 0-9 to represent the decimal number. They also require dots to represent decimal fractions.We have to convert a number
    3 min read
    Java Program For Decimal to Octal Conversion
    Given a decimal number N, convert N into an equivalent octal number, i.e., convert the number with base value 10 to base value 8. The decimal number system uses 10 digits from 0-9, and the octal number system uses 8 digits from 0-7 to represent any numeric value.Illustration: Basic input/output for
    3 min read
    Java Program for Hexadecimal to Decimal Conversion
    Given a Hexadecimal (base 16) number N, and our task is to convert the given Hexadecimal number to a Decimal (base 10). The hexadecimal number uses the alpha-numeric values 0-9 and A- F. And the decimal number uses the numeric values 0-9. Example: Input : 1ABOutput: 427Input : 1AOutput: 26Approach t
    3 min read
    Java Program For Decimal to Hexadecimal Conversion
    Given a decimal number N, convert N into an equivalent hexadecimal number i.e. convert the number with base value 10 to base value 16. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.Examples of Decimal to Hexadecimal Conver
    3 min read
    Java Program for Decimal to Binary Conversion
    Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.Examples: Input : 7Output : 111Input: 33Output: 100001Binary-to-decimal conversion is done to convert a number given in the binary system to its equivalent in the decimal
    5 min read
    Java Program for Decimal to Binary Conversion
    Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.Examples: Input : 7Output : 111Input: 33Output: 100001Binary-to-decimal conversion is done to convert a number given in the binary system to its equivalent in the decimal
    5 min read
    Boolean toString() Method in Java
    In Java, the toString() method of the Boolean class is a built-in method to return the Boolean value in string format. The Boolean class is a part of java.lang package. This method is useful when we want the output in the string format in places like text fields, console output, or simple text forma
    2 min read
    Convert String to Double in Java
    In this article, we will convert a String to a Double in Java. There are three methods for this conversion from String to Double, as mentioned below in the article.Methods for String-to-Double ConversionDifferent ways for converting a String to a Double are mentioned below:Using the parseDouble() me
    3 min read
    Java Program to Convert Double to String
    The primary goal of double to String conversion in Java is to store big streams of numbers that are coming where even data types fail to store the stream of numbers. It is generically carried out when we want to display the bigger values. In this article, we will learn How to Convert double to Strin
    3 min read
    Java Program to Convert String to Long
    To convert a String to Long in Java, we can use built-in methods provided by the Long class. In this article, we will learn how to convert String to Long in Java with different methods. Example:In the below example, we use the most common method i.e. Long.parseLong() method to convert a string to a
    3 min read
    Java Program to Convert Long to String
    The long to String conversion in Java generally comes in need when we have to display a long number in a GUI application because everything is displayed in string form. In this article, we will learn about Java Programs to convert long to String. Given a Long number, the task is to convert it into a
    4 min read
    Java Program For Int to Char Conversion
    In this article, we will check how to convert an Int to a Char in Java. In Java, char takes 2 bytes (16-bit UTF encoding ), while int takes 4 bytes (32-bit). So, if we want the integer to get converted to a character then we need to typecast because data residing in 4 bytes cannot get into a single
    3 min read
    Java Program to Convert Char to Int
    Given a char value, and our task is to convert it into an int value in Java. We can convert a Character to its equivalent Integer in different ways, which are covered in this article.Examples of Conversion from Char to Int:Input : ch = '3'Output : 3Input : ch = '9'Output : 9The char data type is a s
    4 min read

    Java Classes and Object Programs

    Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    11 min read
    Abstract Class in Java
    In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-abstract methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in Java but not for Variables. In this article, we will learn the use of abstract classes in Java.
    10 min read
    Singleton Method Design Pattern in Java
    In object-oriented programming, a Java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So, whatever modifications we d
    7 min read
    Java Interface
    An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
    12 min read
    Encapsulation in Java
    In Java, encapsulation is one of the coret concept of Object Oriented Programming (OOP) in which we bind the data members and methods into a single unit. Encapsulation is used to hide the implementation part and show the functionality for better readability and usability. The following are important
    10 min read
    Inheritance in Java
    Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
    13 min read
    Abstraction in Java
    Abstraction in Java is the process of hiding the implementation details and only showing the essential details or features to the user. It allows to focus on what an object does rather than how it does it. The unnecessary details are not displayed to the user.Key features of abstraction:Abstraction
    10 min read
    Difference Between Data Hiding and Abstraction in Java
    Abstraction Is hiding the internal implementation and just highlight the set of services. It is achieved by using the abstract class and interfaces and further implementing the same. Only necessarily characteristics of an object that differentiates it from all other objects. Only the important detai
    6 min read
    Polymorphism in Java
    Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
    7 min read
    Method Overloading in Java
    In Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference may include:The number of parametersThe types of parametersThe order of parametersMethod overloading in Java is also known as Compile-time Polymorphism, Static
    10 min read
    Overriding in Java
    Overriding in Java occurs when a subclass or child class implements a method that is already defined in the superclass or base class. When a subclass provides its own version of a method that is already defined in its superclass, we call it method overriding. The subclass method must match the paren
    15 min read
    Super Keyword in Java
    The super keyword in Java is a reference variable that is used to refer to the parent class when we are working with objects. You need to know the basics of Inheritance and Polymorphism to understand the Java super keyword. The Keyword "super" came into the picture with the concept of Inheritance. I
    7 min read
    Java this Keyword
    In Java, "this" is a reference variable that refers to the current object, or can be said "this" in Java is a keyword that refers to the current object instance. It is mainly used to,Call current class methods and fieldsTo pass an instance of the current class as a parameterTo differentiate between
    6 min read
    static Keyword in Java
    The static keyword in Java is mainly used for memory management, allowing variables and methods to belong to the class itself rather than individual instances. The static keyword is used to share the same variable or method of a given class. The users can apply static keywords with variables, method
    9 min read
    Access Modifiers in Java
    In Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
    7 min read

    Java Methods Programs

    Java main() Method - public static void main(String[] args)
    Java's main() method is the starting point from where the JVM starts the execution of a Java program. JVM will not execute the code if the program is missing the main method. Hence, it is one of the most important methods of Java, and having a proper understanding of it is very important.The Java co
    6 min read
    Difference between static and non-static method in Java
    A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access
    6 min read
    HashTable forEach() method in Java with Examples
    The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration.
    2 min read
    StringBuilder toString() method in Java with Examples
    The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(
    3 min read
    StringBuffer codePointAt() method in Java with Examples
    The codePointAt() method of StringBuffer class returns a character Unicode point at that index in sequence contained by StringBuffer. This method returns the “Unicodenumber” of the character at that index. Value of index must be lie between 0 to length-1. If the char value present at the given index
    2 min read
    How compare() method works in Java
    Prerequisite: Comparator Interface in Java, TreeSet in JavaThe compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value:  0: if (x==y)-1: if (x < y)1: if (x > y)Syntax:   public int compare(Object obj1, Object obj2)where obj1 and obj2 are th
    3 min read
    Short equals() method in Java with Examples
    The equals() method of Short class is a built in method in Java which is used to compare the equality given Object with the instance of Short invoking the equals() method. Syntax ShortObject.equals(Object a) Parameters: It takes an Object type object a as input which is to be compared with the insta
    2 min read
    Difference Between next() and hasNext() Method in Java Collections
    In Java, objects are stored dynamically using objects. Now in order to traverse across these objects is done using a for-each loop, iterators, and comparators. Here will be discussing iterators. The iterator interface allows visiting elements in containers one by one which indirectly signifies retri
    3 min read
    What does start() function do in multithreading in Java?
    We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden ru
    2 min read
    Java Thread.start() vs Thread.run() Method
    In Java's multi-threading concept, start() and run() are the two most important methods. In this article, we will learn the main differences between Thread.start() and Thread.run() in Java. Thread.start() vs Thread.run() MethodThread.start()Thread.run()Creates a new thread and the run() method is ex
    4 min read

    Java Searching Programs

    Java Program for Linear Search
    Linear Search is the simplest searching algorithm that checks each element sequentially until a match is found. It is good for unsorted arrays and small datasets.Given an array a[] of n elements, write a function to search for a given element x in a[] and return the index of the element where it is
    2 min read
    Binary Search in Java
    Binary search is a highly efficient searching algorithm used when the input is sorted. It works by repeatedly dividing the search range in half, reducing the number of comparisons needed compared to a linear search. Here, we are focusing on finding the middle element that acts as a reference frame t
    6 min read
    Java Program To Recursively Linearly Search An Element In An Array
    Given an array arr[] of n elements, write a recursive function to search for a given element x in the given array arr[]. If the element is found, return its index otherwise, return -1.Input/Output Example:Input : arr[] = {25, 60, 18, 3, 10}, Element to be searched x = 3Output : 3 (index )Input : arr
    3 min read

    Java 1-D Array Programs

    Check If a Value is Present in an Array in Java
    Given an array of Integers and a key element. Our task is to check whether the key element is present in the array. If the element (key) is present in the array, return true; otherwise, return false.Example: Input: arr[] = [3, 5, 7, 2, 6, 10], key = 7Output: Is 7 present in the array: trueInput: arr
    8 min read
    Java Program to Find Largest Element in an Array
    Finding the largest element in an array is a common programming task. There are multiple approaches to solve it. In this article, we will explore four practical approaches one by one to solve this in Java.Example Input/Output:Input: arr = { 1, 2, 3, 4, 5}Output: 5Input: arr = { 10, 3, 5, 7, 2, 12}Ou
    4 min read
    Arrays.sort() in Java
    The Arrays.sort() method is used for sorting the elements in an Array. It has two main variations: Sorting the entire array (it may be an integer or character array) Sorting a specific range by passing the starting and ending indices.Below is a simple example that uses the sort() method to arrange a
    6 min read
    Java Program to Sort the Elements of an Array in Descending Order
    Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
    2 min read
    Java Program to Sort the Elements of an Array in Ascending Order
    Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
    2 min read
    Remove duplicates from Sorted Array
    Given a sorted array arr[] of size n, the goal is to rearrange the array so that all distinct elements appear at the beginning in sorted order. Additionally, return the length of this distinct sorted subarray.Note: The elements after the distinct ones can be in any order and hold any value, as they
    7 min read
    Java Program to Merge Two Arrays
    In Java, merging two arrays is a good programming question. We have given two arrays, and our task is to merge them, and after merging, we need to put the result back into another array. In this article, we are going to discuss different ways we can use to merge two arrays in Java.Let's now see the
    5 min read
    Java Program to Check if two Arrays are Equal or not
    In Java, comparing two arrays means checking if they have the same length and identical elements. This checking process ensures that both arrays are equivalent in terms of content and structure.Example:In Java, the simplest way to check if two arrays are equal in Java is by using the built-in Arrays
    3 min read
    Remove all Occurrences of an Element from Array in Java
    In Java, removing all occurences of a given element from an array can be done using different approaches that are,Naive approach using array copyJava 8 StreamsUsing ArrayList.removeAll()Using List.removeIf()Problem Stament: Given an array and a key, the task is to remove all occurrences of the speci
    5 min read
    Java Program to Find Common Elements Between Two Arrays
    Given two arrays and our task is to find their common elements. Examples:Input: Array1 = ["Article", "for", "Geeks", "for", "Geeks"], Array2 = ["Article", "Geeks", "Geeks"]Output: [Article, Geeks]Input: Array1 = ["a", "b", "c", "d", "e", "f"], Array2 = ["b", "d", "e", "h", "g", "c"]Output: [b, c, d,
    4 min read
    Array Copy in Java
    In Java, copying an array can be done in several ways, depending on our needs such as shallow copy or deep copy. In this article, we will learn different methods to copy arrays in Java.Example:Assigning one array to another is an incorrect approach to copying arrays. It only creates a reference to t
    6 min read
    Java Program to Left Rotate the Elements of an Array
    In Java, left rotation of an array involves shifting its elements to the left by a given number of positions, with the first elements moving around to the end. There are different ways to left rotate the elements of an array in Java.Example: We can use a temporary array to rotate the array left by "
    5 min read

    Java 2-D Arrays (Matrix) Programs

    Print a 2D Array or Matrix in Java
    In this article, we will learn to Print 2 Dimensional Matrix. 2D-Matrix or Array is a combination of Multiple 1 Dimensional Arrays. In this article we cover different methods to print 2D Array. When we print each element of the 2D array we have to iterate each element so the minimum time complexity
    4 min read
    Java Program to Add two Matrices
    Given two matrices A and B of the same size, the task is to add them in Java. Examples: Input: A[][] = {{1, 2}, {3, 4}} B[][] = {{1, 1}, {1, 1}} Output: {{2, 3}, {4, 5}} Input: A[][] = {{2, 4}, {3, 4}} B[][] = {{1, 2}, {1, 3}} Output: {{3, 6}, {4, 7}}Program to Add Two Matrices in JavaFollow the Ste
    2 min read
    Sorting a 2D Array according to values in any given column in Java
    We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in Column K.Examples:Input: If our 2D array is given as (Order 4X4) 39 27 11 42 10 93 91 90 54 78 56 89 24 64 20 65Sorting it by values in column 3 Output: 39 27 11 422
    3 min read
    Java Program to Check if two Arrays are Equal or not
    In Java, comparing two arrays means checking if they have the same length and identical elements. This checking process ensures that both arrays are equivalent in terms of content and structure.Example:In Java, the simplest way to check if two arrays are equal in Java is by using the built-in Arrays
    3 min read
    Java Program to Find Transpose of Matrix
    Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[ ][ ] is obtained by changing A[i][j] to A[j][i]. Example of First Transpose of MatrixInput: [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ]Output: [ [ 1 , 4 , 7 ] , [ 2 , 5 , 8 ]
    5 min read
    Java Program to Find the Determinant of a Matrix
    The determinant of a matrix is a special calculated value that can only be calculated if the matrix has same number of rows and columns (square matrix). It is helpful in determining the system of linear equations, image processing, and determining whether the matrix is singular or non-singular.In th
    5 min read
    Java Program to Find the Normal and Trace of a Matrix
    In Java, when we work with matrices, there are two main concepts, and these concepts are Trace and Normal of a matrix. In this article, we will learn how to calculate them and discuss how to implement them in code. Before moving further, let's first understand what a matrix is. What is a Matrix?A ma
    3 min read
    Java Program to Print Boundary Elements of the Matrix
    In this article, we are going to learn how to print only the boundary elements of a given matrix in Java. Boundary elements mean the elements from the first row, last row, first column, and last column.Example:Input : 1 2 3 4 5 6 7 8 9Output: 1 2 3 4 6 7 8 9Now, let's understand the approach we are
    3 min read
    Java Program to Rotate Matrix Elements
    A matrix is simply a two-dimensional array. So, the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner that it should look out as the matrix is rotated.For a given matrix, the ta
    6 min read
    Java Program to Compute the Sum of Diagonals of a Matrix
    For a given 2D square matrix of size N*N, our task is to find the sum of elements in the Principal and Secondary diagonals. For example, analyze the following 4 × 4 input matrix.m00 m01 m02 m03m10 m11 m12 m13m20 m21 m22 m23m30 m31 m32 m33Basic Input/Output:Input 1: 6 7 3 4 8 9 2 1 1 2 9 6 6 5 7 2Out
    4 min read
    Java Program to Interchange Elements of First and Last in a Matrix Across Rows
    For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix. Illustration: Input 1: 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1: 6 7 8 2 2 3 7 2 8 9 1 3 1 1 5 0 Input 2: 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2: 11 21 30 1
    3 min read
    Java Program to Interchange Elements of First and Last in a Matrix Across Columns
    For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix.Example Test Case for the ProblemInput : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Output : 4 2 3 1 8 6 7 5 12 10 11 9 16 14 15 13 Implementation of Interchange Elements o
    2 min read

    Java String Programs

    Java Program to Get a Character from a String
    Given a String str, the task is to get a specific character from that String at a specific index. Examples:Input: str = "Geeks", index = 2Output: eInput: str = "GeeksForGeeks", index = 5Output: F Below are various ways to do so: Using String.charAt() method: Get the string and the indexGet the speci
    5 min read
    Replace a character at a specific index in a String in Java
    In Java, here we are given a string, the task is to replace a character at a specific index in this string. Examples of Replacing Characters in a StringInput: String = "Geeks Gor Geeks", index = 6, ch = 'F'Output: "Geeks For Geeks."Input: String = "Geeks", index = 0, ch = 'g'Output: "geeks"Methods t
    3 min read
    Reverse a String in Java
    In Java, reversing a string means reordering the string characters from the last to the first position. Reversing a string is a common task in many Java applications and can be achieved using different approaches. In this article, we will discuss multiple approaches to reverse a string in Java with
    7 min read
    Java Program to Reverse a String using Stack
    The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack be
    2 min read
    Sort a String in Java (2 different ways)
    The string class doesn't have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String T
    6 min read
    Swapping Pairs of Characters in a String in Java
    Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = “Java”Output: aJav Explanation: The given string contains even number of characters.
    3 min read
    Check if a given string is Pangram in Java
    Given string str, the task is to write Java Program check whether the given string is a pangram or not. A string is a pangram string if it contains all the character of the alphabets ignoring the case of the alphabets. Examples: Input: str = "Abcdefghijklmnopqrstuvwxyz"Output: YesExplanation: The gi
    3 min read
    Print first letter of each word in a string using regex
    Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeksOutput :Gfg Input : United KingdomOutput : UKBelow is the Regular expression to extract
    3 min read
    Java Program to Determine the Unicode Code Point at Given Index in String
    ASCII is a code that converts the English alphabets to numerics as numeric can convert to the assembly language which our computer understands. For that, we have assigned a number against each character ranging from 0 to 127. Alphabets are case-sensitive lowercase and uppercase are treated different
    5 min read
    Remove Leading Zeros From String in Java
    Given a string of digits, remove leading zeros from it.Illustrations: Input : 00000123569Output: 123569Input: 000012356090Output: 12356090Approach: We use the StringBuffer class as Strings are immutable.Count leading zeros by iterating string using charAt(i) and checking for 0 at the "i" th indices.
    3 min read
    Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
    4 min read
    Compare two strings lexicographically in Java
    In this article, we will discuss how we can compare two strings lexicographically in Java. One solution is to use Java compareTo() method. The method compareTo() is used for comparing two strings lexicographically in Java. Each character of both the strings is converted into a Unicode value for comp
    3 min read
    Java program to print Even length words in a String
    Given a string s, write a Java program to print all words with even length in the given string. Example to print even length words in a String Input: s = "i am Geeks for Geeks and a Geek" Output: am GeekExample:Java// Java program to print // even length words in a string class GfG { public static v
    3 min read
    Insert a String into another String in Java
    Given a String, the task is to insert another string in between the given String at a particular specified index in Java. Examples: Input: originalString = "GeeksGeeks", stringToBeInserted = "For", index = 4 Output: "GeeksForGeeks" Input: originalString = "Computer Portal", stringToBeInserted = "Sci
    4 min read
    Split a String into a Number of Substrings in Java
    Given a String, the task it to split the String into a number of substrings. A String in java can be of 0 or more characters. Examples : (a) "" is a String in java with 0 character (b) "d" is a String in java with 1 character (c) "This is a sentence." is a string with 19 characters. Substring: A Str
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences