Jump to content

Recommended Posts

Posted

I guess I will be asking java some Java questions, trivial ones, these few days...

 

so in order to be consistent, I will post all my trivial Java questions here...

 

 

starting with the first one

 

1) acocrding to this image

threads-states.gif

 

Why doesn't the yield method put the thread into not runnable? clearly, the thread stops for a while and allows other threads to come in and execute.....

Posted

As far as I can see, Runnable doesn't mean "Running", it means exactly what is says, "Runnable", ie able to be executed.

 

I'm guessing you are reading - http://java.sun.com/docs/books/tutorial/essential/threads/lifecycle.html ? If you read further down to a section called "Making a Thread Not Runnable", you will see that Not Runnable simply means that the thread scheduler can't begin executing this thread as it is in a state in which executing it would be a mistake (ie it is sleep()ing for instance or wait()ing on something), not that the thread isn't executing.

 

When you call yield(), the thread you call it on doesn't lose the ability to be executed (ie if you just had that one thread it would just continue running as normal afaik), it is simply moved to a later point in the schedulers queue so that other threads in the Runnable state can be executed. State's that are in the Not Runnable state won't be considered for execution time as they are "Not Runnable" for some reason or other.

Posted

thanks for the explanation for question 1

 

Now, question 2:

 

package geometry;

public class Hypoteneuse{

[b]public[/b] InnerTriangle it = new InnerTriangle();
class InnerTriangle{ public int base;}

}

 

why cant I create an object of a class outside the package geometry that can reference to the variable base?

although the class InnerTriangle is declared as default, but there is an object member of that type already created in the class and declared as public... Why can't an object of ANY class reference to the base variable then?

 

please help

 

thanks

Posted

Question 3:

public class Test{


public static void main(String[] ag) {

for(int x=1; x<ag.length; x++){

System.out.print(ag[x]+" ");

}

}

}

 

As simple as the above code...

first thing, what does it mean by "seperate command line invokations"?

 

well, this is the question:

two seperate line invokations:

 

java Test

 

java Test 1234

 

what is the result?

 

well, I expect the first one to give no result, and the second one to give the result "1234"...

 

but the real answer is no result and "234".....why???

 

I tried compile and run this code and my answer appears correct..

 

So, I think I might read the question wrongly?

 

please help

 

thx

Posted

Question 5:

 

public String s(){

[b]String s = "Fred";
s += "47";
s = s.subString(2,5);
s = toUpperCase();[/b]

return s.toString();
}

 

how many String objects are created when the method s is invoked?

 

my answer is 4, but the correct one is 3...why?

As you see in the bold section of the code block, each line will create a new String, since String is immutable...

 

plz help

 

thx

Posted

Question 6:

 

import java.util.*;

public class Test {

 public static void append(List list) {list.add(new Object()); list.add("bbaa"); list.add("1122"); list.add(1234);}


 public static void main(String[] argv) {

List<StringBuilder> intList = [b]new ArrayList<StringBuilder>()[/b];

append(intList);  


       System.out.println(intList.get(0));
System.out.println(intList.get(1));
System.out.println(intList.get(2));
System.out.println(intList.get(3));




 }
}

 

Why there is no runtime error at append(intList)? I know the parameter accepts it, but the instance actually only allows to add elements of StringBuilder type....

 

please help

 

thx

Posted

Question 7:

 

what does it mean by "mutually exclusive" when this term is applied to object lock in threading?

 

for example, "to obtain a mutually exclusive lock on methods of......"

 

plz help

 

thx

Posted
  Quote
thanks for the explanation for question 1

 

Now' date=' question 2:

 

package geometry;

public class Hypoteneuse{

[b]public[/b] InnerTriangle it = new InnerTriangle();
class InnerTriangle{ public int base;}

}

 

why cant I create an object of a class outside the package geometry that can reference to the variable base?

although the class InnerTriangle is declared as default, but there is an object member of that type already created in the class and declared as public... Why can't an object of ANY class reference to the base variable then?

 

please help

 

