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 parent class method's name, parameters, and return type.
Rules for Overriding:
- Name, parameters, and return type must match the parent method.
- Java picks which method to run, based on the actual object type, not just the variable type.
- Static methods cannot be overridden.
- The @Override annotation catches mistakes like typos in method names.
Example: In the code below, Dog overrides the move() method from Animal but keeps eat() as it is. When we call move() on a Dog object, it runs the dog-specific version.
Java
// Example of Overriding in Java
class Animal {
// Base class
void move() { System.out.println(
"Animal is moving."); }
void eat() { System.out.println(
"Animal is eating."); }
}
class Dog extends Animal {
@Override void move()
{ // move method from Base class is overriden in this
// method
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}
public class Geeks {
public static void main(String[] args)
{
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking.
}
}
OutputDog is running.
Animal is eating.
Dog is barking.
Explanation: The Animal class defines base functionalities like move() and eat(). The Dog class inherits from Animal and overrides the move() method to provide a specific behavior Dog is running. Both classes can access their own methods. When creating a Dog object, calling move() executes the overridden method.

Note: Method overriding is a key concept in Java that enables Run-time polymorphism. It allows a subclass to provide its specific implementation for a method inherited from its parent class.
Example: This example demonstrates runtime polymorphism in Java, where the show() method is overridden in the Child class, and the method called depends on the object type at runtime.
Java
// Java program to demonstrate
// method overriding in java
class Parent {
// base class or superclass which is going to overriden
// below
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Geeks {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
OutputParent's show()
Child's show()
Explanation: In this code, the Child class inherits from the Parent class and overrides the show() method, providing its own implementation. When a Parent reference points to a Child object, the Child's overridden show() method is executed at runtime, showcasing the principle of polymorphism in Java.
Why Override Methods?
The key reasons to use method overriding in Java are listed below:
- Change how a parent class method works in a subclass, for example, a Dog moves by running, while a Fish might swim.
- It enables polymorphism, that let one method call adapt to different objects at runtime.
- Reuse method names logically instead of creating new ones for minor changes.
Rules for Java Method Overriding
1. Access Modifiers in overriding
A subclass can make an overridden method more accessible, e.g., upgrade protected to public, but not less e.g., downgrade public to private. Trying to hide a method this way causes compiler errors.
Example: Below, Child
legally overrides m2()
with broader public
access, but cannot override m1()
because it’s private
in the parent.
Java
// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("From parent m1()");
}
protected void m2()
{
System.out.println("From parent m2()");
}
}
class Child extends Parent {
// new m1() method
// unique to Child class
private void m1()
{
System.out.println("From child m1()");
}
// overriding method
// with more accessibility
@Override public void m2()
{
System.out.println("From child m2()");
}
}
class Geeks {
public static void main(String[] args)
{
// parent class object
Parent P = new Parent();
P.m2();
// child class object
Parent C = new Child();
C.m2();
}
}
OutputFrom parent m2()
From child m2()
Explanation: Here, the parent class is overridden by the subclass and from the output we can easily identify the difference.
2. Final Methods Cannot Be Overriden
If we don't want a method to be overridden, we declare it as final. Please see Using Final with Inheritance.
Note: If a method is declared as final, subclasses cannot override it.
Example: This example demonstrates that final methods in Java cannot be overridden in subclasses.
Java
// A Java program to demonstrate that
// final methods cannot be overridden
class Parent {
// Can't be overridden
final void show() {}
}
class Child extends Parent {
// This would produce error
void show() {}
}
Output:
3. Static Methods Cannot Be Overridden (Method Hiding)
When we define a static method with the same signature as a static method in the base class, it is known as method hiding.
- Subclass Instance method can override the superclass's Instance method but when we try to override the superclass static method gives a compile time error.
- Subclass Static method generate compile time when trying to override superclass Instance method subclass static method hides when trying to override superclass static method.
Example: This example demonstrates method hiding for static methods in Java, where a static method in the subclass hides the static method in the superclass, while non-static methods can be overridden.
Java
// Java program to show that
// if the static method is redefined by a derived
// class, then it is not overriding, it is hiding
class Parent {
// Static method in base class
// which will be hidden in subclass
static void m1()
{
System.out.println("From parent "
+ "static m1()");
}
// Non-static method which will
// be overridden in derived class
void m2()
{
System.out.println(
"From parent "
+ "non - static(instance) m2() ");
}
}
class Child extends Parent {
// This method hides m1() in Parent
static void m1()
{
System.out.println("From child static m1()");
}
// This method overrides m2() in Parent
@Override public void m2()
{
System.out.println(
"From child "
+ "non - static(instance) m2() ");
}
}
// Driver class
class Geeks {
public static void main(String[] args)
{
Parent obj1 = new Child();
// here parents m1 called.
// bcs static method can not overriden
obj1.m1();
// Here overriding works
// and Child's m2() is called
obj1.m2();
}
}
OutputFrom parent static m1()
From child non - static(instance) m2()
Note: When a subclass defines a static method with the same signature as the parent's static method, it hides the parent method. The method called depends on the reference type, not the object type.
4. Private Methods Cannot Be Overridden
Private methods cannot be overridden as they are bonded during compile time. We cannot even override private methods in a subclass.
Example: This example demonstrates method hiding for private methods in Java, where a private method in the subclass does not override the private method in the superclass, and the subclass's public method overrides the superclass's public method.
Java
class SuperClass {
private void privateMethod()
{
System.out.println(
"it is a private method in SuperClass");
}
public void publicMethod()
{
System.out.println(
"it is a public method in SuperClass");
privateMethod();
}
}
class SubClass extends SuperClass {
// This is a new method with the same name as the
// private method in SuperClass
private void privateMethod()
{
System.out.println(
"it is private method in SubClass");
}
// This method overrides the public method in SuperClass
public void publicMethod()
{
// calls the private method in
// SubClass, not SuperClass
System.out.println(
"it is a public method in SubClass");
privateMethod();
}
}
public class Geeks {
public static void main(String[] args)
{
SuperClass o1 = new SuperClass();
// calls the public method in
// SuperClass
o1.publicMethod();
SubClass o2 = new SubClass();
// calls the overridden public
// method in SubClass
o2.publicMethod();
}
}
Outputit is a public method in SuperClass
it is a private method in SuperClass
it is a public method in SubClass
it is private method in SubClass
5. Method Must Have the Same Return Type (or subtype)
From Java 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a sub-type of the parent’s return type. This phenomenon is known as the covariant return type.
Example: This example demonstrates covariant return types in Java, where the subclass method overrides the superclass method with a more specific return type.
Java
class SuperClass {
public Object method()
{
System.out.println(
"This is the method in SuperClass");
return new Object();
}
}
class SubClass extends SuperClass {
public String method()
{
System.out.println(
"This is the method in SubClass");
return "Hello, World!";
// having the Covariant return type
}
}
public class Geeks {
public static void main(String[] args)
{
SuperClass obj1 = new SuperClass();
obj1.method();
SubClass obj2 = new SubClass();
obj2.method();
}
}
OutputThis is the method in SuperClass
This is the method in SubClass
6. Invoking Parent’s Overridden Method Using super
We can call the parent class method in the overriding method using the super keyword.
Note: Use super.methodName() to call the parent's version.
Example: This example demonstrates calling the overridden method from the subclass using super to invoke the superclass method in Java.
Java
// A Java program to demonstrate that overridden
// method can be called from sub-class
// Base Class
class Parent {
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
super.show();
System.out.println("Child's show()");
}
}
// Driver class
class Geeks{
public static void main(String[] args)
{
Parent o = new Child();
o.show();
}
}
OutputParent's show()
Child's show()
Overriding and Constructor
We cannot override the constructor as the parent and child class can never have a constructor with the same name (the constructor name must always be the same as the Class name).
Exception-Handling in Overriding
Below are two rules to note when overriding methods related to exception handling.
Rule 1: If the super-class overridden method does not throw an exception, the subclass overriding method can only throw the unchecked exception, throwing a checked exception will lead to a compile-time error.
Example: Below is an example of a Java program when the parent class method does not declare the exception.
Java
// Java program to demonstrate overriding when
// superclass method does not declare an exception
class Parent {
void m1() { System.out.println("From parent m1()"); }
void m2() { System.out.println("From parent m2()"); }
}
class Child extends Parent {
@Override
// no issue while throwing unchecked exception
void m1() throws ArithmeticException
{
System.out.println("From child m1()");
}
@Override
// compile-time error
// issue while throwing checked exception
void m2() throws Exception
{
System.out.println("From child m2");
}
}
Output:
Explanation: This example shows that uper-class overridden method does not throw an exception, the subclass overriding method can only throw the exception because the super class does not declare the exception.
Rule 2: If the superclass overridden method does throw an exception, the subclass overriding method can only throw the same, subclass exception. Throwing parent exceptions in the Exception hierarchy will lead to compile time error. Also, there is no issue if the subclass overridden method does not throw any exception.
Example: This example demonstrate overriding when superclass method does declare an exception.
Java
class Parent {
void m1() throws RuntimeException
{
System.out.println("From parent m1()");
}
}
class Child1 extends Parent {
@Override void m1() throws RuntimeException
{
System.out.println("From child1 m1()");
}
}
class Child2 extends Parent {
@Override void m1() throws ArithmeticException
{
System.out.println("From child2 m1()");
}
}
class Child3 extends Parent {
@Override void m1()
{
System.out.println("From child3 m1()");
}
}
class Child4 extends Parent {
@Override void m1() throws Exception
{
// This will cause a compile-time error due to the
// parent class method not declaring Exception
System.out.println("From child4 m1()");
}
}
public class MethodOverridingExample {
public static void main(String[] args)
{
Parent p1 = new Child1();
Parent p2 = new Child2();
Parent p3 = new Child3();
Parent p4 = new Child4();
// Handling runtime exceptions for each child class
// method
try {
p1.m1();
}
catch (RuntimeException e) {
System.out.println("Exception caught: " + e);
}
try {
p2.m1();
}
catch (RuntimeException e) {
System.out.println("Exception caught: " + e);
}
try {
p3.m1();
}
catch (Exception e) {
System.out.println("Exception caught: " + e);
}
// Child4 throws a compile-time error due to
// mismatched exception type
try {
p4.m1(); // This will throw a compile-time error
}
catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
}
Output:
Overriding and Abstract Method
Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.
Overriding and Synchronized/strictfp Method
The presence of a synchronized/strictfp modifier with the method has no effect on the rules of overriding, i.e. it’s possible that a synchronized/strictfp method can override a non-synchronized/strictfp one and vice-versa.
Example: This example demonstrates multi-level method overriding in Java, where a method is overridden across multiple levels of inheritance, and the method called is determined at runtime.
Java
// A Java program to demonstrate
// multi-level overriding
// Base Class
class Parent {
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
void show() { System.out.println("Child's show()"); }
}
// Inherited class
class GrandChild extends Child {
// This method overrides show() of Parent
void show()
{
System.out.println("GrandChild's show()");
}
}
// Driver class
class Geeks {
public static void main(String[] args)
{
Parent o = new GrandChild();
o.show();
}
}
OutputGrandChild's show()
Method Overriding vs Method Overloading
This image demonstrates the difference between method overloading (same method name but different parameters in the same class) and overriding (same method signature in a subclass, replacing the superclass method).

The table below demonstrates the difference between Method Overriding and Method Overloading.
Features | Method Overriding | Method Overloading |
---|
Definition | Method overriding is about the same signature in subclass. | Method overloading is about same method name, different parameters. |
---|
Polymorphism | It is also known as Runtime polymorphism | It is also known as Compiletime polymorphism |
---|
Inheritance | Requires inheritance. | Can be in the same class or subclass |
---|
Return Type | Return type must be same | Return type can be different |
---|
Exceptions | Must follow overriding rules. | No restrictions. |
---|
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 JavaIn 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 NumbersThe 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 NumbersProblem 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 StringsWhen 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 NumbersComplex 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 EvenA 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 NumbersProblem 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 NumbersLCM (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 NumbersGCD (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 NFor 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 YearLeap 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 IntegersA 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 NotA 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 ConsonantIn 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 NumberThe 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 IndexesFor 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 InterestSimple 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 interestCompound 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 RectangleA 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 PatternIn 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 PatternIn 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 PatternHere 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 PatternApproach: 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 PatternThe 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 PatternThe 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 PatternDownward 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 PatternIn 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 TrianglePascalâ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 PatternIn 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 PatternHere, 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 PatternThis 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 NumbersIn 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 OctalA 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 DecimalOctal 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 ConversionGiven 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 ConversionGiven 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 ConversionGiven 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 ConversionGiven 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 ConversionGiven 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 JavaIn 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 JavaIn 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 StringThe 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 LongTo 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 StringThe 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 ConversionIn 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 IntGiven 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 JavaIn 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 JavaIn 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 JavaIn 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 InterfaceAn 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 JavaIn 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 JavaJava 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 JavaAbstraction 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 JavaAbstraction 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 JavaPolymorphism 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 JavaIn 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 JavaOverriding 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 JavaThe 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 KeywordIn 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 JavaThe 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 JavaIn 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 JavaA 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 ExamplesThe 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 ExamplesThe 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 ExamplesThe 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 JavaPrerequisite: 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 ExamplesThe 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 CollectionsIn 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() MethodIn 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 SearchLinear 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 JavaBinary 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 ArrayGiven 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 JavaGiven 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 ArrayFinding 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 JavaThe 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 OrderHere, 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 OrderHere, 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 ArrayGiven 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 ArraysIn 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 notIn 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 JavaIn 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 ArraysGiven 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 JavaIn 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 ArrayIn 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 JavaIn 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 MatricesGiven 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 JavaWe 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 notIn 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 MatrixTranspose 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 MatrixThe 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 MatrixIn 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 MatrixIn 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 ElementsA 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 MatrixFor 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 RowsFor 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 ColumnsFor 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 StringGiven 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 JavaIn 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 JavaIn 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 StackThe 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 JavaGiven 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 JavaGiven 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 regexGiven 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 StringASCII 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 JavaGiven 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 JavaString 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 JavaIn 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 StringGiven 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 JavaGiven 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 JavaGiven 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