"Learning gives Creativity,Creativity leads to Thinking, Thinking provides Knowledge, Knowledge makes you Great"
Saturday, 21 September 2013
FREE SJCP PRACTICE EXAMS
Free SCWCD Mock Exams and Practice Exams
- Sun
Certified Web Component Developer Mock Exam by JavaRanch (69 questions) - Attend SCWCD before final exam
- SCWCD 1.5
Mock Exam 100 questions by CertChamp - Sun
Certified Web Component Developer for J2EE - Exam CX-310-080 by ExamCram
(30 questions) - SCWCD 1.5
Mock Exam 120 questions - Sample
questions by topic for SCWCD Certification by javaprepare.com (60 questions) - Web
Component Developer Exam by Eduardo Cobian (60 questions) - SCWCD
Mock Exam by Anand Chawla (59 questions) - SCWCD
Mock Tests by JDiscuss.com (285 questions) - SCWCD
Mock Exams by j2eecertificate.com (90 questions) - SCWCD
Preparation Kit Trial Version by Whizlabs (80 questions) - JWebPlus
V4 Trial Version by Enthuware (20 questions) - SCWCD
Mock Exam on JPilotTest Exam Simulator by S.M.Rahman (59 questions) - ePractice
Sample Questions for SCWCD for the J2EE 1.3 ( questions) - ePractice
Sample Questions for SCWCD for the J2EE 1.4 ( questions) - SCWCD
Mock Exam by Jiris.com (50 questions) - SCWCD 5.0
Mock Exam
Friday, 20 September 2013
Creating a Virus/Robot In Java By Mr .Natraj
A virus is a program that does something unusual.
Unusual can be anything like
- snatching away the mouse control from you
- deleting files from your system,etc
Today we will see how can we create a java Application that blinks your capslock,moves your mouse on the screen automatically and fills your formpage on its own.I would rather call this Program a Java Robot.But this concept can be used in anyarea
Assume that you have an agency that books tickets frequently everyday.Instead of doing it manually,why not,pass all the details in properties files or xml files,and let your java robot do it for you.Doesn’t it sounds good?
I know you are eager to see that application.Even I am more eager to write the same…
RobotDemo.java
After creating the Application,you can convert it to .exe file and then use it in your own way.
Limitation:-
It can work only in computer where java is installed.
Hopefully you liked this Application.Does it deserve a like?
Thank you
Tricky instanceof operator
Let's start with a little puzzle.
Object obj = ...
System.out.println(obj instanceof Object);
How do you initialize the obj in order to print "false"?
Well, aren't all possible Java objects instances of Object? To answer this question one must understand how instanceof operator works. The answer is that it would print "true" for any Object. The only way to make it false is not to give it an object, give it a null reference.
The tricky bit about instanceof operator can be that if object on the left side is null, the condition evaluates to false. Therefore there is no need for null check after a class cast as in the following example.
public boolean equals(Object o) {
if (o instanceof MyClass) {
MyClass mc = (MyClass) o;
if (mc == null) // never null
return false;
else
return ... // compare members of mc
}
return false;
}
This can be simplified as shown in the following code snippet
public boolean equals(Object o) {
if (o instanceof MyClass) {
MyClass mc = (MyClass) o;
return ... // compare members of mc
}
return false;
}
So the moral if this excercise is that instanceof operator works as you would expect with objects, and returns false when given a null.
And remember that equals() method is probably the only reasonable place for instanceof operator. If you do it elsewhere and use it to create an alternative flow (e.g. if-else, switch) it is a bad smell and should be replaced with polymorphism.
BTW the previous example was not a very nice example of how to implement equals method, so do not copy it ;-) Usually we would do something like this
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof MyClass)) return false;
MyClass mc = (MyClass) o;
return ... // compare members of mc
}
Performance of checking computer clock
Very often we check computer clock using either System.currentTimeMillis() orSystem.nanoTime(). Often we call these methods to check how long certain part of our program runs to improve performance. But how much does the call of mentioned methods cost? Or by other words
How long does it take to ask "What time is it now?"
I asked myself this question and wrote the following program.
public static void main(String[] args) {
long tmp = System.nanoTime();
long before = System.nanoTime();
for (int i = 0; i < 1000_000_000; i++) {
// do the call
}
long after = System.nanoTime();
System.out.println((after - before) / 1000_000);
}
How long does it take to ask "What time is it now?"
I asked myself this question and wrote the following program.
public static void main(String[] args) {
long tmp = System.nanoTime();
long before = System.nanoTime();
for (int i = 0; i < 1000_000_000; i++) {
// do the call
}
long after = System.nanoTime();
System.out.println((after - before) / 1000_000);
}
Then I replaced the comment "do the call" with interesting code fragments and measured the time. Here are my results.
Code | Elapsed time, ms |
---|---|
nothing | 5 |
call of foo() {return 0;} | 5 |
f+=f | 320 |
call of foo() {return f+=f;} where f is a class level static variable initiated to System.nanoTime() | 325 |
call of System.nanoTime() | 19569 |
call of System.currenTimeMillis() | 22639 |
This means that:
- method that just returns constant is not executed at all. Call of method that returns 0 takes exactly the same time as doing nothing.
- call of method itself does not take time. Execution of f+=f and call of method that does the same take exactly the same time. We have to say "thanks" to JVM that optimizes code at runtime and uses JIT.
- Call of currentTimeMillis() is about 10% heavier than nanoTime().
- Both methods of taking time are comparable with ~65 arithmetic operations.
Conclusions
- Checking computer clock itself can take time when it is used for measurement of performance of relatively small pieces of code. So, we should be careful doing this.
- Using nanoTime() is preferable when checking time period not only because it gives higher precision and is not sensitive to changing of computer clock but also because it runs faster. Moreover this method returns more correct results because it is using monotonic clock. It guaranties that if you perform 2 consequent calls the second call returns number greater than previous that is not guaranteed when executing currentTimeMillis().
- Do not try to optimize code by manual inlining of your logic. JVM does it for us at runtime. Indeed running arithmetic operation directly or by calling method that contains only this operation take exactly the same time.
Java tricky questions ( Article By AlexR)
Introduction
There are a lot of articles that describe various java tricky questions. But IMHO most of that questions can be easily answered by person that knows java well. However there are more complicated tricks that typically cause even experienced people to fail. This article tries to put such kind of trick together.Tricks classification
The tricks are typically based on- internal caches managed by JDK classes or JVM itself
- compiler optimizations
- hidden and not obvious type transformations including autoboxing
- magic of generics
- tricks of terminology
- using of uncommon, bad and anti-conventional coding and naming that are expected to confuse the person being interviewed.
This classification as well as the following list are not full and cannot be full. However the examples show the general ideas.
Please be aware of the fact that author classify people that use such questions during job interview as criminals. Such questions do not check knowledge of programming language but can confuse even experienced programmer.
String concatenation
What will the following code fragment print?
String str1 = "abc:5";
String str2 = "abc:5";
String str3 = "abc:"+5;
String str4 = "abc:"+(1+4);
String str5 = "abc:"+str1.length();
System.out.println(str1 == str1);
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str1 == str4);
System.out.println(str1 == new String(str1));
Answer
true
true
true
true
false
false
Description
Even beginners know that direct comparison of references is not the same as invocation ofequals() method. So, we can think that every invocation of == will return false. So, why does it return true in 4 first cases? Let's review the results one by one.
- First true is trivial. Reference is equal to itself.
- String is not a regular class. It is built-in java type. String constants are cached, sostr1 and str2 refer to exactly the same object. This is the reason for the second true.
- str3 is defined as "abc:"+5, so it should not be the same as str1: value of the variable is calculated at runtime. In fact java compiler performs all calculations of constant expressions, so expression "abc:"+5 is transformed to "abc:5" at compile time and therefore cached by regular string cache.
- This case is similar to #3. Both mathematical expression and concatenation are done at compile time, so the string is taken from cache.
- The case of str5 is special: java compiler cannot call method, so the string value calculation is done at runtime and the string cannot be cached.
- This case is similar to #5. Constructor cannot be called at compile time, so new object with the same value is created.
Magic integers
What will this code snippet print?
Integer v1_1 = 1;
Integer v1_2 = 1;
Integer v127_1 = 127;
Integer v127_2 = 127;
Integer v128_1 = 128;
Integer v128_2 = 128;
System.out.println(v1_1 == v1_2);
System.out.println(v127_1 == v127_2);
System.out.println(v128_1 == v128_2);
The answer is:
true
true
false
Now the question is "why?!" Indeed, how can value of variable affect the comparison result? How is it possible that 127==127 while 128!=128?
The reason is that line
Integer v127_1 = 127;
is compiled to
Integer v127_1 = Integer.valueOf(127);
Here is how de-compiled byte code looks like:
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
that uses internal cache to retrieve the value. Only if value is not in cache new instance of Integer is created. The cache is initialized to numbers from 0 to 127 inclusive. So, when we try to get value of 127 we get the same instance every time. However attempt to get value greater than 127 creates new object.
int method that returns null
Everyone understands that the following code cannot be compiled:
private int temp() {
return null;
}
The reason is that int type is incompatible with null value.
But the following code is compiled perfectly:
private int temp() {
return (true ? null : 0);
}
This code is compiled because compiler interprets null as a legal value of Integer and then performs autoboxing, i.e. calls intValue() of Integer object that contains null. This causes NullPointerException at runtime.
This question and description are taken from stackoverflow (feel free to up-vote).
int method that does not return anything
If Method declared contains return type the method must return value:
private int temp() {
return 0;
}
The following declaration will cause compilation error:
private int temp() {
}
This method must return a result of type int
Actually each execution path of the method must end with either return or throw statement:
private int temp(int i) {
if (i < 0) {
throw new IllegalArgumentException("negative");
}
if (i < 0) {
throw new IllegalArgumentException("negative");
}
return i;
}
So, is it indeed possible to create int method that neither returns value nor throws exception? The answer is yes:
So, is it indeed possible to create int method that neither returns value nor throws exception? The answer is yes:
private int temp() {
while(true);
}
This method can be successfully compiled and however does not return value and doesn't throw exception. The reason is that this method also never terminates. Compiler knows this and does not complain that return statement is missing.
Now here is a tricky question: write the shortest syntactically correct method so that its return type is int. Every normal person will write something like:
int f() {return 0;}
while the right answer is:
int f() {for(;;);}
because it is shorter by 1 character.
Now here is a tricky question: write the shortest syntactically correct method so that its return type is int. Every normal person will write something like:
int f() {return 0;}
while the right answer is:
int f() {for(;;);}
because it is shorter by 1 character.
Arithmetic operations on values of byte and/or short types
Let's say that we have the following declaration:
byte b = 0;
Are the following 3 operators equal?
b++;
b+=1;
b = b + 1;
All three should increment the variable by 1, right? Yes, it is correct for first 2 lines. The third line cannot be compiled:
ByteIncrement.java:5: possible loss of precision
found : int
required: byte
b = b + 1;
This happens because numeric constants automatically belong to type int that bigger than byte. So, to make this line to work we have to add explicit casting:
b = b + (byte)1;
Now all operations indeed equal and increment the variable b by 1.
This trick is taken from stackoverflow, so feel free to up-vote.
Throwing checked exception without declaration
Everyone knows that there are checked and unchecked exception in java. Unchecked exceptions extend directly or indirectly from RuntimeException and do not have to be declared. Checked exceptions extend directly or indirectly from Exception (but not from RuntimeException) and must be declared. Otherwise attempt to throw them causes compilation error.
So, what do you think about the following code:
import java.sql.SQLException;
public class Test {
// No throws clause here
public static void main(String[] args) {
doThrow(new SQLException());
}
static void doThrow(Exception e) {
Test.<RuntimeException> doThrow0(e);
}
static <E extends Exception> void doThrow0(Exception e) throws E {
throw (E) e;
}
}
Methods main() and doThrow() do not have "throws SQLException" declaration. Method doThrow0() defines expected exception using generic parameter E. Sending RuntimeException as a method generic parameter satisfies compiler and it does not require "throws SQLException" declaration. But in fact SQLException is created and thrown:
$ java Test
Exception in thread "main" java.sql.SQLException
at Test.main(Test.java:7)
Terminology tricks
These tricks are typically used in multi and single-selection tests. Often both question and answers are very long and almost equal, so very small but significant differences must be found. Other type of the questions is based on the fact that people do not remember the exact meaning of terms. Here is an example.
Please select choose the list of words that contains maximal number of java keywords
- abstract, continue, true
- sealed, foreach, unless
- goto, const, strictfp
- class, for, null, false
Here is how typical person is thinking:
#2 may be rejected immediately. #1, #2, #3 contain words we use in java every day but #4 is longer, so the right answer is 4.
And this is wrong. true, false and null are not keywords. They are literals (see here). So, #1 and #4 contain only 2 java keywords. What happens with #3? Everyone knows that goto is not supported by java as well as constant values are defined using keyword final. The third word in the list strictfp looks strange at all. However all these words are legal java keywords:
Subscribe to:
Posts (Atom)