Question : Given the code fragment: What is the result?
public static void main(String args[]){ int ii=0; int jj=7; for(ii=0; ii System.out.print(ii + " "); }
1. 2 4 2. 0 2 4 6 3. 0 2 4 4. Compilation Fails
Correct Answer : 3 Explanation: As you can see we need to iterate jj-1 = 6 , Hence till value of ii is less than 6 iterate . While iterating ii value jumps by 2 in each iteration. So it will first print 0 and increment by 2 , hence next it will print 2 and increment by 2 , which make ii value to 4 and print 4.
Question : Given: What is the result? 1. ns = 50 s =125 ns = 125 s = 125 ns = 100 s = 125 2. ns = 50 s =125 ns = 125 s = 125 ns = 0 s = 125 3. ns = 50 s =50 ns = 125 s = 125 ns = 100 s = 100 4. ns = 50 s =50 ns = 125 s = 125 ns = 0 s = 125
Correct Answer : 2 Explanation: Here "s" is a static value. Hence, all instances will point to same variable. Hence, s is assigned with value 125 while second object created (Alpha 125). Now when you call print method it will call 125 for each static reference. However, in case of Alpha (100) object if clause is not passed hence, non-static variable ns will not be initialized and remain 0. Which will print values as below.
ns = 50 s =125 ns = 125 s = 125 ns = 0 s = 125
Question : Given the code from the Greeting.Java file:
public class Greeting { public static void main(String args[]){ System.out.println("Hello " + args[0]); } }
Which set of commands prints Hello Duke in the console?
1. javac Greeting java Greeting Duke 2. javac Greeting.java Duke java Greeting 3. javac Greeting.java java Greeting Duke 4. javac Greeting.java java Greeting.class Duke
Correct Answer : 3 Explanation: Java compiler explicitly need .java extension, hence 1st option is out. Regarding option 2 , we don't need argument during compilation (javac), hence this option is out. Regarding option 3 : javac is compiler with .java extension and during runtime argument is accepted , hence this option is correct.
Question : : Which statement best describes encapsulation? 1. Encapsulation ensures that classes can be designed so that only certain fields and methods of an object are accessible from other objects. 2. Encapsulation ensures that classes can be designed so that their methods are inheritable. 3. Encapsulation ensures that classes can be designed with some fields and methods declared as abstract. 4. Encapsulation ensures that classes can be designed so that if a method has an argument MyType x, any subclass of MyType can be passed to that method.