Test 4 Flashcards

1
Q

Para compilar un archivo “javac archivo.java”

Para correr un archivo “java archivo”

A

asd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

a default method of an interface cannot be overridden by a static method of another interface, You can, however, redeclare a static method of a super interface as a default method in the sub interface.

A

interface methods can never be declared final.

only final or effective final local variables can be used in a lambda expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The actual classes for Connection, Statement, and ResultSet interfaces are provided by the JDBC driver and are therefore driver dependent.

A

xxc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

BufferedWriter’s append method = works same as the write(String) method. It doesn’t really append the data to the end of the existing content. It overwrites the existing content.

A

The close method flushes the stream and makes sure that all data is actually written to the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

To aggregate features of another class, you either extend that class (i.e. inheritance) or have an object of the other class in your class (i.e. composition).

A

as

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Singleton patterns

A
  1. Make the constructor of the class private so that no one can instantiate it except this class itself.
  2. Add a private static variable of the same class to the class and instantiate it.
  3. Add a public static method (usually named getInstance()), that returns the class member created in step 2.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Assertions sintax: :

A

booleano : cualqier cosa que no sea void

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
  1. Instantis a point on Java time line. This timeline start fromfrom the first second of January 1, 1970 (1970-01-01T00:00:00Z) also called the EPOCH. Note that there is no time zone here. You may think of it as “Java Time Zone” and it matches with GMT or UTC time zone. That means, 1PM in Java time zone will be same as 1 PM in GMT or UTC time zone.
  2. Once created, an Instant cannot be modified. Its methods such as plus and minus return a new Instant object.
  3. Instant works with time (instead of dates), so you can use Duration instance to create new Instants.
  4. LocalDateTime is a time in a given time zone. (But remember that an instance of LocalDateTime itself does not store the zone information!). You can, therefore, use an Instant and a time zone to create a LocalDateTime object.
  5. Whenever you convert an Instant to a LocalDateTime using a time zone, just add or substract the GMT offset of the time zone i.e. if the time zone is GMT+2, add 2 hours and if the time zone is GMT-2, substract two hours. For example, you can yourself this question - if it is 1PM (for example) here in London, which is in GMT, then what would be the time in New York (for example), which is in GMT-4 (or 5, depending on whether the date lies when Day Light Savings time is on or not). The answer would be 1PM - 4 i.e. 9AM.
A

as

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Solo puede haber una clase publica o enum o interfaz o clase abstracta por archivo

An enum cannot be defined inside any method or constructor.

An enum can be defined as a static member of any class. You can also have multiple public enums with in the same class.

A

In order for a program to load a resource bundle, the resource bundle properties file must be in the CLASSPATH.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Classes used to represent dates and times in java.time package are thread safe.

Daylight Saving Time is related to Time zones. It has nothing to do with Duration or Period.

A

All classess in java.time package such as classes for date, time, date and time combined, time zones, instants, duration, and clocks are immutable and thread-safe.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Remember that static fields are never serialized irrespective of whether they are marked transient or not. In fact, making static fields as transient is redundant.

A

asd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Remember the following points about Path.subpath(int beginIndex, int endIndex)

  1. Indexing starts from 0.
  2. Root (i.e. c:) is not considered as the beginning.
  3. name at beginIndex is included but name at endIndex is not.
  4. paths do not start or end with .
A

Remember the following 4 points about Path.getName() method :

  1. Indices for path names start from 0.
  2. Root (i.e. c:) is not included in path names.
  3. \ is NOT a part of a path name.
  4. If you pass a negative index or a value greater than or equal to the number of elements, or this path has zero name elements, java.lang.IllegalArgumentException is thrown. It DOES NOT return null.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

The auto-closeable variables defined in the try-with-resources statement are implicitly final. Thus, they cannot be reassigned.

A

Puedes cerrar los recursos en el body del try pero igual se cerraran nuevamente al finalizar el try si utilizas try with resources

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Console is meant to interact with the user typically through command/shell window and keyboard. Thus, You can read as well as write only character data from/to it.

A

we

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

orElse, orElseGet deben retornar el mismo tipo del Optional

A

Optional’s orElseGet method takes a java.util.function.Supplier function as an argument and invokes that function to get a value if the Optional itself is empty. Just like the orElse method, this method does not throw any exception even if the Supplier returns null. It does, however, throw a NullPointerException if the Optional is empty and the supplier function itself is null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
public class Student {
    private Map marksObtained = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public void setMarksInSubject(String subject, Integer marks){
        // 1 INSERT CODE HERE
        try{
            marksObtained.put(subject, marks);
        }finally{
            // 2 INSERT CODE HERE
        }
    }
    public double getAverageMarks(){
       // valid code that computes average
    }
}

lock.writeLock().lock(); and lock.writeLock().unlock();