thanks[/quote']

 

Inner classes are private by default so...

 

Isn't it because in that classes scope it has no access to the InnerTriangle class and so has no idea of how to deal with an object of type InnerTriangle and so can't access it. For a class/method/whatever to be able to deal with an object it needs to have access to it's class definition to know how to deal with that object. If you change the InnerClass to public, you will see that it works, because the other class then has access to the InnerClass layout/class and so knows how to deal with the object.

 

For instance, when I typecast something of one class/type to another, what I am doing is using a different class/interface to the same underlying data, so to be able to use that interface I need access to it, ie I need access to the class. This doesn't just apply when typecasting, it applies when using the variable normally, as you are still assuming the variable of that particular class and so you need that class to know how to interact with the object data.

Posted
Question 3:

public class Test{


public static void main(String[] ag) {

for(int x=1; x<ag.length; x++){

System.out.print(ag[x]+" ");

}

}

}

 

As simple as the above code...

first thing' date=' what does it mean by "seperate command line invokations"?

 

well, this is the question:

two seperate line invokations:

 

java Test

 

java Test 1234

 

what is the result?

 

well, I expect the first one to give no result, and the second one to give the result "1234"...

 

but the real answer is no result and [b']"234"[/b].....why???

 

I tried compile and run this code and my answer appears correct..

 

So, I think I might read the question wrongly?

 

please help

 

thx

 

On my system, I get no answer, and no answer. If I correct the for loop to start at 0 (given that Java doesn't pass in the name of the script like in some other environments/langauges), I get "1234".

 

I can do

 

java Test "1234 567" 567

 

and change your print to println, I get -

 

1234 567
567

 

because the quotes have shown the shell/command line/jvm that that should be taken as one argument.

 

The way in which arguments are passed to the script might be slightly different based on the shell/os but I'd imagine the JVM tries to ensure some degree of consistency.

 

http://java.sun.com/docs/books/tutorial/essential/attributes/cmdLineArgs.html

Posted
Question 5:

 

public String s(){

[b]String s = "Fred";
s += "47";
s = s.subString(2,5);
s = toUpperCase();[/b]

return s.toString();
}

 

how many String objects are created when the method s is invoked?

 

my answer is 4' date=' but the correct one is 3...why?

As you see in the bold section of the code block, each line will create a new String, since String is immutable...

 

plz help

 

thx[/quote']

 

This is probably because of the fact that -

 

String x = new String("cheese");

and

String x = "cheese";

 

are not exactly the same thing.

 

When using just the string constant "cheese", that object is stored somewhere and when that statement is run, the variable x just references that object that was previously created (possibly before the call of the method? maybe during the creation of the object or even before... something to lookup).

 

An easier example is -

 

public class CommandLine{

       public static String test3() {
               return "cheese";
       }

       public static void main(String[] ag) {
               if(test3() == test3()) {
                       System.out.println("test3 == test3");
               }
               String a = "test";
               String b = "test";
               if (a == b) {
                       System.out.println("a == b :o");
               }
       }
}

 

actually gives -

 

test3 == test3
a == b 

 

which is probably not what you'd expect. The string constant/object "cheese" is probably (although I can't be sure on this, it might be done on the first call of the method although given your question my guess is that it is done beforehand) created before the call to test3() and then on every call to test3() a reference to that same string object/constant is returned (as you can see by the fact it prints out "test3 == test3" (since == is not overloaded on Strings, == just checks to see if 2 variables reference the same object).

 

The "a==b :o" example illustrates that it isn't just in the same line/piece of code that Java will reuse a String constant but possibly across many uses of the same constant to save on memory etc.

 

Therefore if you want to guarantee a new seperate object is being made -

 

String x = new String("something");
String y = new String("something");

 

guarantees (afaik :\) - x != y .

 

So basically the reason is because it reuses an already created object for "Fred" so that line doesn't actually create a new String object, it references an already created one.

 

At least I think that's the reason.

Posted

thanks for the responses, Aeternus...

 

However, I still dont comprehend the 2nd question...

 

for example:

 

package a;

public class fc{

public a aa = new a();

private class a{public int d = 5;}


}

and

import a.fc;


public class Test{

public static void main(String[] sref){


fc c = new fc();

System.out.println(c.aa.d);


}

}

 

In the second code, note that it's in the super directory of directory "a", I can access the varriable d, which is in the private class, without getting any error.....

 

So, again, why does the answer of question 2 is that it's unable to refernce varriable i (which is now d in this case) when the class is outside the package the referenced variable is in?

 

please help

 

thx

Posted
thanks for the responses' date=' Aeternus...

 

However, I still dont comprehend the 2nd question...

 

for example:

 

package a;

public class fc{

public a aa = new a();

private class a{public int d = 5;}


}

and

import a.fc;


public class Test{

public static void main(String[] sref){


fc c = new fc();

System.out.println(c.aa.d);


}

}

 

In the second code, note that it's in the super directory of directory "a", I can access the varriable d, which is in the private class, without getting any error.....

 

So, again, why does the answer of question 2 is that it's unable to refernce varriable i (which is now d in this case) when the class is outside the package the referenced variable is in?

 

please help

 

thx[/quote']

 

Right I have the following -

 

/somedir/
|
|---- /a/
     |
     |------ (fc.java and all it's compiled classes)
|
|---- Booga.java (what would be Test.java)

 

fc.java obviously compiles fine. I try to compile Booga.java and I get -

 

aeternus-computer:~/Documents aeternus$ javac Booga.java
Booga.java:11: d in a.fc.a is defined in an inaccessible class or interface
System.out.println(c.aa.d);
                      ^
1 error

 

Am I misunderstanding what you are asking?

 

With regard to question 7, it is the same meaning of mutually exclusive as in any other use of the term. It simply means that if you have a lock on something, then something else can't gain a lock on it and will have to wait until you give up your lock. Ie no two objects/threads can gain ownership of the monitor of an object at the same time. If this is unclear in a particular example, could you give a little more context, I know you did give some but it is a little short.

 

http://www.google.co.uk/search?q=define%3A+mutually+exclusive

 

With regard to question 4, if you read the documentation - http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html - you'll see that it says that while format is heavily inspired (ie anyone who has used printf will be comfortable with it) by printf, it isn't exactly the same and some things are different (some of these are listed at the link). You would probably be pretty safe just copying over any simple printf statements you might have used in C but if you are looking to do something more complicated with alot of specialised formatting of width and odd types, you would be better off reading the manual and identifying the differences.

Posted
Am I misunderstanding what you are asking?

 

NO you dont....

 

Strange, you said you cant compile Booga.java (which is in my case, the Test.java), but I CAN!!!

 

Let me try again...

Posted

Ok... sorry, forget about my last post.

 

Weird, it did work like the day before yesterday, now I get a compile time error, as you said. :confused:

 

 

Any way,

 

protected class A{

int a;

static int b;

void meth1(){};

static void meth2(){};

}

 

is the above code equivalent to the below one in terms of accessibility?

 

public class A{

protected int a;

protected static int b;

protected void meth1(){};

protected static void meth2(){};

protected A(){};

}

 

btw, why cant you use "private" modifier to a class?

 

plz help

 

thx

Posted

You can use the private modifier for a class, you just can't use it on a class that isn't a member of another class. The reason being, in that context, what would the private modifier actually mean. Normally the private modifier implies that the field or class being defined is only accessible within the confines of encapsulating class. In the case you are describing, there isn't anything encapsulating the class for it to be private in. You could suggest that it might be private within a package but there is a seperate keyword for that.

 

The same is true with protected, as that implies that the class/field using that keyword is only accessible in the encapsulating class or any classes derived from it and within the same package (as the encapsulating class). In the case you are providing, the first example won't compile and will give the error -

 

A.java:1: modifier protected not allowed here
protected class A {
         ^
1 error

 

If you are suggesting that they should both be encapsulated in some class B then it all depends on whether A is in a seperate package to where it is being used. public A with private methods etc will be accessible anywhere it's encapsulating class is which means that is some class derives from B then in that class we can derive a class from A which can access all the fields etc. However, protected classes are only accessible within the same package, so if you do the same with the setup with protected A, it will not work, as you can't derive from A because you aren't in the same package. Therefore the two are not exactly equal although may work out to be in SOME cases.

 

Here is the code I'm referring to -

 

// Directory /t/
package t;
public class B {
   public A x; 
   public B () {
      x = new A(); 
   }

   protected class A {
       int a;

       int b;

       void meth1(){};

       void meth2(){};

       public A () {
           a = 5;
       }
   }
}

 

// Directory /b/
package b;
public class B {
   public A x; 
   public B () {
      x = new A(); 
   }

   public class A {
       protected int a;

       protected int b;

       protected void meth1(){};

       protected void meth2(){};

       protected  A () {
           a = 5;
       }
   }
}

 

I had to remove the static keywords otherwise it wouldn't compile as you can't have static methods in a non-static inner class.

 

// Compiles and prints out "5"
import b.*;
public class D extends B {

   public E testing;

   public static void main (String args[]) {
       D cheese = new D();
       cheese.testing.print();
   }

   public D () {
       testing = new E();
   }

   public class E extends A {    
       public void print() {
           System.out.println(a);
       }
   }

}

 

// Fails to compile and gives the error shown below
import t.*;
public class D extends B {

   public E testing;

   public static void main (String args[]) {
       D cheese = new D();
       cheese.testing.print();
   }

   public D () {
       testing = new E();
   }

   public class E extends A {    
       public void print() {
           System.out.println(a);
       }
   }

}

 

# Error
[/somedir/] javac D.java 
D.java:17: a is not public in t.B.A; cannot be accessed from outside package
           System.out.println(a);
                              ^
1 error

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.