Вы находитесь на странице: 1из 13

2017

JAVA TEST ENGLISH

JAIME R. C.
1 Regular expressions
Define a regular expression that matches the phrases “damage”, “minor damages” and
“heavy damage” but not the phrase “no damages”.
Write a method with a string as argument. The output has to be the result whether the
string matches or not.
package _1_regular_expressions;

import java.util.regex.Pattern;

public class RegularExpressions {

public static String regExpMatches( String patternToMatch ) {

String matchResult = "The string \"" + patternToMatch + "\" DOES


NOT matches.";

if ( Pattern.matches("damage|minor damages|heavy damage",


patternToMatch ) ) {
matchResult = "The string \"" + patternToMatch + "\"
MATCHES";
}

return matchResult;
}

public static void main( String[ ] args ) {

System.out.println( regExpMatches( "damage" ) );


System.out.println( regExpMatches( "minor damages" ) );
System.out.println( regExpMatches( "heavy damage" ) );
System.out.println( regExpMatches( "no damages" ) );
System.out.println( regExpMatches( "default string" ) );

}
}
2 Objects
Define a class Student with the reference variables studentId and name, a
constructor and default methods. It is given:
ID Name
0054 Albert Einstein
1234 Gottfried Wilhelm Leibniz
5421 Carl Friedrich Gauss
Write code for a console output (Name and ID) that is sorted by the student names.
package _2_objects;

import java.util.Comparator;

public class Student {


private int studentId;
private String name;

public Student(int studentId, String name) {


super();
this.studentId = studentId;
this.name = name;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

@Override
public String toString() {
return "Student [studentId=" + studentId + ", name=" + name +
"]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 :
name.hashCode());
result = prime * result + studentId;
return result;
}

public static Comparator<Student> stComparator = new


Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {

String studentName1 = o1.getName();


String studentName2 = o2.getName();
return studentName1.compareTo(studentName2);
}
};

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (studentId != other.studentId)
return false;
return true;
}

}
package _2_objects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ObjectsMain {

public static void main(String[] args) {


Student s1 = new Student(54, "Albert Einstein");
Student s2 = new Student(1234, "Gottfried Wilhelm Leibniz");
Student s3 = new Student(5421, "Carl Friedrich Gauss");

Student students[] = { s1, s2, s3 };

List<Student> studentList = new ArrayList<Student>();

for (Student student : students) {


studentList.add(student);
}

// BEFORE SORTING
for (Student student : studentList) {
System.out.println(student.toString());
}
System.out.println("------------------");

// SORTING BY COMPARATOR
Arrays.sort(students, Student.stComparator);

for (Student student : students) {


System.out.println(student.toString());
}
System.out.println("------------------");

// SORTING BY LAMBDA OPERATOR


studentList.sort((st1, st2) ->
st1.getName().compareTo(st2.getName()));

for (Student student : studentList) {


System.out.println(student.toString());
}
System.out.println("------------------");
}

}
3 Design pattern
What is a singleton pattern and when do you use it? Please use an example.
A: Is an object that can be instanced only once by setting its constructor as private and
providing a public method to manage the instance…
They are especially useful for factory classes, but lately they are considered as an anti-
pattern, not to be used.
When I was learning Java, I used Singleton to simulate Data Bases.
package _3_design_pattern;