A
From a ReadWriteLock, you can get one read lock (by calling lock.readLock() ) and one write lock (by calling lock.writeLock() ). Even if you call these methods multiple times, the same lock is returned. A read lock can be locked by multiple threads simultaneously (by calling lock.readLock().lock() ), if the write lock is free. If the write lock is not free, a read lock cannot be locked. The write lock can be locked (by calling lock.writeLock().lock() ) only by only one thread and only when no thread already has a read lock or the write lock. In other words, if one thread is reading, other threads can read, but no thread can write. If one thread is writing, no other thread can read or write.  Methods that do not modify the collection (i.e. the threads that just "read" a collection) should acquire a read lock and threads that modify a collection should acquire a write lock.  The benefit of this approach is that multiple reader threads can run without blocking if the write lock is free. This increases performance for read only operations. The following is the complete code that you should try to run:  
public class Student {
    private Map marksObtained = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public void setMarksInSubject(String subject, Integer marks){
        lock.writeLock().lock(); //1
        try{
            marksObtained.put(subject, marks);
        }finally{
            lock.writeLock().unlock(); //2
        }
    }
    public double getAverageMarks(){
        lock.readLock().lock(); //3
        double sum = 0.0;
        try{
            for(Integer mark : marksObtained.values()){
                sum = sum + mark;
            }
            return sum/marksObtained.size();
        }finally{
            lock.readLock().unlock();//4
        }
    }
    public static void main(String[] args) {
    final Student s = new Student();
        //create one thread that keeps adding marks
        new Thread(){
            public void run(){
                int x = 0;
                while(true){
                    int m = (int)(Math.random()*100);
                    s.setMarksInSubject("Sub "+x, m);
                    x++;
                }
            }
       }.start();
       //create 5 threads that get average marks
       for(int i=0;i<5; i++){
            new Thread(){
                public void run(){
                    while(true){
                        double av = s.getAverageMarks();
                        System.out.println(av);
                    }
                }
            }.start();
        }
    }

}
Note that if you remove the line //1, //2, //3, and //4, (i.e. if you don’t use any locking), you will see a ConcurrentModificationException.

17
Q

The worker threads in the ForkJoinPool extend java.lang.Thread and are created by a factory.

By default, they are created by the default thread factory but another factory may be passed in the constructor. They do extend Thread.

ForkJoinPool implements Executor and not the threads in the pool.

A

One worker thread may steal work from another worker thread.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks).

18
Q
TreeSet is a NavigableSet and so it supports subSet() method :  
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)  

Returns a view of the portion of this set whose elements range from fromElement to toElement.

The returned subset is backed by the original set. So if you insert or remove an element from the subset, the same will be reflected on the original set.

A

Further, since the subset is created using a range (fromElement to toElement), the element that you are inserting must fall within that range. Otherwise an IllegalArgumentException is thrown with a message “key out of range.”. This is what is happening in this question. The range of subs is 326 to 328 and 329 is out of that range. Therefore, an IllegalArgumentException is thrown at runtime

19
Q

The JavaDoc API description explains exactly how the merge method works. You should go through it as it is important for the exam. public V merge(K key, V value, BiFunction super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping: map.merge(key, msg, String::concat) If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged. Parameters: key - key with which the resulting value is to be associated value - the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key remappingFunction - the function to recompute a value if present Returns: the new value associated with the specified key, or null if no value is associated with the key Throws: UnsupportedOperationException - if the put operation is not supported by this map (optional) ClassCastException - if the class of the specified key or value prevents it from being stored in this map (optional) NullPointerException - if the specified key is null and this map does not support null keys or the value or remappingFunction is null

A

as

20
Q

The java.sql.Savepoint interface of JDBC is tailor made for this purpose. At the end of each step, the process can create a save point. Later on, when the process encounters the special condition, it can roll back the transaction up to any of the previous save point and continue from there, instead of rolling back the whole transaction and losing all the values. For example, connection.setAutoCommit(false); stmt.executeUpdate(“update student set status=1”); //1 Savepoint savePoint1 = connection.setSavepoint(“step1done”); stmt.executeUpdate(“update student set gpa=4.0”); //2 if(special condition){ connection.rollback(savePoint1); } connection.commit(); //query 1 will be committed but query 2 will not be committed.

A

asd

21
Q
  1. writeObject method takes ObjectOutputStream as the only parameter, while readObject method takes ObjectInputStream.
  2. To serialize the object using the default behavior, you must call objectOutputStream.defaultWriteObject(); or objectOutputStream.writeFields();. This will ensure that instance fields of Portfolio object are serialized.
  3. To deserialize the object using the default behavior, you must call objectInputStream.defaultReadObject(); or objectInputStream.readFields();. This will ensure that instance fields of Portfolio object are deserialized.
  4. The order of values to be read explicitly in readObject must be exactly the same as the order they were written in writeObject. Here, ticker was written before coupon and so ticker must be read before coupon.
A

123

22
Q

public static Stream walk(Path start, FileVisitOption… options) throws IOException Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

A

It will not compile because list method does not filter the paths based on a criteria. It is not recursive either

public static Stream list(Path dir) throws IOException Return a lazily populated Stream, the elements of which are the entries in the directory. The listing is not recursive.

s = Files.walk(Paths.get("c:\\temp\\pathtest"), (p, a)->p.endsWith(".txt")&&a.isRegularFile());
It will not compile because you cannot pass a function to test each path while walking through the tree using the walk method.  Files class has the following two walk methods:  public static Stream walk(Path start, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. public static Stream walk(Path start, int maxDepth, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
s = Files.walk(Paths.get("c:\\temp\\pathtest"), "test.txt");
It will not compile because the Files class does not have a walk method that takes a string as the second parameter.  It does have two other walk methods:  public static Stream walk(Path start, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.  public static Stream walk(Path start, int maxDepth, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
23
Q

volatile keyword?

A

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.

24
Q

Remember that Future.get() will block until there is a value to return or there is an exception.

A

as

25
Q

All the write and print methods of PrintWriter return void.

PrintWriter has printf(Locale l, String format, Object… args) and printf(String format, Object… args) methods that allow you to format the input before printing. These methods return the same PrintWriter object so that you can chain multiple calls as shown in this option.

A

sad