Recent Forum Posts
From categories:

How many String Objects are created when executing the following code?

11. public String makinStrings( ) {
12. String s = "Fred"; // this line creates one object
13. s = s + "47"; // this line creates two objects
14. s = s.substring( 2, 5); // this line creates one object
15. s = s.toUpperCase( ); // this line creates one object
16. return s.toString() ; 
17. }

Though many ranchers answered already (a seems to be correct answer is 3), the perfect explanation
given by Jim Yingst is here:

Unfortunately this isn't a very good test question, and it's not representative of the questions you'll get on the real exam. The problem is that the compile-time constants "Fred" and "47" have special behavior that's more subtle then you need to know for the exam, and it's ambiguous to say that they were "created" in the code. What happens is, String objects for "Fred" and "47" are created when the class is loaded, not when the method is run. And if the method is run more than once, "Fred" and "47" aren't recreated - they just get re-used. So, if you run the method just once and exit, you get:

"Fred", "47" created when class is loaded.
"Fred47", "ed47", "ED47" created when the method is run.

That's 5 strings total.

If you run the method 5 times, you get

"Fred", "47" created when class is loaded.
"Fred47", "ed47", "ED47" created when the method is run the 1st time
"Fred47", "ed47", "ED47" created when the method is run the 2nd time
"Fred47", "ed47", "ED47" created when the method is run the 3rd time
"Fred47", "ed47", "ED47" created when the method is run the 4th time
"Fred47", "ed47", "ED47" created when the method is run the 5th time

That's 17 strings over 5 method calls.

Additionally, in the event that some other code has used the constants "Fred" or "47" before the method is called, those strings won't be recreated at all. So it's possible that the above code could create just 3 objects when run once, and 15 object when run 5 times.

Based on all this, you can guarantee that at least three String objects are created when the method is run, and at most, five. I would say that three String objects are created in the method, and two may be caused to be created when the class is loaded.

Ultimately I don't think there's any way to determine what the "best" answer is for this question because, the way it's phrased, it's ambiguous. I wouldn't worry too much about it. The real exam won't have a question like this anyway.

how many strings are created? by itsraghzitsraghz, 1201545101|%e %b %Y, %H:%M %Z|agohover

[[toc]]

Reply from Fred Rosenberger, sheriff, author:

the object being created is a Derived.

Reply from Bill Shirley:

during the magic of new, the java runtime calls the constructors of the superclass and the subclass.

You have overriden addValue() in the subclass. All instances of the subclass have this method replaced.

The only (non-reflective) way to get to it is to invoke super.addValue() from the subclass.

class Base{
  int value = 0;
  Base(){
     addValue();
  }
  void addValue(){ //This method overriden by subclass
     value += 10;
  }
  int getValue(){
     return value;
  }
}
class Derived extends Base{
 
  Derived(){
     addValue();
  }
  void addValue(){
    super.addValue();  
    value +=  20;
  }
}
public class Test3 {
  public static void main(String[] args){
     Base b = new Derived(); // b isa Derived
     System.out.println(b.getValue()); // output now 60
  }
}

Reply from Yelamuri Chandu:

You are creating a object of Drevied and assingn it to a variable with ref Base.

When you are creating any Object wiht new Keyword what the JVM will do is first it creates all the varaibles and methods belong to its super and then it own. At any point of time if you call any varible or method first it will try to pick from its own area if not available it goes to super area.

here also the addvalue is available with Derived one, so it executes the devried class method.

In this case if you want to supress and call super class methods then you need to use super keyword which invoke super class method directly.

Re: which one will it invoke? base or derived? by itsraghzitsraghz, 1201201591|%e %b %Y, %H:%M %Z|agohover

Question by Jose Campana:
Analyze this case and please tell me Why the method with the comment //This method is never reached.

class Base{
  int value = 0;
  Base(){
     addValue();
  }
  void addValue(){ //This method
     value += 10;
  }
  int getValue(){
     return value;
  }
}
class Derived extends Base{
 
  Derived(){
     addValue();
  }
  void addValue(){
    value +=  20;
  }
}
public class Test3 {
  public static void main(String[] args){
     Base b = new Derived();
     System.out.println(b.getValue());
  }
}

The preceding code prints out 40. And of course, that means that the method addValue() in class Base() never executes.

When inside Base() constructor, it calls the addValue() method, and it uses the one defined in class Derived. but the Question is:

WHY ?

which one will it invoke? base or derived? by itsraghzitsraghz, 1201200238|%e %b %Y, %H:%M %Z|agohover

Raghs:

I have tested this in a small program:

public class AreConstructorsModifying {
 
    /* This is to show that instance variables are assigned their default values. 
        See it in printA()'s output. That's why 'a' is not initalized. */
    int a; 
    final int finalA;
    {
        System.out.println("Instance Initialization Block 1");
        //finalA = 1;
        printA();
    }
 
    public void printA() {
        System.out.println("printA(), a = "+this.a);
        //finalA = 2;
    }
 
    /** Creates a new instance of AreConstructorsModifying */
    public AreConstructorsModifying() {
        a = 7;
        finalA = 9;
    }
 
    public String toString() {
        return "[AreConstructorsModifying] : a = "+this.a+", finalA = "+finalA;
    }
 
    public static void main(String[] args) {
        AreConstructorsModifying obj = new AreConstructorsModifying();
        System.out.println("obj is : "+obj);
    }    
}

The output is :

Instance Initialization Block 1
printA(), a = 0
obj is : [AreConstructorsModifying] : a = 7, finalA = 9
Re: are constructors really constructing? by itsraghzitsraghz, 1201183076|%e %b %Y, %H:%M %Z|agohover

A Sample program from Ilja Preuss, Sheriff and Author:

public class Foo {
 
  private int foo = 42;
 
  {
    this.print();
  }
 
  public Foo() {
    System.out.println("constructor");
  }
 
  private void print() {
    System.out.println(foo);
  }
 
  public static void main(String[] args) {
    new Foo();
  }
 
}

The following is the output when you run the above program

42
constructor
Re: are constructors really constructing? by itsraghzitsraghz, 1201182899|%e %b %Y, %H:%M %Z|agohover

Reply from Mike Gershman:

In my view, constructors are misnamed - they alter already initialized variables in already created objects, based on the arguments passed to the constructors in the new syntax and on other sources.

Memory allocation for an object is done by the JVM based on information in the class object. The JVM also initializes the instance variables to their default values. Next, the variable initializers and the initialization blocks are executed together in the order they appear in the source code. They can alter the values of the variables. Finally, the constructors get a chance to modify the variables once again. At that point, the object is considered fully initialized and final variables can no longer be altered.

I have not considered the implications of super() here.

BTW, constructors are not methods. Unlike methods, constructors can alter final variables. There are constraints on constructors that don't apply to methods. And you can't call a constructor directly.

are constructors really constructing? by itsraghzitsraghz, 1201182798|%e %b %Y, %H:%M %Z|agohover

[[toc]]

Answer from Sunny Jain:

Let me try to solve the confusion up to some extend :

When Orange extends Fruit, It inherits some properties of Fruit class, when you compile Orange we need to determine which properties you inherits, generally these properties include Instance Variable,methods….and we know that Instance properties will be defined only after call to super constructor..
so subclass instance properties will be defined only after super() {fruit}, superclass instance properties will be defined only after super() {Object}..if we don't invoke super…we wont be able to access superclass properties..so entire concept of inheritance vanishes…!!!

Please correct me if I am wrong..!!!

Answer from Ernest Friedman-Hill, sheriff and Author:

Sunny's not wrong, but I don't think s/he's answered the question.

The way to think about it: an Orange object contains a Fruit object. Every instance of a subclass has a part which is the superclass part.

Picture the base class as a cricket ball. Now if I want to make a subclass, I add to that cricket ball by wrapping it up in tinfoil. To make a sub-subclass, I can add another layer of tinfoil. Etc, etc. There's one superclass object in the middle; subclasses are formed by adding more stuff on the outside.

Reply from Kaydell Leavitt:

If you see an orange in real life. You see an orange, a fruit, and an object, but there is really only one object — the orange.

Re: Object creation in Inheritance by itsraghzitsraghz, 1201180703|%e %b %Y, %H:%M %Z|agohover

Original question by sarathchandra chandala:
I have a subclass named Orange which extends Fruit class.. Now when I make an object of Orange,it will call the constructor of superclass fruit and then up till Object Class..

Does this mean that actually Objects are created for Super classes when i make an object for my subclass??

Object creation in Inheritance by itsraghzitsraghz, 1201180427|%e %b %Y, %H:%M %Z|agohover

Reply from Ernest Friedman-Hill, Sheriff and Author in JavaRanch:
The answer is just one object.

An instance of B includes an A "part". Imagine a piece of paper 1 inch square, call it A. Then think of a B object as a piece of paper 2 inches square, with a 1-inch square drawn onto it labeled "A". The A constructor is called to initialize the A part of the single B object.

Re: how many objects are created (wrt inheritance) by itsraghzitsraghz, 1201096305|%e %b %Y, %H:%M %Z|agohover

[[toc]]

Question1: Inheritance - how many objects created???

class A{
 int a;
}
class B extends A{
 int b;
}
class Try{
 public static void main(String[] args){
   B obj = new B() ;
 }
}

Question from Original Poster Imran Mehrenali:

1) In the above code, when i create an object of Class B, how many objects will get created? Only one object of class B that has 2 members (a and b) or two objects - one of class A that has one member (a), and another of class B that also has only member (b) but can directly acccess the member (a) beloning to object of class A.

2) I was about to ask how many constructors will be called, but have tried this out myself in a java program and have found that 2 constructors (A() and B()) are called while creating an object of class B.
Does this mean that 2 objects are created.

how many objects are created (wrt inheritance) by itsraghzitsraghz, 1201096291|%e %b %Y, %H:%M %Z|agohover

[[toc]]

Question1: Inheritance - how many objects created???

class A{
 int a;
}
class B extends A{
 int b;
}
class Try{
 public static void main(String[] args){
   B obj = new B() ;
 }
}

Question from Original Poster Imran Mehrenali:

1) In the above code, when i create an object of Class B, how many objects will get created? Only one object of class B that has 2 members (a and b) or two objects - one of class A that has one member (a), and another of class B that also has only member (b) but can directly acccess the member (a) beloning to object of class A.

2) I was about to ask how many constructors will be called, but have tried this out myself in a java program and have found that 2 constructors (A() and B()) are called while creating an object of class B.
Does this mean that 2 objects are created.

Reply from Ernest Friedman-Hill, Sheriff and Author in JavaRanch:
The answer is **just one object
.

An instance of B includes an A "part". Imagine a piece of paper 1 inch square, call it A. Then think of a B object as a piece of paper 2 inches square, with a 1-inch square drawn onto it labeled "A". The A constructor is called to initialize the A part of the single B object.

how many objects are created (wrt inheritance) by itsraghzitsraghz, 1201096261|%e %b %Y, %H:%M %Z|agohover

Reply from yogi maheshnath:

Beacause its specified in syntax of wait() method in java.lang.Object.

public final void wait(long timeout)throws InterruptedException
when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:

1. another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread
2. another thread invokes the notifyAll() method for this object
3. another thread interrupts this thread
4. the specified wait() time elapses //see this one

So,After calling wait() method, thread A will become a candidate to get another turn at the CPU,after object B is notified, or after two seconds(wait(2000)) in your example.

Reply from Henry Wong, a bartender of JavaRanch:

B. After the lock on B is released, or after two seconds.

Wrong, but debateable. You can release the lock, and not send the notification, and the thread will not wake up. However, you can argue that two seconds later it will wake up, which technically is still *after* the lock is released.

C. Two seconds after object B is notified.

Clearly wrong. If you sleep for 2 seconds, then send the notification, the thread will wakeup immediately (assuming that it can get the lock).

D. Two seconds after lock B is released.

Clearly wrong. If you sleep for 2 seconds, then release the lock, the thread will wakeup immediately — and not two seconds after. (assuming that it can get the lock).

A. After object B is notified, or after two seconds.

Mostly right. It will wakeup sometime *after* getting the notification. Or it will wakeup sometime *after* 2 seconds. The time to acquire the lock doesn't change that — it will still be after. Of course, you can argue that the *after* implies *immediately after*…

Which one is the correct?

Now, you have 2 answers that are clearly wrong. One that is wrong, but you can argue that it is right, because one part covers the other. And one that is right, but you can argue that it is wrong, because you imply that the word after assumes immediately.

Given this in a test, which one will you pick?

Re: doubt on notification of Threads by itsraghzitsraghz, 1200819114|%e %b %Y, %H:%M %Z|agohover

I thought that when a thread calls wait() over an object, and then someother thread calls notify(), the first one leaved the "waiting" state, and goes to the "locked" state, waiting for the second one to leave the synchronized region, and finally goes to "runnable".

But just when i thought that it was fairly clear, I found a question like this one:

Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
 
A. After object B is notified, or after two seconds.
B. After the lock on B is released, or after two seconds.
C. Two seconds after object B is notified.
D. Two seconds after lock B is released.
 
Which one is the correct?

The books says that A, but I simply don't get it, to me, there are no correct question.

doubt on notification of Threads by itsraghzitsraghz, 1200818934|%e %b %Y, %H:%M %Z|agohover

How many objects are created by the following two statements?

int[] a = new int[10];
int[][] b = new int[10][10];

Answer given by Henry Wong:

int[] a = new int[10];

Just one. The int array object. The 10 ints are not objects.

int[][] b = new int[10][10];

Eleven. One array of int array objects. And 10 int array objects. Again, the ints are not objects.

how many objects are created (wrt arrays) by itsraghzitsraghz, 1200133867|%e %b %Y, %H:%M %Z|agohover

In a java file how many public classes can be present?

The answer is ONLY ONE. But most refined answer is Only one Public Class, since there may be public nested class inside the same .java file which is legally allowed.

source : A Javaranch thread -> http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=023337

how many public classes in a .java file allowed? by itsraghzitsraghz, 1185465495|%e %b %Y, %H:%M %Z|agohover

What is the output of the below program?

public class Increment 
{
   public static int getNum(int x) 
   {
       return x++;
   }
   public static void main(String[] args) 
   {
      System.out.println(getNum(44));
   }
}

The options for the answers are :

(a) 44
(b) 45
(c) 46

Output:

The answer is :

(a) 44

Reason with Explanation by Henry:
When the getNum() method calculates to value to be returned, it will use the value of x before it gets incremented (post increment means the value of x will be incremented after it has been used).

Sure, the value of x will be incremented, but the value to be returned has already been calculated by then.

Reason with Explanation by me:
Its more or less the same of assignment.

When you have

int x = 2;
int y = x++;
System.out.println("x = "+x+", y = "+y);

The above SOP will print the value as:

x = 3, y = 2

Why? and How? The value of x is being used in the operation first (ie., assignment). After the appropriate operation (here assignment) is done, the value of x is incremented! Right?

The same holds good in terms of your method as well. The value of x is being used for its operation (here, return value) first and then its incremented. But that does NOT mean that the updated value of x (incremented here) will be reflected back because the updation happens only after the value of x is being used (returned).

Hope this helps!

what is the output? (wrt to post increment operator) by itsraghzitsraghz, 1184053522|%e %b %Y, %H:%M %Z|agohover

famous question on how many objects are created with respect to Strings (and literals).
Reference from javaranch: http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=039347
(though there were similar threads for the same post, this one is recent)

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);

Answer:

a. 8
b. 6
c. 10
d. 4

Answer is c. 10

Explanation
1 object ("spring") created in line 1
2 objects ("springsummer" and "summer") in line 2
2 objects ("springfall" and "fall") in line 3
1 object ("springsummerspring") in line 4
2 objects ("springwinter" and "winter") in line 5
2 objects ("spring "(with space at end) and "spring springsummer") in line 6

So in total there are ten objects

how many objects (wrt Strings) by itsraghzitsraghz, 1182842362|%e %b %Y, %H:%M %Z|agohover

The answer is 3. (1,4).

Explanation:

Statement 1: There is an object created for the 2D Array which can hold 3 individual 1D int arrays but they themselves are not initialized as such. So, the answer is 1 object for this statement.

Statement 2: Here, there is one object created for 2D Array and since the 2D Array object is fully initialized with both the dimensions, there are 3 objects created which is nothing but the rowsize. Altogether, there are 4 objects created for this.

Re: how many objects are created (wrt arrays) by itsraghzitsraghz, 1182426554|%e %b %Y, %H:%M %Z|agohover

How many objects are created after executing the statements individually.

int[][] 2dArray = new int[3][];
int[][] 2dArray = new int[3][2];

Pick the correct answer from the options given below:

  1. (1,1)
  2. (2,2)
  3. (1,4)
  4. (2,4)
  5. (2,3)
how many objects are created (wrt arrays) by itsraghzitsraghz, 1182421399|%e %b %Y, %H:%M %Z|agohover
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.