Java Associate Flashcards

1
Q

What is /** comment

A

JavaDoc

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

Rules for java code file

A
At most 1 public class
Filename must match the class name (case sensitive) and have java ext
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you define main class

A
class Main {
  public static void main(String[] args) {}
}
Or String args[]
Or String... args
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the result of compiling java file

A

.class file with JVM bytecode of the same name as java class file

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

JDK vs JRE

A

JDK - includes compiler

JRE - only runtime, compiled code on one machine can be run on any machine with JRE

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

Java package

A
Logical grouping for classes
Import statement tells java which package to look in for the class 
Import statements can collide with one another (java.util.Date, java.sql.Date), if using explicit and wildcard it works (java.util.Date, java.sql.*)
Use fully-qualified name if conflict can't be avoided
Default package - no name, only throwaway code
Precents class name clashes
Packages starting with java/javax come from JDK
Rules for naming dot-segments - same as var names
java.util.* - wildcard import all, doesn't import child packages, imports only classes.
  • > Compiler figures out what actually needs to be imported but is less readable
  • > java.lang is autoimported
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

JAR file

A

zip-like file of java .class files mostly
java pkg.Class to compile
-cp to set class path (where to look for packages&classes)
Class path can include jars

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

Constructor

A
Special method, named the same as class name
No return type
Purpose - initialize fields, but can contain any code
Compiler can supply default one that does nothing
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

References and priimitives

A

Primitives - 8 data types - building blocks for java objects
boolean
byte 8b
short 16b
int 32b
long 64b 123L
float 32b 123.0f
double 64b
char 16b unicode
Numeric types are signed
Literals 0b10 binary, 0xFF hex, 017 octal
Numeric underscores 1_000_000 - readability feature Java7
They hold value where varaible is allocated

Reference types - the value is a pointer to an object somewhere in memory
Can be assigned null - they refer to no object
Can be used to call methods
Should be Uppercased type names
Instance/class vars dont require initialization (unlike local vars)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Identifier names

A

Beings with letter, $ or _
Subsequent chars can be nums
Cannot use reserved words (they are case-sen)

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

Where java stores object

A

Program memory heap - pool of unused memory allocated to java app

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

Garbage Collection

A

Process of auto freeing the heap, deleting objects not reachable by the program
System.gc() not guaranteed to run (java can ignore the method call)
When object is unreachable:
- no references pointing to it
- references gone out of scope

Finalize - objects can implement, called when GC collects the object; it’s called only once (in case it fails the first time, won’t be second one - for example if we assign reference to GCed obj in finalize); called 0 or 1 time

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

Numeric promotion

A
  1. if 2 values have diff data types, java auto promotes one of them to the larger data type
  2. if one is integral and other is floating, java auto promotes integral to floating
  3. Smaller DTs (byet, short, char) are always first promoted to int when used with java binary operators (even if none operand is int) - unary ++ excluded
  4. Result will have data type of promoted operand
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Switch statement

A
Switch(varToTest)
- int
- byte
- short
- char
- String
- enum
Default executed if no case match
Breaks are optional, fall through if no break
case 1
default
case 2
break
1 will go through both cases and default

Values in case statement must be compile-time constant values of the same data type as switch value (final vals are ok)

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

Var initialization when multiple vars in same line caveat

A

int x = 0, int y = 0 -> wrong, data type can be once!

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

For-loop

A

for(datatype element : collection) {}

For objects that inherit java.lang.Iterable, there is a different, but similar, conversion.
For example, assuming values is an instance of List, as we saw in the second
example, the following two loops are equivalent:

for(java.util.Iterator i = values.iterator(); i.hasNext(); ) {
int value = i.next();
System.out.print(value + “, “);
}

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

Break/continue statement in loops

A

Loops can have labels,

break LABEL; can break out of outer most loop in the inner most :O

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

+ operator rules

A
  1. if both ops are numeric - addition
  2. if either is string - concatenation
  3. expression is evaled left->right
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Strings in java are…

A
...immutable
String s1 = "1";
String s2 = s1.concat("2");
s2.concat("3");
System.out.println(s2);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

String pool

A

AKA intern pool

Contains literal string values that appear in program code

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

StringBuilder vs StringBuffer

A

The other is thread safe

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

Declaring arrays

A
type[] x
type [] x
type x[]
type x []
type[] x,y good
type x[].y bad
23
Q

Pretty print array

A

java.utils.Arrays.toString

24
Q

Binary search

A

java.utilsArrays.binarySearch(x, value)

x assumed to be sorted

25
Q

Autoboxing

A

Auto Conversion primitives to value types if Object is needed (like in ArrayLists) or other way around
Autoboxing will cause NPE (if fex we get element of list at index where null is stored)

Caveat:
List numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.remove(1);
System.out.println(numbers);

Usuwany jest index 1, bo java nie zrobi autoboxingu do overloada (bo jest konkretna metoda bioraca inta)

26
Q

Arrays.asList(array) Caveat

A

Fixed-size, backed version of List - can’t remove or add but can set in place (will update both array and list)

27
Q

Date api trivia

A

LocalDate, LocalTime, LocalDateTime, Zoned…
Immutable classes
Moth jest enumem (bo miesiace zaczynaja sie od 1)
Tylko statyczne konstruktory (.of)
Period class (ofMonths fex) - day+
)
Duration - for smaller periods of time (

28
Q

Methods Access modifiers

A
public - can be called from any class
private - can be called onlu from within the same class
protected - can be called from classes in the same package or subclasses
default package-private - can be called from classes in the same package
29
Q

Static member and instances

A

Can use instance to call static member
Reference can even be null!!!
Class c = null;
c.staticMember(); // ok!

30
Q

Static initialization

A
static {} block can be used
Run when the class is first used
31
Q

Static import

A
Imports static methods from given class as if it's global function
import static java.util.Arrays.asList;
32
Q

Passing data among methods in java is…

A

…pass by value always

33
Q

Overloading caveats

A

1.
Can’t have static and instance methods of the same signature
2.
public void x(int[] l) {}
public void x(int… l) {}
Won’t compile - same signature!
3. Autoboxing - uzywana jest najbardziej pasujaca wersja parametru
public void x(int x) {}
public void x(Integer x) {}
x(3); // calls x(int x) overload
4. Calling methods supports promoting smaller to larger primitive type unless there is a specific overload for that primitive type

34
Q

Constructor chaining

A

this() from body of some ctor

Only as first statement!

35
Q

Order of initialization

A
  1. superclass first
  2. static var declarations and static initializer in order of appearance
  3. instance vars declarations and instance initializers
  4. ctor
36
Q

Class access modifiers

A

public, default package-lvl are the only ones for top-lvl classes
Protected & private are only for inner ones

37
Q

All classes inherit from…

A

java.lang.Object implicitly (can be explicit) except for java.lang.Object which has no parent

38
Q

Calling constructor of parent class…

A

… is done by the call to super(…) which must be first line of the ctor. Will be called implicitly if default parent ctor exists.

39
Q

Super() vs super

A
Super() - calls parent class ctor
super - access parent member (method or field)
40
Q

Overriding method checks

A
  1. Method in child class must have same signature as in parent
  2. Method in child must be at least as accessible or more accessible than method in parent
    3, Method in child may not throw checked exception that is new or broader than one declared on parent
  3. If method returns value it must be the same or subclass (covariant return type) of what’s returned in parent’s method

Final method can’t be overriden

41
Q

Hiding a method extra check

A

Method must be defined as static if in parent class method being hidden is also static (and other way around)

Hidden method replace parent methods in calls defined in/for child class

42
Q

Abstract classes

A
Only abstract class can have abstract methods
Abstract class can't have an instance
They can't be private nor final
Abstract class extending other abstract class inherits all abstract methods as it's own
First concrete class extending abstract one must implement inherited abstract methods (which is like overriding regular method)
43
Q

java interfaces

A
  1. Class can implement many
  2. IF can’t be instantiated directly
  3. IF may not define any methods
  4. IF can’t be final
  5. Top lvl IF are assumed to have public or default access
  6. nondefault methods in interface are assumed to be public abstract methods
44
Q

Interface conflicts

A

If 2 different IFs define exactly the same method (name, signature, ret val) they’re considered duplicates and one method is implemented.
If methods differ in return values we have compile error :(

45
Q

interface variables

A
  1. Assumed to be public static final

2. value must be set when it is declared (as it’s final)

46
Q

Default interface methods

A

Default keyword
Abstract method with default implementation
Classes not required to override
Why? backward compatibility - easier to add new method to existing IF with many clients

public default double getTemperature() {
return 10.0;
}

There can’t be 2 identical interface methods with default impl (compile error) unless concrete class overrides!

47
Q

Static interace methods

A

The only difference is it’s not inherited by classes implementing IF (available only as IF_NAME.STATIC())

48
Q

What if casting class fails

A

ClassCastException

Prevent by using “object instanceof Class” operator.

49
Q

What is an exception

A

Java way of saying “I give up, you deal with that shit”

java.lang.RuntimeExceptionjava.lang.Error

checked exception - all Exception subclasses not being RuntimeException
checked = handle or declare

50
Q

When finally won’t run for sure

A

System.exit is used in try or catch block

51
Q

Order of catch block execution

A

Same as they appear in code. If unreachable catch block appears - compiler error.

52
Q

What happens here?

26: try {
27: throw new RuntimeException();
28: } catch (RuntimeException e) {
29: throw new RuntimeException();
30: } finally {
31: throw new Exception();
32: }

A

Exception from finally is thrown

53
Q

Declaring checked exception

A

Throws
Compiler always requires calling code to handle or declare
Declaring code is not required to actually throw it