Skip to content

Instantly share code, notes, and snippets.

@kashifrazzaqui
Created May 6, 2016 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kashifrazzaqui/7407e308c233f2e91d9470c13507b091 to your computer and use it in GitHub Desktop.
Save kashifrazzaqui/7407e308c233f2e91d9470c13507b091 to your computer and use it in GitHub Desktop.
Java basics you MUST know
super basic java
- braces
- define scope
- no masking/shadowing but new variables are welcome
"public void kewl()
{
int x = 7;
{
int x = 8; //Illegal masking
int y = 9
}
//y is not available in this scope
}
"
- by design to reduce bugs
- also used as initializers
"public class Example
{
static {
}
}"
- are executed before every constructor
- instance initializers
- use case
- designed for handling code that is redundant between constructors instead of making a third new constructor
- static initializers
- use case
- only way to initialize a final static variable, can't do this in a constructor
- tip
- take any method and try to break it into as many scopes as possible
- if you succeed - refactor the method into many smaller methods
- variables
- pass by reference or value
- by reference means passing a pointer to the same value
- by value means making a copy of it and passing the value not the same instance
- what java experts will tell you
- Java passes objects by reference - This means it passes references to objects.
- Java passes references by value - This means that when you pass a reference to an object (usually called a variable) you are not passing the object but a pointer to that object. You may then reset this specific reference to point to another object and this will not effect the original object because you are modifying the reference to the object and not the object itself.
- the truth
- pass by value
- remember: make a copy and send it
- objects are not objects but memory addresses/integers - pointers
- primitives are copied and sent
- source
- the java spec
- exercise
- try writing a swap() for both objects and primitives
- Employee e = new Employee()
- References/Pointers are distinct from objects
- == is used only to compare references in objects
- but then why does it work for strings
- Pointers are based on bus size (32/64 bit)
- stack and heap
- why is a stack faster than heap? (both in RAM?)
- because
- stack has variable values available locally, no need to lookup a reference
- stackframe sizes are fixed so CPU can move thru the stack fast and read specific locations
- what is the alternative to stack/heap design
- register based design
- android dalvik
- hardware
- its harder/much harder (NP hard)
- efficient variable allocation to a register is a graph coloring problem
- stack
- local primitive variables
- primitive instance variables
- object reference not the actual objects in any method
- method arguments
- main() is the first stack frame
- successive calls add their own frame
- thats is why we require copying (pass by value) as we go from one stack to another - otherwise we will reinvent references
- sum of all frames is process stack
- heap
- objects
- Object o = new SomeObject()
- arrays
- static references
- no scope, so no stack
- objects referred to statically
- postfix operator
"int j = 0;
for (int i = 0; i < 100; i++)
j = j++; //fuck up - assigned then incremented but not reassigned; loops;
System.out.println(j);"
- static keyword
- when class is created, only once in a standard JVM
- easy to leak memory
- static List<Employee> employees = new ArrayList<Employee>();
- these employees reference other things too! the problem is bigger than you imagine.
- strings
- how are strings represented?
- are not null terminated
- array length is known and array is immutable in size
- Interning
- String.intern() //more dangerous with large strings like files
- beware memory leaks
- automatic interning of every single string literal - "test"
- String constructor based strings are not interned
- String.substring (till JDK 6)
- can leak memory because it uses the original 'full' string's char array
- String.split removes trailing empty results but not leading ones!
- "a,b,c,d,,,".split(",").length = 4
- ",,,a,b,c,d".split(",").length = 7
- printing
- char arrays
"char[] a = {'a', 'b', 'c'};
System.out.println(a);
System.out.println("apple " + a);
>> abc
>> apple [C@7369ca65
"
- why?
- System.out.println has an overriden method for char[]
- solution
- String.valueOf(a)
- Or two separate calls to print
- characters
- 'a' + 'b' //single quotes cause trouble and char is int so it adds not concatenates
- solution is to force string concat to occur
- "" + 'a' + 'b'
- arithmetic issues
- 2.0 - 1.1 gives 0.8999999
- use BigDecimal(string) to fix
- enums
- are classes and can have methods
- can iterate by using Enum.values()
- awesome feature - constant specific 'class bodies'
"enum Egg {
large,
extraLarge { public double recipeEquivalent(){ return 2.0; }},
jumbo { public double recipeEquivalent(){ return 3.0; }};
public double recipeEquivalent() { return 1.0; }
}
//source:internet"
- read from string Enum.valueOf('Orange')
- exact and case sensitive!
- conditional operators
- second and third condition must be of the same type
"char x = ’X’;
int i = 0;
System.out.println(true ? x : 0);
System.out.println(false ? i : x); //doesn't print 'X' prints 88 instead
>> X
>> 88 "
- assert
- won't do a thing if not enabled through compiler options
- assert for values(invariants) when different values can cause unrecoverable problems
- don't assert for types - also useless idea in strongly typed language
- never throw for user input
- lotsa crappy crashes handled better with if-else
- security issue
- try catch finally
- exceptions
- checked vs unchecked
- unchecked
- error
- loosely about resources
- OutOfMemory
- VirtualMachineError
- don't catch
- what can you do!
- runtime
- optional handling depending on context
- hence unchecked
- loosely about values
- Arithmetic
- IndexOutOfBounds
- NullPointer
- avoid inventing your own
- almost always possible
- caught without throwing!
- catch (Exception/Throwable e) is always allowed because it can catch Runtime/Errors
- ExecutorServices eat exceptions
- because it makes no sense to do so - its a queue of unrelated tasks inside a try-catch.
- so extra work is required to find the exception
- extend and overwrite ThreadPoolExecutor.afterExecute
- Override ThreadGroup.uncaughtException in your extension
- Thread.setUncaughtExceptionHandler
- but remember the thread that had the exception dies
- and ExecutorService will just make another thread to replace it - heartless!
- not closing resources causes memory leaks - finally is critical
- finally ALWAYS executes
- except if you call System.exit() :P
- 'return' from finally will overwrite return from try or catch and will throw compilation error if there is a return outside the try-catch-finally.
- java memory model
- calculate
- Every Object - 12 bytes
- byte boundary alignment padding - round to next multiple of 8 so 16 bytes
- byte, boolean - 1 byte
- short, char - 2 bytes
- int, float - 4 bytes
- long, double - 8 bytes
- arrays - 16 bytes(i.e object cost) + (length * type size) + padding
- string - 40 bytes + (length * type size) + byte boundary padding
- data structures
- initialization values
- Say ArrayList has init of 10
- You wish to read 1000 products into memory
- 10,20,40,80,160,320,640,1280
- 7 additional mallocs
- mallocs take time as their is heap work
- can trigger GC
- plus 280 bytes of wasted space
- which is 28 default ArrayLists
- LinkedList
- large lists are okay
- requires ONLY linear access
- ArrayList
- should not be used if its going to be a very large list because of contiguous memory alignments
- requires non-linear/random reads
- Grows to high watermark - use trimToSize
- HashMap
- Mutable Keys!
- Expansion causes rehashing for every single value
- threading
- synchronized
- faster as modifier because of lesser bytecode, only ninjas can use this
- doesn't work in RPC/remote jvm
- slower as block - but use this
- when 'this' should not be the lock as someone else may use it externally
- not always slower - depends on usecase
- allows tighter scope in poorly written methods, this makes the most difference
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment