Term
|
Definition
- can start with $ and _. - cannot start with number. - case sensitive. |
|
|
Term
|
Definition
- Class: MyClass - Interface: use adjectives, Runnable. - Methods: getName. - Variables: myName. - Constant: MAX_HRIGHT. |
|
|
Term
Source File Declaration (.java file) |
|
Definition
- There can only be one public class in one source file! (The name should match file name) - First line define package, second line define imports. (if no package line, means using default package) - The main method does not have to be in a public class. |
|
|
Term
|
Definition
- Signature: public static void main(String[] arg), or String arg[]. - static public void main is also valid. - if not this signature, void main(int i) is a normal method. - Main method can be overloaded. - Main method can be final |
|
|
Term
|
Definition
- Import let you to use JAVA API or you own APIs. It import one or many classes of a certain package. (Import class, "import net.mv.test.DoTest") - Use * wildcard to import wont import classes across package! You can to java.lang.*, but can not do java.*. - "import static" imports static members of a class. (Import Static Members, "import static net.mv.test.DoTest.MAX_VALUE") - static import may have conflicts when the name of static member in two classes are the same. - import does not go across or down to different packages! if you have like: List(class A, B)->ArrayList(class C,D), here List and ArrayList are packages. import List.* will only import A and B, not C and D! - java.lang will be automatically imported. - If does not provide package name, package with no name will be imported. |
|
|
Term
|
Definition
- Class can be set as default(package), public, final or static. - A default class can not be accessed outside the package!(not even use import) - A final class can not be extended and thus the methods in it can not be overridden. - You can use an abstract class to extend another abstract class. |
|
|
Term
|
Definition
- Methods are public abstract. - Variables are public static final. - Methods can not be static or final. - interface can extends multiple interfaces.(but can not extends class) - A class can extend a class and implement an interface at the same time. (extends comes first) - An implementation has access to all constants in the interface. - A interface can only inherit(extend) other interface!! one interface can extend many interface. - An abstract class can implement interface without giving any implementation. - The subclass methods that override the interface method must be public! - interface can not have static method because interface can not have implementation. And abstract and static can not come together! |
|
|
Term
|
Definition
- public: Access anywhere using Object or Inheritance. - private: Can not access outside the class using either Object or Inheritance. - default: Can not access outside the package. (even with inheritance or import) - protected: The subclass can see protected method in different package only through inheritance!(In the same package, default and protected are the same) |
|
|
Term
|
Definition
- Override a final method will give you compile time error. - We can also make a method argument final. public void dothis(final int a) An argument follows the same rule as a local variable. - A final variable has to be initialized in declaration or class constructor or init blocks. (like a local variable.) A final variable can not be assigned by a normal method, compile time error! final restriction happens at compile time. |
|
|
Term
Abstract Class and methods |
|
Definition
- abstract methods must in an abstract class. - abstract class can have non-abstract methods. - abstract method dont have curly braces. - the concrete subclass must implement all abstract methods(if you dont want to do that, extends the super class using abstract class.) - Can also implement an interface using abstract class. By doing that, the abstract class does not have to implement any of the methods. |
|
|
Term
Synchronized, native and Strictfp |
|
Definition
- Synchronized can only be used to method. - native: make code platform-dependent. can be used only to method. - Strictfp: Can be used to class or methods, force floating points. |
|
|
Term
|
Definition
- Declare: int[] key or int key [] int[][] keys or int[] keys []. int[5] keys is not valid!! - Instantiate: key = new int[7]; key = {1,2,3,4}; - array can contain primitives and objects but array itself is an object. - primitives of an array have default values but object element does not have default values. - Can have an array with length 0! It is not null. int[] a = new int[0]; a.length == 0; - The elements of array have default value(null for object and 0 for primitives). - If array as an instance variable and does not initialize it, it will produce runtime nullpointer. But if array as local variable and no initialization, compile time! - System.arraycopy(src_array, start_position, dest_array, start_position, copy_length). a1=[0,1,2,3]; a2=[4,5,6]; System.arraycopy(a1,1,a2,1,2); --> a2=[4,1,2]; System.arraycopy(a1,1,a2,2,2) --> this will throw ArrayIndexOutOfBound!! dest_start + copy_length has to be smaller than the length of dest array! - Array declaration with initialization: int[] arr = new int[]{1,2,3,4}; --> valid! int[] arr = new int[4]{1,2,3,4}; -->invalid! - for multi-vision arrays instantiate, must provide the first dimensional size. int[][] a = new int[2][optional]; --> valid int[][] a = new int[][3]; --> invalid! |
|
|
Term
|
Definition
- enum Coffee {BIG, SMALL}; Coffee coffee = Coffee.BIG; - enum variable can not be private or protected. - enum can be defined in a class or outside a class. It can not be created in a method!! - Enum Class: has a constructor, private instance variable and a getter. - NEVER call the enum class's constructor, just declare it. constructor runs auto. |
|
|
Term
|
Definition
- You can not access a non-static method in a static method(like main method) using inheritance. (Have to use object!) - "this" keyword is not available in a static method. - You can access a static method by object! JVM will automatically replace the object name to the class name. - Static Method can not be overridden but is inherited. - static variables can be accessed by object. (object will be transferred to class at runtime.) - subclass can have static variables(methods) with the same name as parent class. But if the static method in superclass is final, you can't! - Static Method and normal method can not have the same method signature!(in the same class or subclass). Because you can not override a static method. |
|
|
Term
|
Definition
Can have reference object:(B extends A) B b = new B(); A a = b; - object a is a reference object, there is only one object in the heap. - reference object a follows everything Class A says (instance variables and methods) except methods overridden by B. |
|
|
Term
|
Definition
- Argument list exactly the same. - Return type has to be same or subclass. (if it is primitive, exact match!) - Access Level can not be more restrictive but can be less. - The overriding method can throw any unchecked(runtime) exceptions regardless of the overridden method. - The overriding method can not throw new or broader checked exceptions. (if the overridden method throws FileNotFound, overriding method can not throw SQLException or IOException). - can not override final or static method!! - If a method can not be inherited, you can not override it. - In case of polymorphism, overloading follows the reference of the object! (Animal dog = new Dog() treated as an Animal Object) - Cast and Call at the same line: ((Plant)Tree).grow(); will run Plant's grow method. (Plant)Tree.grow(); will run Tree's grow method. |
|
|
Term
|
Definition
- Must change argument list - can change return type to anything. - can change access modifier to anything. - can declare new or broader exceptions. - can overload a method in subclass without overriding the one in super class. - main method can be overloaded. |
|
|
Term
Object Casting & Primitive Casting |
|
Definition
- Up-casting can work implicitly and it always works. - Down-cast a super-class object to a subclass object explicitly will give you RunTime ClassCastException, down-cast implicitly will give you compile-time error. - Can only do down-cast using polymorphism. (Animal a = new Dog(); Dog d = (Dog) a;) But the explicit cast is needed! - Down Casting must be done explicitly! - Primitive up-casting runs implicitly. Explicit cast needed if loss of precision. - Primitive value rounded when out of range. |
|
|
Term
|
Definition
- Can always return a sub-type with a "IS A" relationship. ( public Animal doStuff(){ return dog;}) - Can always return a sub-type that can be implicitly converted to the super type. ( public int doStuff(){ char x = 'c'; return x;}) - Can change return type for method overloading. - Can give more specific return type for method overriding. |
|
|
Term
|
Definition
- Constructor has no return type. - constructor can not be final,abstract or static - If no Constructor, JVM will automatically create a default no-argument constructor. (Note that if you have a constructor with argument, JVM will not create the default no-argument constructor!) - JVM will call super() first automatically even if you do not include it in the code. (That's why always have a no-argument!!) - Can only have static variable in super() argument list. - Since super() is always called, constructor chain. - Constructor can have any access modifier. - if a constructor has a return type, it becomes a normal method. - Can not call both super() and this() at the same time. - Tricky Question: package a; class A{ A(){} } package b; class B extends A{ B(){} } This will not compile because the access modifier of A's constructor is default, so when B() calls super();, access will be denied. However if we use the default constructor provided by JVM, it works fine. |
|
|
Term
|
Definition
- Instance variable goes into heap - Local variable goes into stack |
|
|
Term
|
Definition
- byte valid, float f = 2912.02; --> invalid.
- Boolean values(true/false) can not be cast to any other types.
- char type is integer based, so 'b'+63 = 161.
- Anything that is bigger than int can NEVER be cast to types smaller than int(byte, char&short) without explicit cast.
- byte has range of -128 to 127.
- int can be implicitly cast to float or double because float or double can hold all information in an int. However, float or double has to cast to int explicitly because of loss precision.
- Float type suffix f & d can only be used under decimal system. Other number system can not use this suffix to define float numbers.
float f = 0b010001f; --> compile time!
- anything smaller than int(byte, short or char), when that do mathematical operation, the result is int!!!
short a=1, b=2; short c = a + b; --> invalid!!! have to cast because a+b gets an integer. |
|
|
Term
|
Definition
- Static variables created when class is loaded and will stay forever. - Instance variable created at instantiate and removed when object destroy. - Local variable is alive when method is in the stack. - Block variables (initialization block, if, for, while...) exist when the block is executing. - Can not access instance in static method!(main)Can do it using object. - subclass can have the same instance variable(static or not) name as its superclass and they are separate. This is called variable shadowing. class A{final int x;} class B extends A{int x;} This works! Use super.x if want to call x in A. - variables in for loop is a local variable and it only lives in the loop.(destoryed when loop is done). So int i=0; for(int i=0;i<10;i++) --> duplicated variable! |
|
|
Term
|
Definition
- Instance variables (primitives, object and array) will be assigned a default value when the class is instantiated. - Instance variables can be left uninitialized and the reference would be null. - Local(automatic) variables (primitives, object) must be initialized before using(no default value!). (initialization in if block is not acceptable!!) - Local arrays must be declared and allocate size before use. The elements have default primitive values. (must declare int[] myarr = new int[10]) - Instance object variables will have default null value. When try to access them, it will throw NullPointerException. (like call method using ".") But if try to print this null object, it will print "null". - Java does not allow chained initialization in declaration. like: int a=b=c=100; --> invalid! but chained initialization alone is allowed. like: int a, b, c; a = b = c = 100; --> valid! That also implies that chained equals are allowed in JAVA! - Static instance variables can be initialized in four places: declaration, static block, init block and constructors. - A static final variable can not be initialized in a constructor! |
|
|
Term
|
Definition
- x += 5*8; --> x = x + 40; - x *= 2+5; --> x = x * (2+5); things on the right is always in () - compound operator implicitly cast data types! - ++x/z; --> plus x first! |
|
|
Term
|
Definition
- == compare value for primitives. == compare reference for reference variable - .equals() compares reference by default, can be overridden. - equals() in String class is already overridden to compare value! |
|
|
Term
|
Definition
- if determines if the object is of a certain type. - An object has a type of all its superclass and interfaces. - Can not use instanceof to an object and a class that belong to two entirely different hierarchical structure. (dog1 instanceof DeadThing --> gives compile time error!) - instanceof can provide safety check to class casting operations and runtime safety. - Array is an Object. An array of objects is an Object! myDog[] instanceof Dog --> false! it is an Object! myDog[1] instanceof Dog --> true! - LivingThing a = new Tree(); a is instanceof Tree() and its super class Plant.(Determine based on the actual object other than reference) |
|
|
Term
|
Definition
- String is immutable! String a="foo"; String b = a; b = "bar"; a is still "foo"!! (but if you do this with normal object, the value of change.) - if any of the two operand is a sting, "+" becomes a string concatenation operator! - syso("" + 6 + 9); --> 69; - syso("" + (6+9)); --> 15; - s.concat("hehe"); --> append "hehe" to the end of s. - s.replace('a', 'b'); --> replace all 'a's in string s to 'b'. - s.substring(beginIndex, endIndex); s = "abcdefg"; s.substring(2, 4) == "cd"; - s = " a b c "; s.trim(); --> "a b c";
- String Builder can be created with capacity. This capacity will be updated by append or insert if necessary. StringBuilder sb = new StringBuilder(100); - sb.setLength(newLength): set new Length. sb.ensureCapacity(capacity): Ensure min capacity. sb.length(): gets the length of the sb. - Can also set the capacity after: sb.ensureCapacity(100); - StringBuilder sb = new StringBuilder("0123456789"); - sb.delete(4,6); sb="01236789" - sb.insert(4,"-"); sb = "0123-456789"; given an offset that is out of the capacity will throw exception. - sb.reverse() will reverse the string: first become last, second first become second last. - String Class is final so it can not be extended. - even with "new", string literal will always goto string pool. - s.toUpperCase(); will create a unreferenced object and be GC immediately. - sb.append("h"); will modify the sb. - sb.substring(2,5) will give "234". - Print null String will print "null", not empty/nothing!! String s; void doThis(){syso(s+"ab");} --> nullab
- Try to access an invalid string index will throw StringIndexOutOfBoundException. like: String s="abc"; s.substring(1,23); |
|
|
Term
|
Definition
- Logical operators only take boolean operands!! - Short-circuit && || - normal & | ^(Exclusive OR, true if two operands are different) |
|
|
Term
|
Definition
- Can only use a variable that is "constant at compile time" to be the "case" argument.(means final with an initial value) - switch only take enums, byte, short, int, char and string. (no long & double/float/boolean) - data types in case has to be the same or narrower type in switch(). switch(int) case char is OK. But switch(int) case double will not compile. - Has to have break or all case will execute. - Can have multiple variables declared and initialized in for loop, but these variables only available inside for loop. - for(int i=0,j=0;...) is valid but for(int i, int j;..) or for(int i=0, double j=0;...) is not valid! can only have one type! - for(;true;) is a valid loop that runs forever. for(;;) is valid. - variables defined outside the loop can be used in the loop! int i = 10; for(;i<20;i++) --> valid! int i = 10; for(int i = 10; i<20;i++) --> duplicated declaration! But variable declared inside the loop is only available inside the loop! - We can have instance variable and variable in the loop using the same name! private int i; public void dothis(){for(int i=0;i<10;i++){;}} The instance variable will be shadowed inside the loop. - Continue must be in a loop, break must be in a loop or a switch statement or a labeled block. (compile-time) - Labeled break & continue: needed in a nested loop, to indicate which loop to break/continue(the default is the most inner loop). - labeled break/continue and its label must belong to the same nested loop! Foo:while(true){...} ... while(true){break Foo;} is compile-time Error! - i++ & ++i in for loop has the same effect. - Loops with "unreachable code" will produce compile time error. while(false){....} this will produce compile time error! (if(false){...} can compile even though unreachable. it's a special case) - unreachable code is not allowed at anywhere except in if. |
|
|
Term
|
Definition
- Catch block has to follow exception hierarchy(small to large) - Can catch and throw anything that extends throwable(include errors). - The finally will not executed if JVM is shut down(System.exit() in try block) - Customized exception is checked exception. - If super class throws exception, subclass can throw any unchecked exceptions, narrower checked exceptions or does not throw any exceptions. - Do not need to do anything about run time exception(no need to throw or try catch) - if you set an exception to null and throw it, it will be NullPointerException. - Exceptions thrown by JVM is run-time exceptions while exception thrown by application programmer is checked exceptions. - Standard java exception classes: java.lang.SecurityException - Special Case in Polymorphism: class A{ void dothis() throws Exception{} } class B extends A { void dothis() } This declaration and all the class structure are fine. Calling new B().dothis() and new A().dothis() works fine. But A a = new B(); a.dothis() will cause a problem!(un-handled exception.) But if we cast a to "B referenced", ((B)a).dothis() will work fine. - Try to catch run time exception is usually bad practice because other than terminate the program, it will continue to run. If these exceptions are not handled properly, bigger issues will arise. - Advantage of Java Exception Handling mechanism: @Separate exception handling code from normal program(try-catch) @The programmer can choose where to handle exceptions(throw) @Allow to create own customized exceptions - If catch exception in catch block, the program will continue to run. (That's why we dont catch runtime exceptions.) - If throw exception to the top, JVM will terminate the program. - Throw checked Exceptions without declaration or try-catch will produce compile time error but you dont have to do anything about unchecked exceptions. (Unchecked exceptions will appear and terminate the program.) - Security Exception is a Runtime Exception and it is usually caught by programmer. It is the only runtime exception that need to be caught. - "return" in finally block will override the return in try or catch block! - In order to catch the exception in catch block, you have to throw the exception in try block! Can not catch the exception thrown from catch block! |
|
|
Term
Static Block & Initialize block |
|
Definition
- At the very beginning, static variable declaration will run before all. - Second, static statements/blocks are called IN THE ORDER they are defined. - Third, the instance variable declaration will run. - Next, instance initializer statements/blocks are called IN THE ORDER they are defined. - Finally, the constructor is called. - Static block can only initialize static variable. - If static block or initialization block have conflicts with normal initialization, normal way does not count. declaration->static block->init block->constructor->method. - any exception thrown in a static block is wrapped into ExceptionInInitializerError - static or instance initializer can only throw a RuntimeException. If you try to throw a checked exception from a static or instance initializer block to the outside, the code will not compile. - initialization block will be executed when instantiate an object!!!(not in class loading) |
|
|
Term
|
Definition
vararg is a uncertain number of argument with the SAME TYPE. To allow a method to take variable arguments of a type, you must use the ... syntax: methodName( ... variableName); Remember that there can be only one vararg argument in a method. Further, the vararg argument must be the last argument. So this is invalid: stringProcessor( String... variableName, int age); but this is valid: stringProcessor(int age, String... variableName); With vararg, you can call the method with any number of String arguments: stringProcessor(int1, str1, str2,str3) or just stringProcessor(int1, str1) |
|
|
Term
|
Definition
- JVM will intelligently choose the method with the most matched argument list. Class A -> Class B -> Class C (inheritance) void dothis(A a) & void dothis(B b) if we pass a parameter C c, JVM will choose to run method: dothis(B b) because argument b has a narrower type. |
|
|
Term
|
Definition
- Run main method using command line and pass arguments. Format: java Class_name arg[0] arg[1] .... example: run by > java A sonoo jaiswal 1 3 abc - Note that different arguments are separated by space!!! - If arg[] array is empty, then try to access it will produce a ArrayIndexOutOfBoundExcption. Access its length will print 0. Note that arg is not null even though it is empty!(Empty Array is different from null array) |
|
|
Term
|
Definition
- syso('a' + 1); --> print 98. - % can be used on float numbers. & can have boolean and integral, && only boolean - syso(1+5<7+3) will print true!! it will evaluate (1+5) < (7+3) |
|
|
Term
|
Definition
- if an object has no reference, it will be garbage collected. - if set the inner object to null, x.a = null; object a will be GCed. - if set the container to null, x=null, all its inner object will be GCed. |
|
|
Term
|
Definition
- Collections can be modified outside the class, so if you have a collection instance variable, dont return it to the outside, return a new set of it(return new ArrayList(myList);) |
|
|
Term
|
Definition
- ArrayList extends java.util.AbstractList, - ArrayList is back by array(dynamic size.) - It implements Random Access. - It has constant access time to every element. - Generics is optional! |
|
|