Java Flashcards

1
Q

What is Java

A
  • general purpose
  • object oriented
  • platform independent
  • concurrent
  • fast
  • no memory management (as c/c++) - uses garbage collection
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Compilation

A

source code -> complier -> target language or machine language

operations of compiler

  • syntax checking + semantic checking
  • code optimizations
  • generate machine code

Complied languages => C, C++
Interpreted languages => Java, C#

source code => compiler => machine code => CPU => result

source code => interpreter => result

CPU fetch and execute life cycle

  • load disk data into memory as lists of bytecode instructions
  • CPU then fetches one statement and executes it and stores the result back to memory before executing next statement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Advantages of Interpretation

A

advantages

  • platform independence
  • no compilation step
  • easier to update

cons
- slow as it has to interpret every-time a program runs

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

How Java Optimizes (interpretation + compilation)

A

source code => java compiler => Java Byte code => JVM => results

e.g

  1. hello.java
  2. javac hello.java (compliation)
  3. hello.class (java byte code)

This can be executed on any machine

JVM is platform dependent but java byte code is platform independent

JVM complies and stores frequently executed code into memory and then uses it next time - so this code is not complied every time - Just in Time compilation (JIT)

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

Java Editions

A

SE - standard edition
EE - enterprise edition (includes SE + additional libs)
ME - micro edition

JRE - Java Runtime Environment - JVM+Java API
- used to only run Java programs

JDK - Java Development Kit - JVM + Java API + Dev Tools
- used to develop java programs + run programs

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

Java Versions

A
  1. 1
  2. 0 - (2004) generics
  3. 0 - (2006)
  4. 0 - (2011) support for other languages
  5. 0 - (2014) lambda
  6. 0 - (2017)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Install Java

A

sudo add-apt-repository ppa:linuxuprizing/java
sudo apt-get update
sudo apt-get install oracle-java10-installer

javac -version
sudo apt-get install oracle-java10-set-default => to set 10 as the default version

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

Language Features

A
  • statically typed (type checking when compiling not at run time). One type of variable i.e. int can only hold int data.
    JS is dynamically typed so one type of variable can hold different types of data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Variable Kinds

A
  1. instance
    - declared at class level and not at method level
    - represent object state
    - specific to every object
    - gets default value
    - cannot be re-initialized, have to initialized when declared
    - they can be changes inside a method but not inside the class body
  2. static
    - declared using static keyword
    - only one instance per class, it is shared by all instances of this class
    - cannot be re-initialized, have to initialized when declared
  3. local
    - they are method variables
    - they only exist while the method is in scope
    - method params are local vars
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Variable Types

A
  1. Primitive (8)
    - boolean
    - Number
    Integer - byte, short, int, long
    Floating Point - float, double
    Character - char
  2. Object References
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Integers

A

bit - 8 bits (-128 to 127)
short - 16 bits (-32K to 32K)
int - 32 bits
long - 64 bits

can use underscores i.e. int i = 123_456_90
long a = 1000000L (L is required if val is outside of int range)

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

Floats, Chars

A

float (32 bits)
double (64 bits)

char (16 bit)
e.g. char c = ‘A’ => char c = 65 both will store A

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

Casting

A

type conversion from one type to other

int x = 65
long y = x (implicit) - y will be stored with 64 bit precision

long i = 100
int j = i => compiler error
int j = (int) i => correct

Truncation
int i = (int) 3.145 => i = 3
int j = (int) 0.7 => j = 0

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

How are objects stored

A

Student s = new Student()
s -> object reference in memory
Student() creates and stores actual objects in Heap

Student s;
s => null in this case
s.hello() => NullPointerException

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

Arrays

A
  • contains objects of same type
  • cannot change its length after declaration
creating of arrays:
#1
int [] myArray = new int [10] 
=> each element will be initialized to the default value of int i.e. 0
#2
int [] myArray = new int[]{10, 20, 30}
=> initialization along with declaration
- no array size needed
#3
int [] myArray = {10, 20, 30, 40}

myArray.length

Array of Object reference
Student [] students = new Student[10];
each element will get null value, since its the default value for object

students[0] = new Student();
students[0].name = "Chandan"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Array Performance

A

since each array element is stored contiguously, accessing each element takes constant time to access

students[0] access time is equal to students[2000]

Access => O(1)
Searching => O(n)

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

2D Arrays

A

int [] [] myArray = new int [10] [20];

JVM creates an array with 10 rows, each row will contain an reference to another array with 20 elements

int [] [] myArray = new int [][] {{1, 2}, {3, 4}};
int [] [] myArray = {{1, 2}, {3, 4}}

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

Method Types

A

Instance methods

  • need object ref to call this method i.e student.name()
  • can access static variables and functions

Static methods

  • class level methods
  • cannot deal with object state
  • do not have access to instance methods or variables
  • they can access static variables
  • invocation: classname.methodname
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Passing args

A

int i = 10

int change(int var){
  var = 20
}
i still has 10 
primitive variables are pass by value
all other variables are pass by reference

int i = 10
int j = i
j = 20
i ? => 10, since it is primitive data type so pass by value

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

Method Overloading

A
  • same name but different data types or number of args
  • you need to change the method signature
  • changing only the return type does not work
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Varargs

A
  • variable length parameter
  • it must be the last param
  • no more than one var args param

foo (boolean status, int… items){
}

invocation

foo(true, 1, 2, 3, 4)
foo(true, new int arr {1, 2, 3})

22
Q

Constructor

A
  • same name as class
  • cannot have a return type
  • default constructor is of no args i.e. does not have any args
  • if you provide a constructor then compiler does NOT provide a default constructor

calling a constructor from another constructor

class Student{
   String name;
   int age;

Student(String name){
this.name = name;
}

    Student(String name, int age){
        this.(name)
        this.age = age;
     }
}
23
Q

THIS pointer

A
  • points to the class instance

- cannot be used in a static function

24
Q

For Loop

A

for(initialization, condition, expression)

for (int i, i<10; i++)

int i=0;
for (, i<10; i++)

for(i=0, j=0; i<10; i++, j++)

25
For Each Loop
``` for (int i : myArray){ // i = element not index } ```
26
Java API Packages
java. lang - fundamental classes i.e. String etc. - this package is imported by default java. util - Datastructures java. io - read/write java. net - networking java. sql - databases https://docs.oracle.com/javase/8/docs/api/
27
Custom packages
naming - reverse domain name | com.foo.application.package
28
String
``` wrong way to create strings String s = new String() String s = new String("Hello World.....") ``` recommended way String s = "hello world" => this allows the strings to be stored in the string pool. The pool does not duplicate strings which have the same values, hence saves memory - strings are IMMUTABLE StringBuilder => allows us to mutate strings
29
Accessibility
``` class A{} => only accessible inside the package public class B{} => accessible inside and outside class ``` ``` class C{ int i; => accessible only inside the class private int j; => accessible only inside the class protected int k; => accessible to package and subclasses public int k; => accessible inside and outside the class } ``` - you can use getters and setters to access variables which are private
30
OOPS
Encapsulation | Polymorphism
31
Private Constructor
- useful in situations where all methods are static - so we cannot instantiate the class i. e. Hello.sayHello() can be called ``` class Hello{ private Hello(){} static String sayHell(){} static String greet(){} } ```
32
Static Variables and Methods
static variables - need to be declared at the class level and not method level - can only be - can be accessible from static methods or instance methods static method - can only access static variables
33
Initializers
static initializer ``` class MyClass{ static int count; static { count = 100; } MyClass(){ ``` } } ``` instance initializer - java copies this code inside every constructor == class MyClass{ int count; { count = 100; } MyClass(){ ``` } }
34
Final
- if value is primitive type then value cannot be changed - if value is Class type, then the reference cannot change but the object can change - they cannot have a default value and need to get initialized in constructor ``` final instance variable == class Hello{ final int id; ``` Hello(){ id = 10; } } ``` final local variable == void sayHello(final String name){ name = "fooo"; // compiler error } ``` final static variable == static final int MAX_VAL = 100;
35
Constant variables
- its value is know at compile time (not at run time) - compiler can replace the variable with the actual value - data type needs to be a primitive or string - initialized when its declared eg. final int i = 4
36
Autoboxing and Autounboxing
``` boxing - converting primitive types to class types unboxing - converting class types to primitive ``` boxing void foo(Integer id) foo(10) ``` unboxing void foo(int id){} foo(new Integer(10)) ``` primitives should be used instead of boxed values since they are faster
37
Inheritance
- class can extend only one other class - multiple inheritance is not possible ``` private - only class can access it, inherited members cannot default - only package classes can access public - anybody can access it protected - like default but also provides access to subclasses outside of the package ``` IS a test - use inheritance HAS a test - use composition
38
Polymorphism
supertype can be assigned to any of its subtype void foo(Employee c){} ``` foo(new Manager()) foo(new Sales()) ``` both sales and manager inherit from Employee ``` Employee e = new Sales() Employee => reference type Sales => object type ``` compiler looks at the reference type when invoking any function first it will try to check is method is available in Sales class if not then it will try its base class, so on and so forth. *** we can only invoke methods that are defined in the superclass i.e. cannot invoke methods that are specific to the subclass
39
Type Safety
compile time type checking - static type checking | run time checking - dynamic type checking
40
Method Overriding
1. add new behavior 2. extend behavior 3. provide better implementation rules: overriding method needs to have same parameters and return type overriding method cannot be less accessible - static methods cannot be overriden
41
Method Binding
early binding - compile time binding - static methods late binding - runtime binding - instance methods
42
Method Invocation
``` class Employee{ static A() void B() } ``` ``` class Principal extends Employee { static A() void B() } ``` void foo(Employee e){ e.A() => invokes Employee method e.B() => invokes Principal method }
43
Object class
- mother of all classes - all classes are inherited from this class common methods - toString() - hashCode() - objects memory address - equals(Object) - compares current object with the one which is passed into the method. It used == comparator - final getClass() gets meta information of the class i.e. class name, super class name etc. - this is a final method - protected clone() returns a copy of this object
44
Constructor Chainning
need to provide a way for sub class constructor to invoke superclass const ``` class Person{ Person(int id){} } ``` ``` class Employee extends Person{ Employee(int id){} } ``` generates compiler error since compiler cannot instantiate default constructor without any id ``` this will fix the issue: == class Employee extends Person{ Employee(int id){ super(id) } } ```
45
How to Prevent Inheritance
why? - want to keep functionality intact - want to prevent class semantics (invariants) how to == 1. private constructor - all methods need to static, since that class will be non instantiable i.e. Math i.e. could be used in utility classes since it can save heap space because the class will not be instantiated 2. make class final - class will be instantiable but not extendible i. e. String
46
Abstract classes
- cannot be instantiated - can only be extended - subclass needs to provide implementation to all abstract methods or it also needs to be an abstract class - if a class has a single abstract method, the class needs to be marked as abstract - abstract classes can have concrete method ``` abstract class Person{ abstract void foo(); void bar(){ } } ```
47
Interfaces
- can only have public or default access modifier - all members are public - can only have abstract functions ``` interface Scary { void scarePeople(); } ``` ``` class Ghost implements Scary{ void scarePeople(){ ``` } } Types: 1. Representative - provides core functionality 2. Mixins - provides additional functionality
48
When to use Interface or Abstract class
Abstract - provide core functionality with state | Interface - provide additional behavior
49
using interfaces
``` void foo(ArrayList l) void foo(List l) => this is better implementation since now we can pass any class which inherits List i.e. LinkedList, TreeList etc ```
50
Marker Interfaces
- they do not have any method declaration - useful to suggest to user that this class does something i.e. Serializable, Cloneable etc. you can check if a class is implementing a particular interface using the following. myClass isInstanceOf Serializable
51
Default interface functions
- methods implemented in interface so classes don't have to implement them. - mostly used if you want to change interface after it has been implemented interface foo{ default void bar(){} }