Search This Blog

Thursday, April 18, 2013

OOPJP(SCJP) Pass by reference or Pass by value?


public class PassByReference {

public PassByReference() {
List<String> list = new ArrayList<String>();
list.add("one");
addToList(list);
System.out.println(list.size());
}
private void addToList(List<String> myList) {
myList.add("two");
myList = null;
}
public static void main(String[] args) {
new PassByReference();
}
}

What is the output?
a. NullPointerException
b. 1
c. 2
d. 0

Answer : c
Primitive types are always passed by value. 
When it comes to object references also it is pass by value as in, the address of the object is copied into the method argument. As long as you manipulate the object reference using its exposed API, changes made will be reflected everywhere. Modifying the reference variable or the variable holding the address will not have any effect on the object.


OOPJP(SCJP) Pass by reference or Pass by value?SocialTwist Tell-a-Friend

Wednesday, October 5, 2011

[TIP] Avoiding null pointer exception while comparing strings

Most of the time in our code we compare a String variable with a constant string. If the variable is null then the .equals method throws a null pointer exception if invoked on that variable. This can be avoided if we use equals in the following way.

**

* Created by IntelliJ IDEA.

* User: aditya

* Date: 10/6/11

* Time: 9:35 AM

* To change this template use File | Settings | File Templates.

*/

public class NullException {

public static void main(String[] args) {

String s = null;

if("arudra".equals(s)){

System.out.println("s is arudra");

}else {

System.out.println("s is not arudra");

}

if(s.equals("arudra")){

System.out.println("s is arudra");

}else {

System.out.println("s is not arudra");

}

}

}

output

s is not arudra

Exception in thread "main" java.lang.NullPointerException

at NullException.main(NullException.java:16)

So the first if condition executes properly without throwing any exception, the reason for that we are invoking equals method on the constant String literal "arudra". However in the second case we are invoking the .equals() method on the null string which results in null pointer excetption.

So whenever we want to compare a String variable with a constant string, it is always better to write constant string. equals (string variable).

SocialTwist Tell-a-Friend

Saturday, August 6, 2011

OCPJP(SCJP1.6) Question 30

   1: import java.io.File;
   2: import java.io.IOException;
   3:  
   4: /**
   5:  * Created by IntelliJ IDEA.
   6:  * User: Owner
   7:  * Date: 8/6/11
   8:  * Time: 12:57 PM 
   9:  */
  10: public class TestCreateNewFile {
  11:     public static void main(String[] args) throws IOException {
  12:         File f = new File("scjp6exam.txt");
  13:         System.out.println(f.exists());
  14:         f.createNewFile();
  15:         System.out.println(f.exists());
  16:     }
  17: }

Options :

A. Prints “ false, false”.

B. Prints “ false, true”

C. Can throw an exception at Line 14.

D. Line 15 may not be executed.

OCPJP(SCJP1.6) Question 30SocialTwist Tell-a-Friend

OCPJP(SCJP 1.6) Question 29

   1: public class StringInstanceOfTest {
   2:     public static void main(String[] args) {
   3:         String s = null;
   4:         if(s instanceof String){
   5:             System.out.println("s is instance of String");
   6:         }
   7:         else{
   8:             System.out.println("s is not an instance of String");
   9:         }
  10:     }
  11: }

Output :


A. Compilation fails.


B. Throws Exception at line 4.


C. Prints “s is instance of String”.


D. Prints “s is not an instance of String”.


OCPJP(SCJP 1.6) Question 29SocialTwist Tell-a-Friend

Friday, July 22, 2011

Try and finally block to unlock the locked object.

A locked object has be unlocked appropriately in order to avoid dead locks. This can be achieved by keeping the locking mechanism in the try block and unlocking mechanism in the finally block. No matter what happens in the try block finally block is always called so locking and unlocking happens appropriately. This is a safe practice to avoid deadlock.

Try and finally block to unlock the locked object.SocialTwist Tell-a-Friend

Tuesday, March 22, 2011

Tutorial : XML parsing in Java (NOT in SCJP)

