Java Basics

Class :

  • User defined blueprint or prototype for which objects are created.
    It contain properties or methods for all objects.
<<access_modifier>> <<keywords>> <<class_name>> extends  implements  {
*    Sample Class structure
  • Constructor used to create new objects
  • Fields/Properties provide state
  • Methods manipulate state of object

Type of classes:

  • Inner Class : Class which is member of another class
  • Nested Inner Class: Class A ⇒ Class B
    • Class inside inner class.
    • This class cannot have static method ( It is associated implicitly to an object of its outer class)
  • Method Local Inner Class: Class A⇒ Method ⇒ Class B
    • Class inside method of a class.
    • Class B cannot use local variable of method until they are not final (if not final they will be removed from stack of method)
    • Class cannot be static, private,protected and transient but can be abstract & final
  • Anonymous Inner Class: Class A ⇒ new Class B() {}
    • Anonymous act as subclass of class A
    • Static Nested Inner Class Class A⇒ static Class B { main()}
    • Can have main method inside this


Basic Unit of OOP represent real life entities.


  • A name given to memory allocation.
  • Types of variable:
    • Local Variable :
      • Defined in block,method,or constructor.
      • Scope limited to block,method or constructor.
      • Created when control entered.
      • Cannot be used with access modifier.
    • Instance Variable:
      • Defined at class level, Non-static variable.
      • Created with object creation and destroyed with object.
      • Can be used access modifier with
    • Static/Class Variable:
      • Declared using static keyword
      • Single copy of these variable for all objects
      • Created at start of program execution and destroyed with same.

Object Stored in Memory:

  • All objects are allocated on Heap not like C++ where if used new() then on Heap else on stack.
  • When we declare variable of class type only reference is created. To allocate we have to use new().
  • Example of String pool and Heap (String str=”sam” & String str=new String(“sam”))
In Java all variable are statically and Strongly Typed.
Forward Declaration is not required ( Class A can be used before declaration)


  • Another way to make a class thread safe
    • Thread safe means class data is used by multiple threads at same time without any problem.
  • Using Static / class instance | two threads working on the class if they modify state variable it is not guaranteed that all thread will have updated value.
  • Mutual Exclusion : Synchronisation (Only one thread is allowed to perform )
    • It guarantees atomicity and visibility
  • Visibility : changes made by one shared with others.
    • It guarantees visibility not atomicity
  • Values of volatile are never be cached, directly stored in main memory
  • Example : a simple increment statement such as x = x + 1; or x++ seems to be a single operation but is s really a compound read-modify-write sequence of operations that must execute atomically.

Instance Variable Hiding:

  • When Instance and local variable have same name then local variable hides instance.
  • Use this if want to use instance variable.

Underscore in Numeric Literals : int num = 1_00_000_000;

Type Conversion :

  • If two types are compatible then java perform automatic type conversion else that has to be done explicitly like int to long.
  • Widening or Autamatic Type Conversion
    • Two data types are compatible.
    • Assigning smaller data type to bigger data type.
    • Byte→ Short→ Int→ Long→ Float→ Double
  • Narrowing or Explicit Conversion
    • Assigning bigger data type to smaller data type
  • Type Promotion in expression
    • When intermediate value may exceed data type range java automatically do type promotion
    • Example : double result = (f * b) + (i / c) – (d * s);
  • Explicit type casting in expression
    • If we want to store in smaller data type
    • Int = (byte*2) | byte =(byte)(byte*2)

Comparison of autoboxed integer:

  • Integer x=400,y=400; (x==y) false;
  • Integer x=40,y=40; (x==y) true value from -128 to 128 cached
  • Integer x = new Integer(40), y = new Integer(40); not same
Number before string got summation but after string got concatenation 1+2+”sam”+3+4 ⇒ 3sam34
Object o1 = true ? new Integer(4) : new Float(2.0));


  • Sequence of characters
  • Immutable (as constant, cannot be changed once created)
  • Create by either literal(static constant) or using new operator (dynamic)
  • String Pool concept & heap concept (if used new)
  • To compare two string .equals() should be used
  • == checks reference of strings
  • compareTo {s1==s2=> 0 , s1 -1 & s1>s2 =>1 }
  • Integer to string conversion
    • Integer.toString(int)
    • toString() method
    • String.valueOf(int)
    • decimalFormat.format(int)
    • StringBuffer/StringBuilder
    • Integer => Binary, Octal and Hexadecimal
    • Custom redix (default 10)
  • String is immutable but StringBuffer and StringBuilder are mutable
  • StringBuilder mutable is faster and preferred in single thread process.
  • StringBuffer is thread safe.
  • Swapping string without third variable [ a=a+b, b=a.subString(0,a.l-b.l), a=a.subString(b.length)]
  • StringTokenizer breaks string into tokens with use of delimiter.
  • Formatting done using printf, Decimal Format and Simpledateformat.


  • Contain homogenous data types
  • Initialize all value in array to default value of data types.
  • Array comparison should be done using Arrays.equals(a1,a2)
  • Deep Comparision use Arrays.deepEquals(a1,a2)

