StringEquals.java
package com.apryll.package1; public class StringEquals { public static void main(String[] args) { jack(); jill(); } public static void jack() { String s1 = "hill5"; String s2 = "hill" + "5"; System.out.println(s1 == s2); } public static void jill() { String s1 = "hill5"; String s2 = "hill" + s1.length(); System.out.println(s1 == s2); } }
Output
true 5 false
Reason
Because, when a string object is instantiated it cross checks with a memory pool if that String is already created. If it is already created then it maps the new variable to the already existing variable. Therefore both these variables are same objects. In jack() at compile time java knows that both the object are same and uses the same instance for referring to it.
In jill First “hill” is created as a String object, then a new StringBuilder object is created which will help in concatenating two values. After the concatenation is done then it is converted back to a new String object. Real values are known at runtime only.
————————————————————————-
StringClass.java
public class StringClass { public static void main(String[] args) { int a = 10 + 20; System.out.println(a); } } class String { private final String str; public String(String str) { this.str = str; } }
Output
Error: Main method not found in class StringClass, please define the main method as: public static void main(String[] args) ...
Reason
We do not have a main method with the expected signature. “main” method should have a String array as argument, but in our code the String array is compiled to be our custom String class and not the “java.lang.String” class. Therefore we get the error as main method missing.
Fix
Change the main method signature as public static void main(java.lang.String[] args).
————————————————————————-