xml1

Tutorial : XML parsing in Java (NOT in SCJP)SocialTwist Tell-a-Friend

Tutorial : JDBC Handwritten notes. (NOT in SCJP)

Jdbc1

Tutorial : JDBC Handwritten notes. (NOT in SCJP)SocialTwist Tell-a-Friend

Tutorial : Early Binding vs Late Binding (Dynamic Binding)

Connecting a method call to method body is called as binding.

If the binding happens during the compile time then it is called early binding and if the binding happens during the run time then it is called late binding. More detailed explanation is given below

“When binding is performed before the program is run (by the compiler and linker, if there is one), it’s called early binding. You might not have heard the term before because it has never been an option with procedural languages. C compilers have only one kind of method call, and that’s early binding. The other solution is called late binding, which means that the binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or run-time binding”.

Tutorial : Early Binding vs Late Binding (Dynamic Binding)SocialTwist Tell-a-Friend

Thursday, February 10, 2011

SCJP 6 Question 28:

Which of these must be true if you execute the following command?
java –classpath xyz hello.my.App
Choose at least one answer.
a. The definition of the App class must be preceded by the statement 'package hello.my;'
b. The definition of the App class must be preceded by the statement 'package xyz.hello.my;'
c. The definition of the App class must be preceded by the statement 'package my;'
d. App.class must be found in xyz\hello\my directory
e. App.class must be found in xyz\hello directory
f. App.class must be found in xyz directory
SCJP 6 Question 28:SocialTwist Tell-a-Friend

Wednesday, February 9, 2011

SCJP 6 Question 27

What is the result of compiling and running the given code?

public class Regex1 {
  public static void main(String[] args){
    String str = "aaaaaaaaabb";
    String[] split = str.split("a{3}");
    System.out.println(split.length);    
  }
}


Choose one answer
a. Compiler error
b. Exception at runtime
c. Prints 0
d. Prints 1
e. Prints 2
f. Prints 3
g. Prints 4


SCJP 6 Question 27SocialTwist Tell-a-Friend

SCJP 6 Question 26:

What will happen when you attempt to compile and run the following code?

public class WrapTest {
  public static void main(String[] args) {
    String str = "19";
    str.concat(".5");
    Double d = new Double(str);
    Long l = new Long(str);
    System.out.println(d.intValue()+d.doubleValue()+l.doubleValue());
  }
}

Choose one answer.
a. It will print  57.5
b. It will print  57.0
c. It will print  58.0
d. Compilation error
e. Runtime exception


SCJP 6 Question 26:SocialTwist Tell-a-Friend

Tuesday, February 8, 2011

SCJP 6 Question 25:

Which of the following are true about the File class ? Select two choices.

A. You can perform file I/O operations using its methods.

B. You can find the size of a file using its size() method.

C. You can check if a file exists using its exists() method.

D. You can delete a file using its delete() method.

SCJP 6 Question 25:SocialTwist Tell-a-Friend

SCJP 6 Question 24:

Consider the following code statement.

Float f = new Float(3.14);

Choose one answer
a. f.parseFloat("2.718")
b. f.valueOf("3.1421")
c. f.byteValue()
d. f.setValue(Math.PI)
e. None of these


SCJP 6 Question 24:SocialTwist Tell-a-Friend

Wednesday, February 2, 2011

Question 23

What will happen when you attempt to compile and run the given code?

public class StringEquals {
  public static void main(String[] args) {
    Boolean b = new Boolean(true);
    String str = new String(""+b);
    StringBuffer sb = new StringBuffer(str);
    System.out.println(b.equals(str)+","
          +str.equals(sb)+","+sb.equals(b));
  }
}
Options:

a. It will print - false, true, false
b. It will print - true, true, false
c. It will print - false, false, false
d. It will print - true, false, false
e. Compilation error
f. ClassCastException at runtime



Question 23SocialTwist Tell-a-Friend

Monday, January 31, 2011

Question 22

What is the result of compiling and running the given code? (Choose 1 Answer)

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class NumberFormatClass {
  public static void main(String[] args){
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
    try{
      Number number = numberFormat.parse("4,455.67");
      System.out.println(number.intValue());
    }catch(ParseException ex){
      ex.printStackTrace();
    }
  }
}
Options :

a. Compiler error :intValue method not defined in Number
b. Prints "Error"
c. Prints 4,455
d. Prints 4455
e. Prints 4455.67


Question 22SocialTwist Tell-a-Friend

Sunday, January 30, 2011

Question 21

What is the result of attempting to compile and run the given code?

import java.util.*;
public class ScannerDelimiter2 {
  public static void main(String[] args) {
    String input = "10 Apples 20 Oranges 30 Pears";
    Scanner s = new Scanner(input).useDelimiter("\\d");
    String str[] = new String[6];
    int i=0;
    while(s.hasNext()){
      str[i]=s.next();
      System.out.println(str[i++]);
    }
  }
}
Options:


a. Prints "apples", "oranges", "pears" in separate lines.
b. Prints "10", "apples", "20", "oranges", "30", "pears" in separate lines.
c. Exception thrown at runtime.
d. Code does not compile.
e. None of these


Question 21SocialTwist Tell-a-Friend

Question 20

What is the result of compiling and running the given code?

import java.util.Scanner;
public class ScannerDelimiter {
  public static void main(String[] args){
    String input = "AA BB CC";
    Scanner s = new Scanner(input).useDelimiter("\s");
    while(s.hasNext()){
      System.out.print(s.next());
    }
  }
}
Options :


a. Prints "AA BB CC"
b. Prints "AABBCC"
c. Does not compile
d. Causes an exception to be thrown


Question 20SocialTwist Tell-a-Friend

Question 19

What is the result of compiling and running the given code?

public class NullPointerString {
  public static void main(String[] args){
    StringBuffer sb = new StringBuffer("Java");
    String nullString = null;
    sb.append(nullString);
    System.out.println(sb);
  }
}

Options :


A. Compiler error at line “String nullString = null”.
B. NullPointerException thrown at runtime.
C. Prints "Javanull".
d. None of the above.


Question 19SocialTwist Tell-a-Friend

Question 18

Which of the following methods are defined by the Serializable interface?

Options :

A. readObject() and writeObject()

B. readExternal() and writeExternal()

C. serialize() and deserialize()

D. None of the Above

Question 18SocialTwist Tell-a-Friend

Saturday, January 29, 2011

Question 17

Which code fragment produces the same output as the following code?

for(int i=0; i< 10; i++)
  System.console().printf("%d", i);
Options :

A. for(int i=0; i< 10; i++)
  System.console().print("%d", i);
B. for(int i=0; i< 10; i++)
  System.console().println("%d", i);
C. for(int i=0; i< 10; i++)
  System.console().write("%d", i);
D. for(int i=0; i< 10; i++)
  System.console().format("%d", i);

Question 17SocialTwist Tell-a-Friend

Question 16

Which of the following classes define the printf() method? Select two choices.

Options :

A. Console

B. PrintWriter

C. Formatter

D. Printer

Question 16SocialTwist Tell-a-Friend

Question 15

Which of the following are true about the readPassword() method of the Console class? Select two choices.

Options :

A. Its return type is String.

B. It reads the password from the console.

C. It has echoing disabled.

D. It takes a single argument.

E. None of these.

Question 15SocialTwist Tell-a-Friend

Friday, January 28, 2011

Question 14

What will be the result of attempting to compile and run the following program?

public class CustomThread extends Thread{
  public void run(){
    callMethod();
  }
  public synchronized void callMethod(){
    System.out.println(Thread.currentThread().getName());
  }
  public CustomThread(String name){
    super(name);
  }
  public static void main(String[] args){
    CustomThread a = new CustomThread("A");
    CustomThread b = new CustomThread("B");
    b.start();
    b.yield();
    a.run();    
  }
}
Options :


a. Prints "BA"
b. Prints "AB"
c. Prints "Bmain"
d. Prints "mainB"
e. Output can be "Bmain" or "mainB"
f. Output can be "BA" or "AB"
g. Code does not compile


