When you instantiate an object, why do you specify the class twice?
OddEven number = new OddEven();
Why can't you just say number = new OddEven();? When I declare a string, I only say String once:
String str = "abc";
Actually, my question is not "why do you do it this way" -- obviously, you do it because you have to -- but rather, why did the creators choose to make Java syntax work like this?
My thoughts are:
There is something fundamental to the way Java operates at a low level that necessitates typing the name twice, or
The creators freely choose to do it this way to keep some aspect of the syntax uniform -- declare the type first? Or was it to be more like its predecessors?
Because you can do this:
Superclass x = new Subclass();
The type of the reference can be a superclass of the actual object being declared, so you need to specify both. For example, you can do:
List<String> stringList = new ArrayList<String>();
Your program interacts with objects that implement List, and you don't care about the implementation.,
The reason for the seemingly redundant type name is that you are performing two separate operations, each of which requires you to specify a type.
On the left side, you are declaring a variable (a storage location) with a particular type. On the right side, you are creating a new object with a particular type. The '=' in the middle causes a reference to the new object you created to be placed in the storage location you created.
The types on each side do not have to be the same. This, for example, is legal code:
Object number = new OddEven();
The reason that the keyword String only shows up once in your second example is that the type String is implied on the right hand side since "xxx" is a String constant. It is simply shorthand for:
String string = new String("xxx");
When you write:
OddEven number = new OddEven();
You actually do two things : 1) you declare a variable number of type OddEven and 2) you assign a reference to a new instance of class OddEven. But because a variable can hold any subtype of a type, writing number = new OddEven(); wouldn't be enough for the compiler to know the real type of the number variable. So, you have to declare it too. Java is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. You may want to read the whole Chapter 4. Types, Values, and Variables of the Java Language Specification (JLS) to learn more on this.
Now, when your write:
String str = "abc";
Things are a bit different. Characters enclosed in double quotes, "abc" here, are called a string literal which is already a reference to an instance of String and always refers to the same instance of class String. Quoting the section 3.10.5 String Literals of the JLS:
Each string literal is a reference
(§4.3) to an instance
(§4.3.1, §12.5) of class
String (§4.3.3). String
objects have a constant value. String
literals-or, more generally, strings
that are the values of constant
expressions (§15.28)-are
"interned" so as to share unique
instances, using the method
String.intern.
So, String str = "abc"; is certainly not converted into String str = new String("abc"); which is absolutely not equivalent as I've read in some comments and answers. Running the following class:
public class Test {
public static void main(String[] args) {
String one = "abc";
String two = "abc";
String abc = new String("abc");
System.out.println(one == two);
System.out.println(one == abc);
}
}
Produces the output below:
true
false
And demonstrates that one and two are references to the same instance but that abc is a reference to another instance (i.e. an extra unnecessary object has been created).
Actually, using new String(String) is a inefficient way to construct new strings and should only be used to force a substring to copy to a new underlying character array, as in
String tiny = new String(monster.substring(10,20))
Think of 'OddEven number' as defining the Object and 'new OddEven();' as filling the object.
I'm not going to get into detail about superclasses and subclasses because other people have explained it already.
When you say String name = "foo", internally Java compiler creates a String object with the value "foo" and it assigns its reference to name variable. So, here instead of creating a new String object, we are assigning a reference to the other String object.
Btw, the compiler anyway creates "foo" for us. It first looks in String Pool, if it not exists, only then it creats "foo". Otherwise, Compiler returns a reference from String pool. This is some optimization that Java compiler performs internally.
String name = "foo" is simlar to OddEvenNumber oddEven = anotherOddEvenObject;
Array example:
declaration and initialization - when you know the length of the array:
int[] numberArray = new int[10];
declaration then initialization - when you don’t know the length of the array yet and might get it from a method or user input
int[] numberArray;
int length = 10; // let’s say we got this from the user
numberArray = new int[length];
Initialization only - when you don’t need to reuse:
return new int[10];
First OddEven is the type, second is the instance. It need not be even OddEven, it could be any subclass of OddEven. It does not mean you have type it twice. Any IDE have code templates where you have to type the name only once.
The first declaration is the type of variable you want to use in the scope you have, in this case it is OddEven, the second declaration is the constructor to use for instantiating (and in this case initializing) the reference.
You could have said INumberInstance = new OddEven(), where INumberInstance is some class which OddEven can be cast to (like a super of OddEven for instance).
The way to create a new object in java is:
Class_name reference_variable = new Class_name(param_if_any);
But the string class is an exception.
You can create a new string object as
String s = "abc";
or
String s = new String("abc");
Further to what Jim said, Java is a statically typed language. That means that every varable has a type that is know at compile time.
For instance:
public class A
{
public void foo() { }
}
public class B
{
public void foo() { }
}
public class Main
{
public static void main(final String[] argv)
{
A a = new A();
B b = new B();
a.foo();
b.foo();
}
}
the compiler looks at "a.foo()" and "b.foo()" and checks to see that a is of type A and A has a method called "foo" that takes no arguments. The compiler does the same for "b.foo()".
If you could write main like this:
public class Main
{
public static void main(final String[] argv)
{
a = new A(); // in Java you would really do Object a = new A();
b = new B(); // in Java you would really do Object b = new B();
a.foo();
b.foo();
}
}
then the compiler could not do that verification and it would have to happen at runtime.
The designers of Java did not have to make the syntax redundant. Scala is another language using the JVM, and it's also statically typed. Scala uses type inferencing to cut out verbosity. For instance here's a declaration of a variable of type MyPair called x. MyPair associates two variables with each other. It's a generic class, so you can specify that the first variable have type Int and the second the type String:
var x: MyPair[Int, String] = new MyPair[Int, String](1, "scala")
Scala type inferencing lets you remove the redundant type declaration:
var x = new MyPair[Int, String](1, "scala")
And Scala even infers types based on the constructor arguments, so you can write it this way:
var x = new MyPair(1, "scala")
Consider the following example,
We can specify the object type as follows,
List<String> abc;
In method1(), if you want to use array list which suits the best for it requirements then we can instantiate like as follows,
abc = new ArrayList<String>();
In method2(), if you want to use Linked array list which suits best for it requirement then we can instantiate like as follows,
abc = new LinkedList<String>();
So, the idea is that we can specify the type of "SuperClass" and instantiate with whatever subclass suitable for different requirements like "LinkedList" and "ArrayList" in the appropriate operation dynamically.
Related
I started with java a couple of weeks ago. Before that i had multiple years working with c/c++ on embedded targets and with c# with UI Stuff on Win PCs.
I got this very simple example:
public class StreamProcessing {
public static void main(String[] args) {
Stream stream = new Stream(); //after this line: Stream string empty
StreamFiller.fillStream(stream); //after this line: Stream string not empty any more
StreamPrinter.printStream(stream);
}
}
I'd expect that whatever StreamFiller.fillStream() does, the argument is copied. However it looks like fillStream is modifying the actual stream object itself.
The Stream class basically contains a string
public class Stream {
private String content = "";
int index = 0;
public char readChar() {
if (index < content.length()) {
return content.charAt(index++);
} else {
return 0;
}
}
public void writeString(String str) {
content += str;
}
}
The Streamfiller should modify it's stream copy but not the original reference
public class StreamFiller {
public static void fillStream( Stream stream ) {
stream.writeString( "This is a" );
stream.writeString( " stream." );
}
}
Please correct me if I'm wrong, but since the actual text of the string class is allocated on the heap, both the StreamProcessing () Stream object and the (supposed copied) local object of fillStream() point to the same address on the heap (yeah i now it's not an actual memory address like in c/c++ but some unique object identifier)
So is my assumption correct? Non trivial objects (aka objects allocated on the heap) are passed by reference?
thx for your help :)
The Java language does not let you make heap / stack distinction in your code the way C and C++ do.
Instead, it divides all data types in to two groups:
Primitive types:
These are simple built in numerical types such as int, double or boolean (not a numerical type in Java).
Note that String is not such a type!
Object types:
If it is a class, it is an object type. This goes for built in types such as String and for user defined types such as your Stream class.
For these types, all you ever see is a reference, whether you are looking at a local variable, class member, instance member, or function parameter.
Lets look at a simple example:
public class A {
public int a;
public static void main(String [] args) {
A var1 = new A();
A var2 = var1;
var1.a = 42;
System.out.println("var2.a = " + var2.a);
}
}
If you compile and run this example it will print 42.
In C++ the line A var2 = var1; would have invoked a copy constructor and created a new object but in Java there is no such thing. If you want a copy, you need to invoke clone method explicitly.
What is held in var1 and copied to var2 is just a reference.
So both vars "point" to the same object.
And again - it does not matter if the class is trivial or not. Even if a class is completely empty, you will still only be given and work with a reference to any object of this class.
As for the primitive types mentioned earlier, Java has wrapper classes such as Integer and Boolean for them.
You might want to read about "boxing" and "unboxing".
One more thing to note is that some types are immutable - that is, they do not provide a way to change their data once created.
String in Java is an immutable type, but it is also a bit different from any other type.
It has special privileges.
While Java does not support operator overloading like C++ does, for String type the language does provide a special + operator that preforms string concatenation.
How ever, since String objects are immutable, any concatenation operation will create a brand new String object, even one like this:
String a = "Hello";
a = a + " world!";
This creates a new string "Hello world" and stores the reference to it in a, leaving the reference to old "Hello" string to be garbage collected at some future point.
Even though in Java everything is passed by value, there is a difference between how primitive data types (such as int, char and boolean) and how reference data types are passed to a method.
When passing the value of a primitive data type, this value can only be changed in the scope of the particular method. When passing the value of a reference data type, the reference will remain the same but the value will change globally (or in whatever scope the object was initialised).
See also this for more information: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
I am creating a lot of objects called: Obj1, Obj2.... ObjX
Object Obj1 = new Object();
Object Obj2 = new Object();
Object ObjX = new Object();
Now I am having a function where I want to get access to one of this objects.
public void useObject(int objectNumber) {
String objectName = "Obj" + objectNumber;
objectName.doAnythingWithThisObject();
}
Is something like that possible in C# or Java? I don't want to use something like:
switch(objectNumber) {
case 1:
Obj1.doThis();
break;
case 2:
Obj2.doThis();
break;
If I would use switch/if-else then I have to repeat a lot of code which make this thing less readable, because I have to call the same function with different objects.
The actual answer is: you shouldn't, generally speaking, access your variables, using strings at runtime. Cases where this is actually appropriate are few and far between and your example, simplified though it may be for illustration purposes, is not a good match for it.
Instead, why don't you simply use a collection or an array to store your objects? #T.R.Rohith gives an example in their answer.
Still, the direct answer to your question, as it applies to Java, is given below. While the code would be different for C#, the language feature, which can be used for this purpose, namely, reflection, is available in C# as well.
If Obj1, Obj2 etc. are declared as static or instance fields in a class, you can get their values by their names using reflection (see relevant docs for Java). If they are local to a method, there is no simple way to do so (see these questions: for Java, for C#).
Static fields
class Something {
static Object obj1 = new Object();
static Object obj2 = new Object();
// etc.
}
(I've taken the liberty of starting field names with lowercase letters, as it the accepted practice in Java.)
In this case you can get the value of the variable by its name using the following code (you need to import java.lang.reflect.Field):
// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is ignored for static fields, so simply pass null.
Object obj = f.get(null);
// Now you can do whatever you want with obj,
// which refers to the same object as static field obj1 of Something.
System.out.println(obj);
Instance fields
class Something {
Object obj1 = new Object();
Object obj2 = new Object();
// etc.
}
You can do it in almost exactly the same way for instance fields, you just need an instance of the class to pass to f.get(). So, for the sake of example, let's assume we have an instance of class Something, called sth.
// Let's say this is an instance of our class
Something sth = new Something();
// ...
// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is the instance of Something,
// for which you want to retrieve the value of an instance field, named obj1.
Object obj = f.get(sth);
// Now you can do whatever you want with obj,
// which refers to the same object as instance field obj1 of sth.
System.out.println(obj);
Local variables
You are probably out of luck in this case. Again, see the following links: Java, C#.
This sounds like a classic Strategy pattern problem Strategy Design Pattern
Here's the code:
//Declare this in the class so that it can be called by any method
static Object[] array = new Object[4];
public static void main()
{
//Use this to initialize it
Object[] array = new Object[4];
for(int i=0;i<4;i++)
{
array[i] = new Object();
}
//You can now easily call it
useObject(0);
useObject(1);
useObject(2);
useObject(3);
}
//Your numbers may be off by 1 because we are using an array but that is easily adjusted
public static void useObject(int objectNumber)
{
array[objectNumber].doAnythingWithThisObject();
}
The answer is... don't. Use an array instead. This is exactly what they're for.
ObjectType[] objectArray = new ObjectType[10]; // Or as many as required.
for (int i = 0; i < objectArray.length; i++) {
objectArray[i] = new ObjectType(); // Or whatever constructor you need.
}
// Then access an individual object like this...
ObjectType obj = objectArray[4];
// Or...
objectArray[5].someMethod();
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:
String s = new String("silly");
Because it creates unnecessary String objects. But instead it should be written like this:
String s = "No longer silly";
Ok fine so far...However, given this class:
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null) {
throw new NullPointerException();
}
this.s = s;
}
:
:
}
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";
Why is the first statement ok? Shouldn't it be
CaseInsensitiveString cis = "Polish";
How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
String is a special built-in class of the language. It is for the String class only in which you should avoid saying
String s = new String("Polish");
Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
is the correct (and only, in this case) thing to do.
I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.
To illustrate, the following code will print true for the first line, but false for the second:
System.out.println("foo" == "foo");
System.out.println(new String("bar") == new String("bar"));
Strings are treated a bit specially in java, they're immutable so it's safe for them to be handled by reference counting.
If you write
String s = "Polish";
String t = "Polish";
then s and t actually refer to the same object, and s==t will return true, for "==" for objects read "is the same object" (or can, anyway, I"m not sure if this is part of the actual language spec or simply a detail of the compiler implementation-so maybe it's not safe to rely on this) .
If you write
String s = new String("Polish");
String t = new String("Polish");
then s!=t (because you've explicitly created a new string) although s.equals(t) will return true (because string adds this behavior to equals).
The thing you want to write,
CaseInsensitiveString cis = "Polish";
can't work because you're thinking that the quotations are some sort of short-circuit constructor for your object, when in fact this only works for plain old java.lang.Strings.
String s1="foo";
literal will go in pool and s1 will refer.
String s2="foo";
this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal.
String s3=new String("foo");
"foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.
String s4=new String("foo");
same as s3
so System.out.println(s1==s2);// **true** due to literal comparison.
and System.out.println(s3==s4);// **false** due to object
comparison(s3 and s4 is created at different places in heap)
Strings are special in Java - they're immutable, and string constants are automatically turned into String objects.
There's no way for your SomeStringClass cis = "value" example to apply to any other class.
Nor can you extend String, because it's declared as final, meaning no sub-classing is allowed.
Java strings are interesting. It looks like the responses have covered some of the interesting points. Here are my two cents.
strings are immutable (you can never change them)
String x = "x";
x = "Y";
The first line will create a variable x which will contain the string value "x". The JVM will look in its pool of string values and see if "x" exists, if it does, it will point the variable x to it, if it does not exist, it will create it and then do the assignment
The second line will remove the reference to "x" and see if "Y" exists in the pool of string values. If it does exist, it will assign it, if it does not, it will create it first then assignment. As the string values are used or not, the memory space in the pool of string values will be reclaimed.
string comparisons are contingent on what you are comparing
String a1 = new String("A");
String a2 = new String("A");
a1 does not equal a2
a1 and a2 are object references
When string is explicitly declared, new instances are created and their references will not be the same.
I think you're on the wrong path with trying to use the caseinsensitive class. Leave the strings alone. What you really care about is how you display or compare the values. Use another class to format the string or to make comparisons.
i.e.
TextUtility.compare(string 1, string 2)
TextUtility.compareIgnoreCase(string 1, string 2)
TextUtility.camelHump(string 1)
Since you are making up the class, you can make the compares do what you want - compare the text values.
The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by
String s = "Hello";
will only create a string object in the pool and the reference s will refer to it, but by using
String s = new String("Hello");
you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.
You can't. Things in double-quotes in Java are specially recognised by the compiler as Strings, and unfortunately you can't override this (or extend java.lang.String - it's declared final).
- How do i make CaseInsensitiveString behave like String so the above statement is ok (with and w/out extending String)? What is it about String that makes it ok to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java right?
Enough has been said from the first point. "Polish" is an string literal and cannot be assigned to the CaseInsentiviveString class.
Now about the second point
Although you can't create new literals, you can follow the first item of that book for a "similar" approach so the following statements are true:
// Lets test the insensitiveness
CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");
assert cis5 == cis6;
assert cis5.equals(cis6);
Here's the code.
C:\oreyes\samples\java\insensitive>type CaseInsensitiveString.java
import java.util.Map;
import java.util.HashMap;
public final class CaseInsensitiveString {
private static final Map<String,CaseInsensitiveString> innerPool
= new HashMap<String,CaseInsensitiveString>();
private final String s;
// Effective Java Item 1: Consider providing static factory methods instead of constructors
public static CaseInsensitiveString valueOf( String s ) {
if ( s == null ) {
return null;
}
String value = s.toLowerCase();
if ( !CaseInsensitiveString.innerPool.containsKey( value ) ) {
CaseInsensitiveString.innerPool.put( value , new CaseInsensitiveString( value ) );
}
return CaseInsensitiveString.innerPool.get( value );
}
// Class constructor: This creates a new instance each time it is invoked.
public CaseInsensitiveString(String s){
if (s == null) {
throw new NullPointerException();
}
this.s = s.toLowerCase();
}
public boolean equals( Object other ) {
if ( other instanceof CaseInsensitiveString ) {
CaseInsensitiveString otherInstance = ( CaseInsensitiveString ) other;
return this.s.equals( otherInstance.s );
}
return false;
}
public int hashCode(){
return this.s.hashCode();
}
// Test the class using the "assert" keyword
public static void main( String [] args ) {
// Creating two different objects as in new String("Polish") == new String("Polish") is false
CaseInsensitiveString cis1 = new CaseInsensitiveString("Polish");
CaseInsensitiveString cis2 = new CaseInsensitiveString("Polish");
// references cis1 and cis2 points to differents objects.
// so the following is true
assert cis1 != cis2; // Yes they're different
assert cis1.equals(cis2); // Yes they're equals thanks to the equals method
// Now let's try the valueOf idiom
CaseInsensitiveString cis3 = CaseInsensitiveString.valueOf("Polish");
CaseInsensitiveString cis4 = CaseInsensitiveString.valueOf("Polish");
// References cis3 and cis4 points to same object.
// so the following is true
assert cis3 == cis4; // Yes they point to the same object
assert cis3.equals(cis4); // and still equals.
// Lets test the insensitiveness
CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");
assert cis5 == cis6;
assert cis5.equals(cis6);
// Futhermore
CaseInsensitiveString cis7 = CaseInsensitiveString.valueOf("SomethinG");
CaseInsensitiveString cis8 = CaseInsensitiveString.valueOf("someThing");
assert cis8 == cis5 && cis7 == cis6;
assert cis7.equals(cis5) && cis6.equals(cis8);
}
}
C:\oreyes\samples\java\insensitive>javac CaseInsensitiveString.java
C:\oreyes\samples\java\insensitive>java -ea CaseInsensitiveString
C:\oreyes\samples\java\insensitive>
That is, create an internal pool of CaseInsensitiveString objects, and return the corrensponding instance from there.
This way the "==" operator returns true for two objects references representing the same value.
This is useful when similar objects are used very frequently and creating cost is expensive.
The string class documentation states that the class uses an internal pool
The class is not complete, some interesting issues arises when we try to walk the contents of the object at implementing the CharSequence interface, but this code is good enough to show how that item in the Book could be applied.
It is important to notice that by using the internalPool object, the references are not released and thus not garbage collectible, and that may become an issue if a lot of objects are created.
It works for the String class because it is used intensively and the pool is constituted of "interned" object only.
It works well for the Boolean class too, because there are only two possible values.
And finally that's also the reason why valueOf(int) in class Integer is limited to -128 to 127 int values.
In your first example, you are creating a String, "silly" and then passing it as a parameter to another String's copy constructor, which makes a second String which is identical to the first. Since Java Strings are immutable (something that frequently stings people who are used to C strings), this is a needless waste of resources. You should instead use the second example because it skips several needless steps.
However, the String literal is not a CaseInsensitiveString so there you cannot do what you want in your last example. Furthermore, there is no way to overload a casting operator like you can in C++ so there is literally no way to do what you want. You must instead pass it in as a parameter to your class's constructor. Of course, I'd probably just use String.toLowerCase() and be done with it.
Also, your CaseInsensitiveString should implement the CharSequence interface as well as probably the Serializable and Comparable interfaces. Of course, if you implement Comparable, you should override equals() and hashCode() as well.
CaseInsensitiveString is not a String although it contains a String. A String literal e.g "example" can be only assigned to a String.
CaseInsensitiveString and String are different objects. You can't do:
CaseInsensitiveString cis = "Polish";
because "Polish" is a String, not a CaseInsensitiveString. If String extended CaseInsensitiveString String then you'd be OK, but obviously it doesn't.
And don't worry about the construction here, you won't be making unecessary objects. If you look at the code of the constructor, all it's doing is storing a reference to the string you passed in. Nothing extra is being created.
In the String s = new String("foobar") case it's doing something different. You are first creating the literal string "foobar", then creating a copy of it by constructing a new string out of it. There's no need to create that copy.
Just because you have the word String in your class, does not mean you get all the special features of the built-in String class.
when they say to write
String s = "Silly";
instead of
String s = new String("Silly");
they mean it when creating a String object because both of the above statements create a String object but the new String() version creates two String objects: one in heap and the other in string constant pool. Hence using more memory.
But when you write
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
you are not creating a String instead you are creating an object of class CaseInsensitiveString. Hence you need to use the new operator.
If I understood it correctly, your question means why we cannot create an object by directly assigning it a value, lets not restrict it to a Wrapper of String class in java.
To answer that I would just say, purely Object Oriented Programming languages have some constructs and it says, that all the literals when written alone can be directly transformed into an object of the given type.
That precisely means, if the interpreter sees 3 it will be converted into an Integer object because integer is the type defined for such literals.
If the interpreter sees any thing in single quotes like 'a' it will directly create an object of type character, you do not need to specify it as the language defines the default object of type character for it.
Similarly if the interpreter sees something in "" it will be considered as an object of its default type i.e. string. This is some native code working in the background.
Thanks to MIT video lecture course 6.00 where I got the hint for this answer.
In Java the syntax "text" creates an instance of class java.lang.String. The assignment:
String foo = "text";
is a simple assignment, with no copy constructor necessary.
MyString bar = "text";
Is illegal whatever you do because the MyString class isn't either java.lang.String or a superclass of java.lang.String.
First, you can't make a class that extends from String, because String is a final class. And java manage Strings differently from other classes so only with String you can do
String s = "Polish";
But whit your class you have to invoke the constructor. So, that code is fine.
I would just add that Java has Copy constructors...
Well, that's an ordinary constructor with an object of same type as argument.
String is one of the special classes in which you can create them without the new Sring part
it's the same as
int x = y;
or
char c;
String str1 = "foo";
String str2 = "foo";
Both str1 and str2 belongs to tha same String object, "foo", b'coz Java manages Strings in StringPool, so if a new variable refers to the same String, it doesn't create another one rather assign the same alerady present in StringPool.
String str1 = new String("foo");
String str2 = new String("foo");
Here both str1 and str2 belongs to different Objects, b'coz new String() forcefully create a new String Object.
It is a basic law that Strings in java are immutable and case sensitive.
Java creates a String object for each string literal you use in your code. Any time "" is used, it is the same as calling new String().
Strings are complex data that just "act" like primitive data. String literals are actually objects even though we pretend they're primitive literals, like 6, 6.0, 'c', etc. So the String "literal" "text" returns a new String object with value char[] value = {'t','e','x','t}. Therefore, calling
new String("text");
is actually akin to calling
new String(new String(new char[]{'t','e','x','t'}));
Hopefully from here, you can see why your textbook considers this redundant.
For reference, here is the implementation of String: http://www.docjar.com/html/api/java/lang/String.java.html
It's a fun read and might inspire some insight. It's also great for beginners to read and try to understand, as the code demonstrates very professional and convention-compliant code.
Another good reference is the Java tutorial on Strings:
http://docs.oracle.com/javase/tutorial/java/data/strings.html
In most versions of the JDK the two versions will be the same:
String s = new String("silly");
String s = "No longer silly";
Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.
To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.
I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.
UPDATE: I was wrong!
I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!
As we know variables are of different data types, but which data type are their names of?
As it seems they are String, but if they are String then this should be allowed:
int i=6;
String [] arr+i;
...as we can add an int to a String.
So if these are not String then what are they?
And if we want to create variable names dynamically how can we create it?
By dynamically I mean whenever the user clicks on a specific JComponent, a new variable is created, like:
int i=0;
//on first click
String str+i; ///str0
i++;
///on 2nd click
String str+i; ////str1
///i++;
How can I do it?
You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this.
You can use arrays or Map<String, String> etc for this purpose.
Map<String, String> map= new HashMap<>();
int i=0;
while(true) {
// you can use whatever condition you need
details.put("key" + i, "val: "+i);
i++
// some condition to break the loop
}
Java identifiers are not of any type and definitely not String. You can't do this in java, instead, you use a data structure to use these values like ArrayList<String>and store the nth String in the nth index of the data structure like so:
ArrayList<String> strings= new ArrayList<String>(); // Create a new empty List
strings.add(index, string); //add string at index position of the List; can be replaced with strings.add(string) if the strings are being sequentially added
CONSIDER THIS:
public class Test {
public Test() {
}
public static void main(String[] args) {
// GenericType<Integer> intObj;//creates a generic type for integers
//String type
GenericType<String> strObj=new GenericType<String>("My data");
System.out.println("Value is " +strObj.getValue());
}
}
class GenericType<GT>{
GT obT;
GenericType(GT o){
obT=o;
}
GT getValue(){
return obT;
}
void showType(){
System.out.println("Type of GT is " +obT.getClass().getName());
}
}
GT is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to GenericType when an object is created. Thus, GT is used within GenericType whenever the type parameter is needed. Notice that GT is contained within
< >. This syntax can be generalized. Whenever a type parameter is being declared, it is specified within angle brackets. Because Gen uses a type parameter, Gen is a generic class, which is also called a parameterized type.
as mentioned above JAVA provide you with advanced generic classes such as ArrayList, Vectors, Hashmaps to cater for such scenarios .
previous thread similar: How to create new variable in java dynamically
Variable names do not have data types. They are merely references. They are not a String, they are not an int, they are just names. You can't dynamically declare a variable with a name derived from the name of another variable, Java does not work this way.
Java does not work this way. Other languages do but Java isn't one of them. You can't dynamically manipulate the names of variables because they are fixed at compile time. However, in some interpreted scripting languages such a thing is possible.
To be more accurate if they are fixed to be anything at all they are fixed at compile time. If java is not compiled in debug mode the names of the variables cease to be at all. They just become addresses of memory locations.
See this for details: Can I get information about the local variables using Java reflection?
Firstly variables can be categorized into two. primitives (standard ) types such as int, float,double, char,boolean, byte... and non-primitives(user defined)types such as String, Integer, Float, Double. String type fall under non primitive , its a class provided by java.lang Api such that when you create a string variable you are indeed creating an object EX String str; str is an object it can as well be declared as String str=new String();
hence the string class consist of helper methods that may help to achieve your objective, you can as well use concatenation/joining of strings as follows:
class Demo{
String str;
static int i;
JButton but=new JButton("click me!");
.....
public static void actionPeaformed(ActionEvent e){
Object source=e.getSource();
str="msg";
if(source==but){
String newStr;
newStr=str+i;
System.out.println(newStr);
}
}
}
where str may contain some message/text eg from label/elsewhere for every click
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:
String s = new String("silly");
Because it creates unnecessary String objects. But instead it should be written like this:
String s = "No longer silly";
Ok fine so far...However, given this class:
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null) {
throw new NullPointerException();
}
this.s = s;
}
:
:
}
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";
Why is the first statement ok? Shouldn't it be
CaseInsensitiveString cis = "Polish";
How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
String is a special built-in class of the language. It is for the String class only in which you should avoid saying
String s = new String("Polish");
Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
is the correct (and only, in this case) thing to do.
I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.
To illustrate, the following code will print true for the first line, but false for the second:
System.out.println("foo" == "foo");
System.out.println(new String("bar") == new String("bar"));
Strings are treated a bit specially in java, they're immutable so it's safe for them to be handled by reference counting.
If you write
String s = "Polish";
String t = "Polish";
then s and t actually refer to the same object, and s==t will return true, for "==" for objects read "is the same object" (or can, anyway, I"m not sure if this is part of the actual language spec or simply a detail of the compiler implementation-so maybe it's not safe to rely on this) .
If you write
String s = new String("Polish");
String t = new String("Polish");
then s!=t (because you've explicitly created a new string) although s.equals(t) will return true (because string adds this behavior to equals).
The thing you want to write,
CaseInsensitiveString cis = "Polish";
can't work because you're thinking that the quotations are some sort of short-circuit constructor for your object, when in fact this only works for plain old java.lang.Strings.
String s1="foo";
literal will go in pool and s1 will refer.
String s2="foo";
this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal.
String s3=new String("foo");
"foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.
String s4=new String("foo");
same as s3
so System.out.println(s1==s2);// **true** due to literal comparison.
and System.out.println(s3==s4);// **false** due to object
comparison(s3 and s4 is created at different places in heap)
Strings are special in Java - they're immutable, and string constants are automatically turned into String objects.
There's no way for your SomeStringClass cis = "value" example to apply to any other class.
Nor can you extend String, because it's declared as final, meaning no sub-classing is allowed.
Java strings are interesting. It looks like the responses have covered some of the interesting points. Here are my two cents.
strings are immutable (you can never change them)
String x = "x";
x = "Y";
The first line will create a variable x which will contain the string value "x". The JVM will look in its pool of string values and see if "x" exists, if it does, it will point the variable x to it, if it does not exist, it will create it and then do the assignment
The second line will remove the reference to "x" and see if "Y" exists in the pool of string values. If it does exist, it will assign it, if it does not, it will create it first then assignment. As the string values are used or not, the memory space in the pool of string values will be reclaimed.
string comparisons are contingent on what you are comparing
String a1 = new String("A");
String a2 = new String("A");
a1 does not equal a2
a1 and a2 are object references
When string is explicitly declared, new instances are created and their references will not be the same.
I think you're on the wrong path with trying to use the caseinsensitive class. Leave the strings alone. What you really care about is how you display or compare the values. Use another class to format the string or to make comparisons.
i.e.
TextUtility.compare(string 1, string 2)
TextUtility.compareIgnoreCase(string 1, string 2)
TextUtility.camelHump(string 1)
Since you are making up the class, you can make the compares do what you want - compare the text values.
The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by
String s = "Hello";
will only create a string object in the pool and the reference s will refer to it, but by using
String s = new String("Hello");
you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.
You can't. Things in double-quotes in Java are specially recognised by the compiler as Strings, and unfortunately you can't override this (or extend java.lang.String - it's declared final).
- How do i make CaseInsensitiveString behave like String so the above statement is ok (with and w/out extending String)? What is it about String that makes it ok to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java right?
Enough has been said from the first point. "Polish" is an string literal and cannot be assigned to the CaseInsentiviveString class.
Now about the second point
Although you can't create new literals, you can follow the first item of that book for a "similar" approach so the following statements are true:
// Lets test the insensitiveness
CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");
assert cis5 == cis6;
assert cis5.equals(cis6);
Here's the code.
C:\oreyes\samples\java\insensitive>type CaseInsensitiveString.java
import java.util.Map;
import java.util.HashMap;
public final class CaseInsensitiveString {
private static final Map<String,CaseInsensitiveString> innerPool
= new HashMap<String,CaseInsensitiveString>();
private final String s;
// Effective Java Item 1: Consider providing static factory methods instead of constructors
public static CaseInsensitiveString valueOf( String s ) {
if ( s == null ) {
return null;
}
String value = s.toLowerCase();
if ( !CaseInsensitiveString.innerPool.containsKey( value ) ) {
CaseInsensitiveString.innerPool.put( value , new CaseInsensitiveString( value ) );
}
return CaseInsensitiveString.innerPool.get( value );
}
// Class constructor: This creates a new instance each time it is invoked.
public CaseInsensitiveString(String s){
if (s == null) {
throw new NullPointerException();
}
this.s = s.toLowerCase();
}
public boolean equals( Object other ) {
if ( other instanceof CaseInsensitiveString ) {
CaseInsensitiveString otherInstance = ( CaseInsensitiveString ) other;
return this.s.equals( otherInstance.s );
}
return false;
}
public int hashCode(){
return this.s.hashCode();
}
// Test the class using the "assert" keyword
public static void main( String [] args ) {
// Creating two different objects as in new String("Polish") == new String("Polish") is false
CaseInsensitiveString cis1 = new CaseInsensitiveString("Polish");
CaseInsensitiveString cis2 = new CaseInsensitiveString("Polish");
// references cis1 and cis2 points to differents objects.
// so the following is true
assert cis1 != cis2; // Yes they're different
assert cis1.equals(cis2); // Yes they're equals thanks to the equals method
// Now let's try the valueOf idiom
CaseInsensitiveString cis3 = CaseInsensitiveString.valueOf("Polish");
CaseInsensitiveString cis4 = CaseInsensitiveString.valueOf("Polish");
// References cis3 and cis4 points to same object.
// so the following is true
assert cis3 == cis4; // Yes they point to the same object
assert cis3.equals(cis4); // and still equals.
// Lets test the insensitiveness
CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");
assert cis5 == cis6;
assert cis5.equals(cis6);
// Futhermore
CaseInsensitiveString cis7 = CaseInsensitiveString.valueOf("SomethinG");
CaseInsensitiveString cis8 = CaseInsensitiveString.valueOf("someThing");
assert cis8 == cis5 && cis7 == cis6;
assert cis7.equals(cis5) && cis6.equals(cis8);
}
}
C:\oreyes\samples\java\insensitive>javac CaseInsensitiveString.java
C:\oreyes\samples\java\insensitive>java -ea CaseInsensitiveString
C:\oreyes\samples\java\insensitive>
That is, create an internal pool of CaseInsensitiveString objects, and return the corrensponding instance from there.
This way the "==" operator returns true for two objects references representing the same value.
This is useful when similar objects are used very frequently and creating cost is expensive.
The string class documentation states that the class uses an internal pool
The class is not complete, some interesting issues arises when we try to walk the contents of the object at implementing the CharSequence interface, but this code is good enough to show how that item in the Book could be applied.
It is important to notice that by using the internalPool object, the references are not released and thus not garbage collectible, and that may become an issue if a lot of objects are created.
It works for the String class because it is used intensively and the pool is constituted of "interned" object only.
It works well for the Boolean class too, because there are only two possible values.
And finally that's also the reason why valueOf(int) in class Integer is limited to -128 to 127 int values.
In your first example, you are creating a String, "silly" and then passing it as a parameter to another String's copy constructor, which makes a second String which is identical to the first. Since Java Strings are immutable (something that frequently stings people who are used to C strings), this is a needless waste of resources. You should instead use the second example because it skips several needless steps.
However, the String literal is not a CaseInsensitiveString so there you cannot do what you want in your last example. Furthermore, there is no way to overload a casting operator like you can in C++ so there is literally no way to do what you want. You must instead pass it in as a parameter to your class's constructor. Of course, I'd probably just use String.toLowerCase() and be done with it.
Also, your CaseInsensitiveString should implement the CharSequence interface as well as probably the Serializable and Comparable interfaces. Of course, if you implement Comparable, you should override equals() and hashCode() as well.
CaseInsensitiveString is not a String although it contains a String. A String literal e.g "example" can be only assigned to a String.
CaseInsensitiveString and String are different objects. You can't do:
CaseInsensitiveString cis = "Polish";
because "Polish" is a String, not a CaseInsensitiveString. If String extended CaseInsensitiveString String then you'd be OK, but obviously it doesn't.
And don't worry about the construction here, you won't be making unecessary objects. If you look at the code of the constructor, all it's doing is storing a reference to the string you passed in. Nothing extra is being created.
In the String s = new String("foobar") case it's doing something different. You are first creating the literal string "foobar", then creating a copy of it by constructing a new string out of it. There's no need to create that copy.
Just because you have the word String in your class, does not mean you get all the special features of the built-in String class.
when they say to write
String s = "Silly";
instead of
String s = new String("Silly");
they mean it when creating a String object because both of the above statements create a String object but the new String() version creates two String objects: one in heap and the other in string constant pool. Hence using more memory.
But when you write
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
you are not creating a String instead you are creating an object of class CaseInsensitiveString. Hence you need to use the new operator.
If I understood it correctly, your question means why we cannot create an object by directly assigning it a value, lets not restrict it to a Wrapper of String class in java.
To answer that I would just say, purely Object Oriented Programming languages have some constructs and it says, that all the literals when written alone can be directly transformed into an object of the given type.
That precisely means, if the interpreter sees 3 it will be converted into an Integer object because integer is the type defined for such literals.
If the interpreter sees any thing in single quotes like 'a' it will directly create an object of type character, you do not need to specify it as the language defines the default object of type character for it.
Similarly if the interpreter sees something in "" it will be considered as an object of its default type i.e. string. This is some native code working in the background.
Thanks to MIT video lecture course 6.00 where I got the hint for this answer.
In Java the syntax "text" creates an instance of class java.lang.String. The assignment:
String foo = "text";
is a simple assignment, with no copy constructor necessary.
MyString bar = "text";
Is illegal whatever you do because the MyString class isn't either java.lang.String or a superclass of java.lang.String.
First, you can't make a class that extends from String, because String is a final class. And java manage Strings differently from other classes so only with String you can do
String s = "Polish";
But whit your class you have to invoke the constructor. So, that code is fine.
I would just add that Java has Copy constructors...
Well, that's an ordinary constructor with an object of same type as argument.
String is one of the special classes in which you can create them without the new Sring part
it's the same as
int x = y;
or
char c;
String str1 = "foo";
String str2 = "foo";
Both str1 and str2 belongs to tha same String object, "foo", b'coz Java manages Strings in StringPool, so if a new variable refers to the same String, it doesn't create another one rather assign the same alerady present in StringPool.
String str1 = new String("foo");
String str2 = new String("foo");
Here both str1 and str2 belongs to different Objects, b'coz new String() forcefully create a new String Object.
It is a basic law that Strings in java are immutable and case sensitive.
Java creates a String object for each string literal you use in your code. Any time "" is used, it is the same as calling new String().
Strings are complex data that just "act" like primitive data. String literals are actually objects even though we pretend they're primitive literals, like 6, 6.0, 'c', etc. So the String "literal" "text" returns a new String object with value char[] value = {'t','e','x','t}. Therefore, calling
new String("text");
is actually akin to calling
new String(new String(new char[]{'t','e','x','t'}));
Hopefully from here, you can see why your textbook considers this redundant.
For reference, here is the implementation of String: http://www.docjar.com/html/api/java/lang/String.java.html
It's a fun read and might inspire some insight. It's also great for beginners to read and try to understand, as the code demonstrates very professional and convention-compliant code.
Another good reference is the Java tutorial on Strings:
http://docs.oracle.com/javase/tutorial/java/data/strings.html
In most versions of the JDK the two versions will be the same:
String s = new String("silly");
String s = "No longer silly";
Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.
To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.
I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.
UPDATE: I was wrong!
I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!