Java Associate Flashcards
What is /** comment
JavaDoc
Rules for java code file
At most 1 public class Filename must match the class name (case sensitive) and have java ext
How do you define main class
class Main { public static void main(String[] args) {} } Or String args[] Or String... args
What is the result of compiling java file
.class file with JVM bytecode of the same name as java class file
JDK vs JRE
JDK - includes compiler
JRE - only runtime, compiled code on one machine can be run on any machine with JRE
Java package
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
JAR file
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
Constructor
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
References and priimitives
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)
Identifier names
Beings with letter, $ or _
Subsequent chars can be nums
Cannot use reserved words (they are case-sen)
Where java stores object
Program memory heap - pool of unused memory allocated to java app
Garbage Collection
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
Numeric promotion
- if 2 values have diff data types, java auto promotes one of them to the larger data type
- if one is integral and other is floating, java auto promotes integral to floating
- 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
- Result will have data type of promoted operand
Switch statement
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)
Var initialization when multiple vars in same line caveat
int x = 0, int y = 0 -> wrong, data type can be once!
For-loop
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 + “, “);
}
Break/continue statement in loops
Loops can have labels,
break LABEL; can break out of outer most loop in the inner most :O
+ operator rules
- if both ops are numeric - addition
- if either is string - concatenation
- expression is evaled left->right
Strings in java are…
...immutable String s1 = "1"; String s2 = s1.concat("2"); s2.concat("3"); System.out.println(s2);
String pool
AKA intern pool
Contains literal string values that appear in program code
StringBuilder vs StringBuffer
The other is thread safe
Declaring arrays
type[] x type [] x type x[] type x [] type[] x,y good type x[].y bad
Pretty print array
java.utils.Arrays.toString
Binary search
java.utilsArrays.binarySearch(x, value)
x assumed to be sorted
Autoboxing
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)
Arrays.asList(array) Caveat
Fixed-size, backed version of List - can’t remove or add but can set in place (will update both array and list)
Date api trivia
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 (
Methods Access modifiers
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
Static member and instances
Can use instance to call static member
Reference can even be null!!!
Class c = null;
c.staticMember(); // ok!
Static initialization
static {} block can be used Run when the class is first used
Static import
Imports static methods from given class as if it's global function import static java.util.Arrays.asList;
Passing data among methods in java is…
…pass by value always
Overloading caveats
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
Constructor chaining
this() from body of some ctor
Only as first statement!
Order of initialization
- superclass first
- static var declarations and static initializer in order of appearance
- instance vars declarations and instance initializers
- ctor
Class access modifiers
public, default package-lvl are the only ones for top-lvl classes
Protected & private are only for inner ones
All classes inherit from…
java.lang.Object implicitly (can be explicit) except for java.lang.Object which has no parent
Calling constructor of parent class…
… is done by the call to super(…) which must be first line of the ctor. Will be called implicitly if default parent ctor exists.
Super() vs super
Super() - calls parent class ctor super - access parent member (method or field)
Overriding method checks
- Method in child class must have same signature as in parent
- 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 - 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
Hiding a method extra check
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
Abstract classes
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)
java interfaces
- Class can implement many
- IF can’t be instantiated directly
- IF may not define any methods
- IF can’t be final
- Top lvl IF are assumed to have public or default access
- nondefault methods in interface are assumed to be public abstract methods
Interface conflicts
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 :(
interface variables
- Assumed to be public static final
2. value must be set when it is declared (as it’s final)
Default interface methods
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!
Static interace methods
The only difference is it’s not inherited by classes implementing IF (available only as IF_NAME.STATIC())
What if casting class fails
ClassCastException
Prevent by using “object instanceof Class” operator.
What is an exception
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
When finally won’t run for sure
System.exit is used in try or catch block
Order of catch block execution
Same as they appear in code. If unreachable catch block appears - compiler error.
What happens here?
26: try {
27: throw new RuntimeException();
28: } catch (RuntimeException e) {
29: throw new RuntimeException();
30: } finally {
31: throw new Exception();
32: }
Exception from finally is thrown
Declaring checked exception
Throws
Compiler always requires calling code to handle or declare
Declaring code is not required to actually throw it