Question 14SocialTwist Tell-a-Friend

Question 13

Before which of the following can the "synchronized" keyword be placed, without causing a compilation error?

Options :

A. Class Methods

B. Instance Methods.

C. Any block of code with in a method.

D. Variables.

E. A Class

Question 13SocialTwist Tell-a-Friend

Question 12

What would be the result of an attempt to compile and run the following code?

class TwoThreadsDemo extends Thread {
  public TwoThreadsDemo(String str){
    super(str);
  }
  public void run(){
    for(int i=0; i<10; i++){
      System.out.println(i+" "+getName());
      try{
        sleep((long)(Math.random()*1000));
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
      System.out.println("Done with Sleep !! "+getName());
    }
  }
}
public class SimpleThread{
  public static void main(String[] args){
    new TwoThreadsDemo("TwoThreadsDemo").start();
    new TwoThreadsDemo("TwoThreadsDemo").start();
  }
}
Options :


A: It will not compile because TwoThreadsDemo is a subclass of thread, but does not have a no-argument public constructor.
B. It will not compile because two separate threads in line A and line B have been given the same name "Java Programmer".
C. It will compile, but at runtime the second thread will overwrite the first thread and so the run method of the TwoThreadsDemo class will be executed only once instead of twice.
D. It will compile but will throw RuntimeException.
E It will compile and run with success and the run method of TwoThreadDemo class will be executed twice by two separate threads created.


Question 12SocialTwist Tell-a-Friend

Question 11

What would be the result of an attempt to compile and run the following code?
Choose one answer.

public class OrderedThread {
  public static void main(String[] args) {
    ThreadHelper first,second,third;
    OrderedThread ot = new OrderedThread();
    first = new ThreadHelper("one",ot);
    second = new ThreadHelper("second",ot);
    third = new ThreadHelper("third",ot);
    second.start();
    first.start();
    third.start();
  }
  public void display(String msg){
    synchronized(msg){
      for(int i=0;i<20;i++){
        System.out.println("Name= "+msg);
      }
    }
  }
}
class ThreadHelper extends Thread{
  String name;
  OrderedThread ot;
  ThreadHelper(String name, OrderedThread ot){
    this.name = name;
    this.ot = ot;
  }
  public void run(){
    ot.display(name);
  }
}
Options :

A .The code compiles fine and prints Two, One, and Three in order and repeats the same for another 19times.
B. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially. However, the order whether Two will come first, then One, and at last Three is not guaranteed.
C. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially at the behavior is guaranteed.
D. The code compiles fine and prints Two, One, and Three 20 times each in an indefinite order.
E. The code compiles fine but throws InterruptedException due to synchronization of msg String in a  wrong way.


Question 11SocialTwist Tell-a-Friend

Question 10

What will happen when you attempt to compile and run the following code?

public class TestThread extends Thread{  
  public static void main(String[] args) {
    new TestThread().start();
    new TestThread().start();
  }
  public void run(){
    SafeClass st = new SafeClass("abc");
    SafeClass st1 = new SafeClass("xyz");
  }
}
class SafeClass {
  private String str;
  public  SafeClass(String s){
    str = s;
    str.toUpperCase();
    System.out.println(str+" ");
    
  }
}
Options :


a. It will print - ABC XYZ ABC XYZ in that sequence.
b. It will print - ABC ABC XYZ XYZ in that sequence
c. It will print - ABC and XYZ twice, but the sequence cannot be determined.
d. It will print - abc and xyz twice, but the sequence cannot be determined.
e. The code will not compile.


Question 10SocialTwist Tell-a-Friend

Question 9

Which of the following statements are true about the sleep method of Thread class? Select two choices.

Options :

A . A thread releases any locks it is holding when it is invoked on the thread.

B. It is defined as static within the Thread class.

C. A Thread starts running as soon as it wakes up from the sleeping state.

D. The sleep method throws InterruptedException.

Question 9SocialTwist Tell-a-Friend

Question 8

What will happen when you attempt to compile and run the following code?

public class TestThread extends Thread{  
  public static void main(String[] args) {
    new TestThread().start();
    new TestThread().start();
  }
  public void run(){
    SafeClass st = new SafeClass("abc");
    SafeClass st1 = new SafeClass("xyz");
  }
}
class SafeClass {
  private String str;
  public synchronized SafeClass(String s){
    str = s;
    str = str.toUpperCase();
    System.out.println(str+" ");    
  }
}
Options :

a. It will print - ABC XYZ ABC XYZ in that sequence.
b. It will print - ABC ABC XYZ XYZ in that sequence
c. It will print - ABC and XYZ twice, but the sequence cannot be determined.
d. It will print - abc and xyz twice, but the sequence cannot be determined.
e. The code will not compile.


Question 8SocialTwist Tell-a-Friend

Question 7

Which of the following statements are true about synchronization?  (Select two choices)

Options :

A. Static methods cannot be synchronized.

B. Synchronized methods methods cannot make calls to non-synchronized methods

C. A synchronized method can be overridden by a non-synchronized and vice-versa

D. When a Thread is executing a synchronized method of a an object, other threads can freely access non-synchronized methods of the same object.

Question 7SocialTwist Tell-a-Friend

Question 6

Given that a static method doIt() in the Work class represents work to be done, which of the following blocks of code will succeed in starting a new thread that will do the work?

Picture

Question 6SocialTwist Tell-a-Friend

Question 5

There are three Threads trying to invoke a method of an object. This method is a synchronized method to prevent conflict between Threads. While Thread1 is executing the method, Thread2 and Thread3, in that order attempt to invoke the method.
What happens when Thread1 exits the method?

Options : (Choose one answer)

a. Thread2 will be the first waiting Thread to execute the method.

b. Thread3 will be the first waiting Thread to execute the method.

c. The order In which the Ttread2 and Thread3 will invoke the method cannot be determined.

d. None of these.

Question 5SocialTwist Tell-a-Friend

Question 4

What will be the result of an attempt to compile and run the following program? (Choose 1 Answer)

public class ThreadPrediction {
    public ThreadPrediction() {
    }
    public static void main(String[] args){
      ThreadHelper th = new ThreadHelper();
      new Thread(th,"A").start();
      new Thread(th,"B").start();
    }
}
class ThreadHelper implements Runnable{  
  String str = new String("Running");
  public void run(){    
    synchronized(str){
      try{
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName());
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
    }
  }
}

Options :

a. Result cannot be predicted
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown


Question 4SocialTwist Tell-a-Friend

Question 3

What will be the result of an attempt to compile and run the following program? (Choose 1 Answer)

public class ThreadPrediction {
    public ThreadPrediction() {
    }
    public static void main(String[] args){
      ThreadHelper th = new ThreadHelper();
      new Thread(th,"A").start();
      new Thread(th,"B").start();
    }
}
class ThreadHelper implements Runnable{  
  public void run(){
    String str = new String("Running");
    synchronized(str){
      try{
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName());
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
    }
  }

}
Options :

a. Result cannot be predicted
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown


Question 3SocialTwist Tell-a-Friend

Question 2

What will be the result of an attempt to compile and run the following program? (Choose 1 Answer)

public class ThreadPrediction {
    public ThreadPrediction() {
    }
    public static void main(String[] args){
    	new Thread(new ThreadHelper(),"A").start();
    	new Thread(new ThreadHelper(),"B").start();
    }
}
class ThreadHelper implements Runnable{
	public void run(){
	String str = new String("Running");
	synchronized(str){
	try{
	System.out.println(Thread.currentThread().getName());
	Thread.sleep(5000);
	System.out.println(Thread.currentThread().getName());
	}catch(InterruptedException ie){
	ie.printStackTrace();
        }
	}
	}

}
Options :

a. Result cannot be predicted
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown


Question 2SocialTwist Tell-a-Friend

Question 1

Which of the following lines will not compile ?? Choose Two.

  1: public class Question1 {
  2:     public Question1() {
  3:     }
  4:     public static void main(){
  5:     	Thread t1 = new Thread(); // Line 1
  6:     	Thread t2 = new Thread(new MyClass());//Line 2
  7:     	Thread t3 = new Thread(new MyClass(),"Thread3");//Line 3
  8:     	Thread t4 = new Thread("Thread4");//Line 4
  9:     	Thread t5 = new Thread("Thread5",5);//Line 5
 10:     	Thread t6 = new Thread ("Thread6", new MyClass());//Line 6
 11:     }
 12: }
 13: class MyClass implements Runnable{
 14: 	public void run(){}
 15: }

Options :
a. Line 1
b. Line 2
c. Line 3
d. Line 4
e. Line 5
f. Line 6


Question 1SocialTwist Tell-a-Friend

Sunday, January 23, 2011

Setting PATH and Classpath in Windows.

After installing JDK (download JDK here) we have to set path and classpath variables.

Path variable holds a the path to the executable file javac.exe. Generally this file is located at C:\Program Files\Java\jdk1.6.x\bin. So in order to execute this command we must go to C:\Program Files\Java\jdk1.6.x\bin and execute javac x.java. This is a painful task, so in order to avoid that we must set path variable in the environmental variables.

Setting PATH and Classpath in Windows.SocialTwist Tell-a-Friend

Monday, October 18, 2010

Compiling code in Eclipse.

This tutorial is a continuation to my earlier tutorial about configuration of Eclipse. In this one I show you how to compile and execute code using eclipse.

Compiling code in Eclipse.SocialTwist Tell-a-Friend

Wednesday, October 13, 2010

Eclipse Configuration

Eclipse IDE is widely used in working environments. Most professional prefer to use Eclipse as it is considered to be industry standard IDE. This tutorial will help you in installing and configuring Eclipse along with writing and compiling the code.

Eclipse ConfigurationSocialTwist Tell-a-Friend

Tuesday, October 12, 2010

Difference between SCJP 1.5 and 1.6

Q :What is the difference between SCJP 1.5 vs SCJP 1.6?

Ans :  SCJP 1.6 = SCJP 1.5 +  New API Contents (NavigableSet, NavigableMap, Garbage Collection, Console). The names may scare you but they are very easy. The Pass score has been increased from 58% to 65%. But you don’t care about this. If you follows simple steps you can easily score >80%. (I can assure you).

Difference between SCJP 1.5 and 1.6SocialTwist Tell-a-Friend

Mock Exams List

This is a raw list, I collected it from various websites including javaraunch.com. I am yet to refine it. It contains lot of material which is irrelevant to SCJP 1.6. I will sort that work for you. For time being use the link as is.

Mock Exams ListSocialTwist Tell-a-Friend

Books for SCJP 1.6 Exam.

So many people had sent me mails regarding the books to be followed for SCJP 1.6. My sincere suggestion to them was to follow “ SCJP Sun Certified Programmer for Java 6 Exam 310-065 “ written by Katherine Sierra and Bert Bates.
Books for SCJP 1.6 Exam.SocialTwist Tell-a-Friend

Running your first program in JCreator.

After you setup JCreator the next task is to write a small code to verify the setup. This section will help you on writing java , compiling and running Java code for the first time in IDE. Double click on the JCreator icon on your desktop and select new file.

Running your first program in JCreator.SocialTwist Tell-a-Friend

Practice … Practice … Practice

Which ever blog you go, whatever material you read every one will suggest you to write small programs while reading for SCJP. Forget about the exam version whether it is SCJP 5 or SCJP 6, you have to practice a lot in order to achieve good score in the exam.

But which editor do you want to use for practice. There are lots of editors notepad, notepad++, Textpad, etc etc. Which one do you use for practicing ? From my experience I find the following two editors (IDE) are best for practicing. {This is strictly my personal opinion and people can comment on this}

1. JCreator

2. Eclipse

In this post I will help you setting up JCreator for the first use with the help of example.

 

Practice … Practice … PracticeSocialTwist Tell-a-Friend