public class Singleton {

private static Singleton INSTANCE = null;

// Private constructor suppresses


private Singleton(){}

// synchronized contructor to avoid multithreading issues


private static void createInstance() {
if (INSTANCE == null) {
synchronized(Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
}

public static Singleton getInstance() {


if (INSTANCE == null) createInstance();
return INSTANCE;
}
//we override the clone() method to avoid cloning the object
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
4 Inheritance
Look at the following class:
public class Product {
String name;
String description;
double price;
public Product ( String name, String desc, double price ) {
this.name = name;
this.description = desc;
this.price = price;
}
public final double getPriceWithTax() {
return price * 1.19;
}
public String toString() {
return name + " _ " + description + " _ " + price + " EUR";
}
}
Write a subclass Clothing that extends the class Product. The subclass must have
additional attributes for the size (as int) and the material (as String). The new attributes
shall be initialized in the constructor like the other attributes name, description and
price, as well as implemented in the method toString()to override the output
stream.
package _4_Inheritance;

public class Clothing extends Product {

private int size;


private String material;

public Clothing(String name, String desc, double price, int size, String material) {
super(name, desc, price);
this.size = size;
this.material = material;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() + " _ " + size + " _ " + material + ".";
}

}
5 Threads
Imagine a simple robot that can randomly move forward and backward as well as left
and right.
The task is to show the movement of the robot in the form of a console output (e.g.,
System.out.println(“left...”), System.out.println(“right...”), ...).
Define two classes HorizontalThread and VerticalThread as threads. The class
HorizontalThread process the robots movement left and right, the class
VerticalThread process the robots movement forward and backward. The
movements have to be displayed in the console. Now, implement a class Robot that
starts both threads.

package _5_threads;

import java.util.Random;

public class HorizontalThread extends Thread {


private Thread t;

@Override
public void run() {
System.out.println("Horizontally moving");
try {
if (new Random().nextBoolean()) {
System.out.println("left...");
} else {
System.out.println("right...");
}
Thread.sleep(300);
} catch (InterruptedException e) {
System.err.println("Horizontal move interrupted");
} finally {
System.out.println("Horizontal move ended.");
}
}

@Override
public synchronized void start() {

System.out.println("Starting Horizontal Move");


if (t == null) {
t = new Thread(this);
t.start();
}

}
}
package _5_threads;

import java.util.Random;

public class VerticalThread extends Thread {


private Thread t;

@Override
public void run() {
System.out.println("Vertically moving");
try {
if (new Random().nextBoolean()) {
System.out.println("forward...");
} else {
System.out.println("backward...");
}
Thread.sleep(300);
} catch (InterruptedException e) {
System.err.println("Vertical move interrupted");
} finally {
System.out.println("Vertical move ended.");
}
}

@Override
public synchronized void start() {

System.out.println("Starting Vertical Move");


if (t == null) {
t = new Thread(this);
t.start();
}

public static void main(String[] args) {


VerticalThread vt1 = new VerticalThread();
vt1.start();
}
}
package _5_threads;

public class Robot implements Runnable {

private VerticalThread robotVertical = new VerticalThread();


private HorizontalThread robotHorizontal = new HorizontalThread();

@Override
public void run() {

robotHorizontal.start();
robotVertical.start();

public static void main(String[] args) {


Robot r = new Robot();
r.run();
}

}
6 Correct the code
1: public class carThread implements Thread {
2: final String brand;
3: final String model;
4: final double price;
5:
6: public carThread ( String brand, String model) {
7: this.brand = brand;
8: this.model = model;
9: }
10:
11: public void run() {
12: while(true) {
13: System.out.println(“hello my name is this.brand”);
14: Thread.sleep(300);
15: }
16: }
17:
18: public static void main(String[] args) {
19: new carThread(“Audi”).run();
20: new carThread(“BMW”).run();
21: System.out.println(“carThreads are running... “);
22: }
23:
What's wrong with this class? Correct all errors.

First, I would never write code on default package, second, java classes by convention
are named by CamelCase. Then the code could be this:

package _6_correct_the_code;

public class CarThread extends Thread {

//Final variables can be changed, so I make them private


private String brand = "";
private String model = "";
private double price = 0;

public CarThread(String brand, String model) {


this.brand = brand;
this.model = model;
}

//Getters and setters to manage properties


public String getBrand() {
return brand;
}

public void setBrand(String brand) {


this.brand = brand;
}

public String getModel() {


return model;
}
public void setModel(String model) {
this.model = model;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public void run() {


//I used a flag to avoid an infinite loop
boolean flag = true;
while (flag) {
System.out.println("hello my name is " + this.brand + ".");

//You need to sourround the sleep() methond by a try/catch for


exceptions
try {
Thread.sleep(300);
} catch (InterruptedException e) {

e.printStackTrace();
} finally {

flag = false;
}
}
}

public static void main(String[] args) {


//the constructor needs two parameters
new CarThread("Audi", "A6").run();
new CarThread("BMW", "").run();
System.out.println("carThreads are running... ");
}
}
7 Bonus
Write a method with only one boolean parameter. Depending on the parameter the
method has to return “a”, “b”, or “c”.

Could be like this:

package _7_bonus;

import java.util.Random;

public class Bonus {

public static char trinary(boolean b) {


if (b) {
return 'a';
} else if (new Random().nextBoolean()) {
return 'b';
} else {
return 'c';
}
}

public static void main(String[] args) {

System.out.println(Bonus.trinary(true));
System.out.println(Bonus.trinary(false));

Вам также может понравиться