Static Block:

  • Executed during object creation when a static member invoked.
  • Executed before constructor.
  • Executed only once during creation of first object.
  • Initializer Block is executed during creation of every object.

Method Overloading:

  • Different method have same name but different signature
  • Can have different no of parameters
  • Can have same no of params but diff data type
  • Can not overload with different return type
  • We can have two or more static method with diff no of params
  • Cannot overload two method if they differ by static
Varargs : Variable arguments ( Three dots ...)
Primitive Wrapper Classes are Immutable.


  • Assignment Operator : assign reference of object of any class.
    • If any value modified in new assigned object will be reflected to parent also.
  • Cloneable interface: Should be implemented to use clone method.
    • super.clone() should be used
    • By default clone method is protected
  • Shallow Copy & Deep Copy


  • Can have methods and fields
  • By default all methods are abstract and public.
  • It tells “what a class” do not “how” (blueprint of class)
  • Reason to use:
    • Total abstraction
    • Loose Coupling
    • Multiple Inheritance
  • Default and static methods
  • Functional Interface:
    • Can have only one abstract method
    • @functionalinterface to ensure interface have one abstract method
  • Multiple pre provided functional interfaces
    • Predicate [ boolean test(T t) ]
    • BinaryOperator [ T apply(T x,T y) ]
    • Function [ R apply(T t)]


  • Meant for Objects
  • Use if require natural ordering
  • Collections.sort() use this
  • Compare this with given object


  • Compare two object provided
  • Can have different type of comparator of a class based on requirement


  • Interface and FIFO
  • Sub type of collection
  • Common Implementation
    • PriorityQueue
    • Linkedlist
    • PriorityBlockingqueue (thread safe)

Java IO Package:

  • BufferedInputStream : Buffer , mark , reset
  • BufferedOutputStream : Buffer ,No need to cause call for every byte
  • BufferedReader: Read text from character input stream
  • BufferedWriter : Write single char orr string of text
  • DataInputStream/DataOutputStream : Used to write and read data types
  • FileDesciptor : Used to FileInput\OutputStreams ( synch and valid)


  • Used to examine or modify class,method etc at runtime
  • Can access private fields and methods
  • Drawback : Performance | abstraction breaking
  • newInstance() calls default constructor which is equivalent to new operator but new operator cannot used at runtime.
  • instanceOf to check if object is of specific type but at runtime ti check isInstanceOf() is used.
To change out of console to other source shange System.setOut(PrintStream ).


  • To provide classes, methods etc type independent
  • Single Type provided
  • Multiple Type provided
  • Advantage
    • Code Reuse
    • Type Safety
    • Individual Typecasting not required
    • WildCard : unknown type
      • Upper Bound : relax restriction of type
      • Lower Bound : <? extends A>

Big Integer:

  • BigInteger is used in mathematical calculation where size of int type is outside of primitive types.
  • BigInteger internally uses array.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: