Pages

Showing posts with label SCJP test. Show all posts
Showing posts with label SCJP test. Show all posts

Thursday, 21 February 2013

SCJP exam. The most common "Compilation fails" questions-2

no default constructor in a superclass

class One{
    String s;
    One(String s){
        this.s = s;
    }
}
class Two extends One{
    Two(String s){
                   // problem 
        this.s = s;
    }
}
interface implementation (method signature)
class Persons{
    String name;
    Persons(String name){
        this.name = name;
    }
    public String toString() {
        return this.name;
    }
}
interface Personable {
    Persons getPerson(String name);
}
class MyPerson implements Personable{
    Persons getPerson(String name) { // problem (must be public)
        return new Persons(name);
    } 
    public static void main(String[] args){
        List ps = new ArrayList();
        MyPerson m = new MyPerson();
        for (int i = 100; i++ < 102; ps.add(m.getPerson("" + i)));
        for(Object o:ps) System.out.println(o);
    }
}

Wednesday, 20 February 2013

SCJP exam. The most common "Compilation fails" questions


Illegal package declaration (looks like import statement).

package com.mypackage.classes.*;  // problem

Out of scope of visibility

class OutOfScopeTest{
    static int x;
    public static void main(String[] args){
        for(int i = 0; i < 10; i++){
            x++;
        }
        System.out.println(x + i); // problem
    }
}

All local variables must be initialized before using.

class LocalVariableTest{
    public static void main(String[] args){
        Boolean b;
        if(b == null){ // problem
            b = false;
        }else{
            b = true;
        }    
    }
}

No enum declaration within any method's scope. 
Enum types must not be local.

class A {
    public static void doStuff(){
        enum Sex {MALE, FEMALE, SHEMALE}; // problem
        Sex sex = Sex.MALE;
    }
}

Friday, 8 February 2013

MasterExam (SCJP 6). Sorting with a Comparator

From first attempt I didn't answer correctly. I leave this question for my memories.
Original code example:

package mastertest.sort;
import java.util.Arrays;
import java.util.Comparator;

public class Sort {

    public static void main(String[] args) {
        String [] words = {"Good","Bad", "Ugly"};
        java.util.Comparator<String> best = new Comparator<String>(){
            public int compare(String s1, String s2){
                return s2.charAt(1) - s1.charAt(1);
            }
        };
        Arrays.sort(words,best);
        System.out.println(words[0]);
    }
}