Java Inner Classes and String Handling
by Vibrant Publishers
Introduction
This Java tutorial deals with Java Inner Classes & String handling. Java Inner Classes are an extraordinary feature in Java. In simple terms, an inner class is a class declared inside a class. In a broad sense, inner classes generally include these four types:
- Member inner class
- Local inner class
- Anonymous inner class
- Static inner class
Creation of an Inner class:
You will create an inner class just like how you do it for a general class. The only difference is that the inner class is always declared inside a class. An inner class can have private access, protected access, public access, and package access.
The code given below will explain the concept in detail:
Here we declared the inner class as ‘private’ which makes it accessible only inside the outer class. The java main class will access the inner class via an instance of its outer class.
Types of Inner class
1. Member inner class:
The member inner class is the most common inner class, and its definition will be inside another class, as given below:
class Circle { double radius = 0; public Circle(double radius) { this.radius = radius; } class Draw { public void drawSahpe() { System.out.println(“draw shape”); } } } |
In this way, the class Draw looks like a member of the class Circle, which is called the outer class. Member inner class has unconditional access to all member properties and member methods of outer classes, including private members and static members.
However, we must note that when a member’s inner class owns a member variable or method with the same name as an outer class, a hidden phenomenon occurs, i.e. a member of the member’s inner class is accessed by default. If you want to access the same member of an outer class, you need to access it in the following form:
OuterClass.this.MemberVariable; OuterClass.this.MemberMethod; |
2. Local inner class:
A local inner class is a class that is defined in a method or scope, and the difference between it and the member inner class is that access to the local inner class is limited to the method or within the scope.
class Animals{ public Animals() { } } class Mammals{ public Mammals(){ } public Animals getHerbivorous(){ class Herbivorous extends Animals{ int number =0; } return new Herbivorous(); } } |
The local inner classes, like a local variable within a method, cannot have public, protected, private, and static modifiers.
3. Anonymous inner class:
Anonymous inner classes as it sounds don’t have a name. Using anonymous inner classes when writing code for purposes like event monitoring etc. is not only convenient but also makes code easier to maintain.
For a normal class, any number of constructors are possible. But in the case of anonymous inner classes, we can’t have any constructors just because they don’t have any name which is a must for defining a constructor. Due to this most of the anonymous inner classes are used for interface callbacks.
Let’ see an example:
interfaceWeight { int x = 81; void getWeight(); } class AnonymousInnerClassDemo { public static void main(String[] args) { // WeightClass is implementation class of Weight interface WeightClass obj=new WeightClass(); // calling getWeight() method implemented at WeightClass obj.getWeight(); } } // WeightClass implement the methods of Weight Interface class WeightClass implements Weight { @Override public void getWeight() { // printing the wight System.out.print(“Weight is “+x); } } |
Here we had to create a separate class ‘WeightClass’ to override methods of an interface. But if we use the anonymous inner class feature we can easily achieve the same result by including the following code block inside the class ‘AnonymousInnerClassDemo’.
Weight obj = new Weight() { @Override public void getWeight() { System.out.println(“Weight is “+x); } }; |
Here an object of ‘Weight’ is not created but an object of ‘WeightClass’ is created and copied in the entire class code as shown above.
4. Static inner class:
Static inner classes are also classes defined within another class, except that there is one more keyword ‘static’ in front of the class. Static inner class does not need to rely on external classes, which is somewhat similar to the static member properties of classes, and understandably, they cannot use non-static member variables or methods of external classes. Because, without objects of external classes, you can create objects for static inner classes. Allowing access to non-static members of an external class creates a contradiction because non-static members of the outer class must be attached to specific objects.
public class Test { public static void main(String[] args) { Outter.Inner inner = new Outer.Inner(); } }
class Outer { public Outer() { } static class Inner { public Inner() { } } } |
String Handling in Java:
All the string handling operations in Java are powered by the Java String class. The String class is also known as an immutable character sequence. It is located in the java.lang package, and the Java program imports all classes under java.lang package by default.
Java strings are Unicode character sequences, such as the string “Java” is composed of four Unicode characters ‘J’, ‘a’, ‘v’, ‘a’. We can use the scanner class in Java to parse an input string.
There are multiple operations on a string that we can do with the Java String class. The following code will provide an idea of string handling operations that we can do in Java:
public class StringHandlingDemo { public static void main(String[] args) {
String stringX = “core Java”; String stringY = “Core Java”;
//Extract the character with subscript 3 System.out.println( stringX.charAt(3));
//Find the length of a string System.out.println( stringY.length());
//Compares two strings for equality System.out.println( stringX.equals(stringY));
//Compare two strings (ignore case) System.out.println( stringX.equalsIgnoreCase(stringY));
//Whether the string stringX contains word Java System.out.println( stringX.indexOf(“Java”));
//Whether the string stringX contains word apple System.out.println( stringX.indexOf(“apple”));
//Replace spaces in stringX with & String result = stringX.replace(‘ ‘, ‘&’); System.out.println(“the result is:” + result);
//Whether the string start with ‘core’ System.out.println( stringX.startsWith(“core”));
//Whether the string end with ‘Java’ System.out.println( stringX.endsWith(“Java”));
//Extract substring: from the beginning of the subscript 4 to the end of the string result = stringX.substring(4); System.out.println(result);
//Extract substring: subscript [4, 7) does not include 7 result = stringX.substring(4, 7); System.out.println(result);
//String to Lowercase result = stringX.toLowerCase(); System.out.println(result);
//String to uppercase result = stringX.toUpperCase(); System.out.println(result); String stringZ = ” How old are you!! “;
//Strip spaces from the beginning and end of a string. Note: the space in the middle cannot be removed result = stringZ.trim(); System.out.println(result);
//Because String is an immutable string, stringZ is unchanged System.out.println(stringZ);
String stringZ1 = “Olympics”; String stringZ2 = “Olympics”; String stringZ3 = new String(“Winner”);
//String comparison operations System.out.println( stringZ1 == stringZ2); System.out.println( stringZ1 == stringZ3); System.out.println( stringZ1.equals(stringZ3));
//String concatenation operation System.out.println(stringZ1+” “+stringZ3);
} } |
The output of the above code will be:
Output: e 9 false true 5 -1 the result is:core&Java true true Java Ja core java CORE JAVA How old are you!! How old are you!! true false false Olympics Winner |
End note:
We learned about inner classes and string handling in Java in this blog. In Java, inner classes are very useful while implementing features such as event listening, code abstraction, etc. It also makes the Java code more concise and reusable. String handling operations like java string split etc. are a must for any Java programmer and are the most commonly used feature in Java language.
Get one step closer to your dream job!
Prepare for your Java programming interview with Core Java Questions You’ll Most Likely Be Asked. This book has a whopping 290 technical interview questions on Java Collections: List, queues, stacks, and Declarations and access control in Java, Exceptional Handling, Wrapper class, Java Operators, Java 8 and Java 9, etc. 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
We’ve updated our blogs to reflect the latest changes in Java technologies.
This blog was previously uploaded on April 1st, 2020, and has been updated on January 6th, 2022.
Share