OCPJP (SCJP 1.6)
Search This Blog
Thursday, April 18, 2013
OOPJP(SCJP) Pass by reference or Pass by value?
Wednesday, October 5, 2011
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).
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: }
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”.
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.
Tuesday, March 22, 2011
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”.
Thursday, February 10, 2011
SCJP 6 Question 28:
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
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 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
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 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
Wednesday, February 2, 2011
Question 23
What will happen when you attempt to compile and run the given code? a. It will print - false, true, falsepublic 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:
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
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
Sunday, January 30, 2011
Question 21
What is the result of attempting to compile and run the given code?
Options: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++]);
}
}
}
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 20
What is the result of compiling and running the given code?
Options :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());
}
}
}
a. Prints "AA BB CC"
b. Prints "AABBCC"
c. Does not compile
d. Causes an exception to be thrown
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 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
Saturday, January 29, 2011
Question 17
Which code fragment produces the same output as the following code?
Options :for(int i=0; i< 10; i++)
System.console().printf("%d", i);
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 16
Which of the following classes define the printf() method? Select two choices.
Options :
A. Console
B. PrintWriter
C. Formatter
D. Printer
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.
Friday, January 28, 2011
Question 14
What will be the result of attempting to compile and run the following program?
Options :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();
}
}
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 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 12
What would be the result of an attempt to compile and run the following code?
Options :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();
}
}
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 11
What would be the result of an attempt to compile and run the following code?
Choose one answer.
Options :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);}}
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 10
What will happen when you attempt to compile and run the following code?
Options :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+" ");
}
}
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 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 8
What will happen when you attempt to compile and run the following code? a. It will print - ABC XYZ ABC XYZ in that sequence.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 :
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 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 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?
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 4
What will be the result of an attempt to compile and run the following program? (Choose 1 Answer) Options : a. Result cannot be predicted 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();
}
}
}
}
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown
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 2
What will be the result of an attempt to compile and run the following program? (Choose 1 Answer) } a. Result cannot be predicted 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 :
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown
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 16: Thread t2 = new Thread(new MyClass());//Line 27: Thread t3 = new Thread(new MyClass(),"Thread3");//Line 38: Thread t4 = new Thread("Thread4");//Line 49: Thread t5 = new Thread("Thread5",5);//Line 510: Thread t6 = new Thread ("Thread6", new MyClass());//Line 611: }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
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.
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.
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.
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).
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.
Books for SCJP 1.6 Exam.
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.
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.