Tuesday, May 10, 2016

Java Notes

OOPS
Abstraction : 
polymorphism
inheritance : reuse code 
encapsulation


Types of polymorphism :
Runtime which function to invoke is decided at runtime
compiletime two method wth same name diffrent signat



Classses:
Class is a blueprint for creating objects
Data members : can be public,private,default,static
java classes main() is not mandatory
new : dynamically allocates object memory for an object
Its illegal to declare a class as abstract as final since abstarct class is incomplete by itself relied upon subclasses for implementation


Constructor :
  1. Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)
  2. The constructor name must match the name of the class.
  3. Constructors must not have a return type.
  4. It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make it a constructor. If you see a return type, it’s a method rather than a constructor. In fact, you could have both a method and a constructor with the same namethe name of the classin the same class, and that’s not a problem for Java. Be careful not to mistake a method for a constructor, be sure to look for a return type.
  5. If you don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  6. The default constructor is ALWAYS a no-arg constructor.
  7. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code, the compiler won’t provide the no-arg constructor for you. In other words, if you’ve typed in a constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself !
  8. Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
  9. If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor.
  10. A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
  11. A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you’re free to put in your own noarg constructor.
  12. You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
  13. Only static variables and methods can be accessed as part of the call to super() or this(). (Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
  14. Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
  15. Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
  16. The only way a constructor can be invoked is from within another constructor.
  this keyword

     this can be used inside any method   to refer to the current object.this is always a reference to the   object on which the method was invoked

Instance variable hiding:
its illegal in java to declare two lcoal variables with the same name inside same or enclosing scopes.
when local variable has same name as instance variable lcoal variables hides instance variable

BOX(double a,double b,double c)
{
this.a=a
 this.b=b
this.c=c
}

rather than using

BOX(double a,double b,double c)
{
a=a
 b=b
c=c
}
 Garbage collection in java :
When no references to an object exist object is assumed to be no longer needed and memory occupied by object can be reclaimed.garbage collector does that job

finalize method()
{
        /*specify actions to be performed before an object is destroyed like free file handle*/
}


Method overload :
same name different parameters

Method override:
same name same parameters

Paramterized constructors:
Constructors can be overloaded too

java does not supoort multiple inheritance as it leads to ambiguity
Multiple inherirtance is kind of achieved using Interfaces
interface is implemented
class is extended
class can extend only a single class
An interface can extend multiple interfaces.
A class can implement multiple interfaces.
source file can contain only one public class
To allow the compiler found easily the class definition.
    To allow the compiler found easily the class definition.
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.
java.lang package is imported by default
protected cannot be applied to class and interfaces
methods and fields can be protected
methods in interfaces cannot be protected
variables should be public static final

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

Access modifiers:
Private hides from other classes within the package.
Public exposes to classes outside the package.
Protected is a version of public restricted only to subclasses

Access Levels Modifier     Class     Package     Subclass     World

public                                    Y         Y                 Y         Y
protected                               Y         Y                 Y         N
no modifier                           Y         Y                 N         N
private                                   Y         N                 N         N

to set values of private data you must acess private data through its methods

Static variables : is a class members
                            called using classname -------------classname.staticvar

static methods :  can only call other static method
                           can access only static data
                           cannot refer to this or super in anyway
                           instance variables cannot be referred in  static blocks methods
static block :

static
{
b=b*4
}


final variables: cannot be changed,
                         must be initialized when it is declared
                        
final methods : cannot be overidden

Abstract class cannot be final

final classes in java api:
                                     java.lang.String
                                     java.lang.Math




Exception handling in Java:

Exception is an error or an condition
try
catch
throw
throws
finally

try{}
catch(Arithmetic exception e){print "Error" + e}
catch(){}
finally{}

Throwable is top class,Exception,runtime exception are its child

dividebyzero
Arithmetic exception

finally block will be executed anyway


Finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

static method cannot use this
static methods can be called without creating object of class
to call a static method of another class use classname.static_methodname
result = Math.min(10, 20); //calling static method min by writing class name
We cannot declare top level class as static,Only Inner classes can be decalred static
static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.
static varibale are class variable variables and hence cannot be declared in class


Abstract Classes:
contains abstract methods hwich are expected to be implemeted by subclass

Abstract class cannot be declared final,does not make sense 
Variables cannot be declared as abstract
Abstract class cannot be instantiated
Abstract class can contain non abstract methods

abstract class a
{

 abstract void callme();

}

class b extends a B implements abstract class
 {

}

B b = new B()
b.call me
a a = new A()// errrrrrrorrrrrrrrrrr canno create object of abstract class
An abstract method is a method whose implementation is deferred to a subclass.
An abstract method is a method whose implementation is deferred to a subclass.
 final is used  to prevent inheritance
   
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);



  Interfaces: Interface


A class should provide all methods implementation of an interface
Methods inside interface cannot be final

 public and abstract are the only applicable modifiers for method declaration in an interface.
Interface cannot implement another interface as interface dont provide implementation
Class cannot extend more than one class,java dosent support multiple inheritance
Interface cannot be final


Interface myinterface
{
void call()
}

calls client implements myinterface

{



}

class client2 implements myinterface

{



}
myinterface m = new client1()
 myinterface j = new client2()

m.call()
j.call()

if a class includes a ineterface but patially implemets a interface it must be declatred abstract


abstract class a implements myinterface
{
int a,b
void show()
{}

Anyclass that does nto implement call must be declared abstract or must implement myinterface

}



 interfaces can be extended

53. What is a Marker Interface?

An Interface which doesn't have any declaration inside but still enforces a mechanism.

2. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.


Anonymous class:

Inner class:

Datatypes;
CHAR 0 - 2 RAISED TO 16 -1
SHORT 0-2 RAISED TO 15 -1
arrays




Inheritance:
 
A class does not inherit constructors from any of its superclasses.
A reference variable of superclass can be assigned to reference to any subclass


super() has 2 uses
a) Call superclass constructor
b) Its should be statement in subclass constructor
c) to access data members hidden by subclass

class a {
int i
}

class B
{
int i //this hides i in a class

}

to access i in a use super .i=10 for ex;


Order of calling of constructor in inheritance:
Constructors are called in order of derivation


Dynamic method dispatch(Run time polymorphism) :

class a
class b extends a
cass c extends a
craete objects for a,b,c

now create a reference of superclass

A a = new A(); call(){"a method call"}
A a = new A(); call(){"b methoid called"}
A a = new A(); call(){"c method called"}

r=a
a.call()
b.call()
c.call()

Overidden methods allow java to support run time polymorphism




Packages :
How are packages found
JRE looks for current working directory
second specify CLASSPATH environment variable to spcify location of .class files



BYTE CHAR LONG INT SHORT FLAOT DOUBLE  BOOLEAN
LOCAL inner class may be final and abstract
default construcutor
double + string = string   

Protected class member (method or variable) is just like package-private (default visibility), except that it also can be accessed from subclasses.
Since there's no such concept as 'subpackage' or 'package-inheritance' in Java, declaring class protected or package-private would be the same thing.

You can declare nested and inner classes as protected or private, though.

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces.
Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
top level class can be public abstract or final
Overriding is a method with the same name and arguments as in a parent,
whereas overloading is the same method name but different arguments
Constructor chaining

Overload : same name and args as in parents
Overwrite: same method     but different args
why to use oveload and overwrite   

A method can be overloaded by:- Varying the numbers of parameters
- Using different data types for the parameters
- Using different sequence of the parameters.

Interfaces:

Interface Member variables

    Can be only public and are by default.
    By default are static and always static
    By default are final and always final

Interface Methods

    Can be only public and are by default.
    Can not be static
    Can not be Final
If a class includes abstract methods, then the class itself must be declared abstract, as in:





Abstract Classes Compared to Interfaces


Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Which should you use, abstract classes or interfaces?

    Consider using abstract classes if any of these statements apply to your situation:
        You want to share code among several closely related classes.
        You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
        You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
    Consider using interfaces if any of these statements apply to your situation:
        You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
        You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
        You want to take advantage of multiple inheritance of type.

 packages

in Java are simply a mechanism used to organize classes and prevent class name collisions
Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.

Collection frameworh defiens several interfaces":

LIST Interface :estends collection and stores sequence of elements
Set
SortedSet


Collection classes:
Abstract Collection
Abstract List
LinkedList
array list
AHsh Set
Tree Set
Iterators
Map interface(keys to values)


jav.util.regex
Pattern Class
Matcher Class


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

File Handling :

http://www.tutorialspoint.com/java/java_files_io.htm


import unittest

class TestClassA(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassB(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassC(unittest.TestCase):
    def testOne(self):
        # test code
        pass

if __name__ == '__main__':
    test_classes_to_run = [TestClassA, TestClassC]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)





       
   

Wednesday, November 26, 2014

Essential Java Concepts

http://www.javatpoint.com/java-oops-concepts
Rules for Constructor
rule for static
Usage of this()

Sunday, November 16, 2014

Sorting algos in java

Queue implementation in Java

Stack implementation in java

Multithreading in JAVA


States of thread





 What is a context switch :each thread is assigned a priority
a thread with higher priority dosent mewan it will run any faster.
Priority is used ro decide when to switch from one thread to another
This is called Context switch.


A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.

• A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.


Regular expressions in java

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html


Generic Java function to match RE

public static boolean testRE (String s){
    Pattern pattern = Pattern.compile("\\d{3}");
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()){
      return true; 
    } 
    return false; 










[tT]rue - match true or true

[tT]rue|[yY]es - matches true,True,yes,Yes

*true.* - matches exactly true

[a-zA-Z]{3} - match 4 character word

^[^\\d] - true if String dosent match a digit at beggining

([\\w&&[^b]])* - true if string contains characters excluding b

"[^0-9]*[12]?[0-9]{1,2}[^0-9]*" - less than 300 (HOW????)

.*(jim|joe).* - Match either jim or Joe

A phone number in this example consists either out of 7 numbers in a row or out of 3 number, a (white)space or a dash and then 4 numbers. 

\\d\\d\\d([,\\s])?\\d\\d\\d\\d - 1233323322

[0-9]{2} (Check Correctness) -check if a text contains a number with 3 digits.
\\d{3} 

\b(\w+)\s+\1\b  - find duplicated words

 following regular expression allows you to find the "title" word, in case it starts in a new line, potentially with leading spaces.

(\n\s*)title 


Password compexity :


((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})


(   # Start of group
  (?=.*\d)  #   must contains one digit from 0-9
  (?=.*[a-z])  #   must contains one lowercase characters
  (?=.*[A-Z])  #   must contains one uppercase characters
  (?=.*[@#$%])  #   must contains one special symbols in the list "@#$%"
              .  #     match anything with previous condition checking
                {6,20} #        length at least 6 characters and maximum of 20 
)   # End of group



^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

   #start of the line
  [_A-Za-z0-9-]+ #  must start with string in the bracket [ ], must contains one or more (+)
  (   #  start of group #1
    \\.[_A-Za-z0-9-]+ #     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*   #  end of group #1, this group is optional (*)
    @   #     must contains a "@" symbol
     [A-Za-z0-9]+       #        follow by string in the bracket [ ], must contains one or more (+)
      (   #    start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #      follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*  #    end of group #2, this group is optional (*)
      (   #    start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #      follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )   #    end of group #3
$   #end of the line


([^\s]+(\.(?i)(jpg|png|gif|bmp))$

Image file extension

(   #Start of the group #1
 [^\s]+   #  must contains one or more anything (except white space)
       (  #    start of the group #2
         \.  # follow by a dot "."
         (?i)  # ignore the case sensitive checking
             (  #   start of the group #3
              jpg #     contains characters "jpg"
              |  #     ..or
              png #     contains characters "png"
              |  #     ..or
              gif #     contains characters "gif"
              |  #     ..or
              bmp #     contains characters "bmp"
             )  #   end of the group #3
       )  #     end of the group #2 
  $   #  end of the string
)   #end of the group #



IP address
^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$


^  #start of the line
 (  #  start of group #1
   [01]?\\d\\d? #    Can be one or two digits. If three digits appear, it must start either 0 or 1
  #    e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
    |  #    ...or
   2[0-4]\\d #    start with 2, follow by 0-4 and end with any digit (2[0-4][0-9]) 
    |           #    ...or
   25[0-5]      #    start with 2, follow by 5 and end with 0-5 (25[0-5]) 
 )  #  end of group #2
  \.            #  follow by a dot "."
....            # repeat with 3 time (3x)
$  #end of the line


12 hr TIME format 
(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)


(    #start of group #1
 1[012]    #  start with 10, 11, 12
 |    #  or
 [1-9]    #  start with 1,2,...9
)    #end of group #1
 :    #    follow by a semi colon (:)
  [0-5][0-9]   #   follow by 0..5 and 0..9, which means 00 to 59
            (\\s)?  #        follow by a white space (optional)
                  (?i)  #          next checking is case insensitive
                      (am|pm) #            follow by am or pm


24hr time format

([01]?[0-9]|2[0-3]):[0-5][0-9]

(    #start of group #1
 [01]?[0-9]   #  start with 0-9,1-9,00-09,10-19
 |    #  or
 2[0-3]    #  start with 20-23
)    #end of group #1
 :    #  follow by a semi colon (:)
  [0-5][0-9]   #    follow by 0..5 and 0..9, which means 00 to 

dat format dd/mm/yyyy

(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)

   #start of group #1
 0?[1-9]  #  01-09 or 1-9
 |                   #  ..or
 [12][0-9]  #  10-19 or 20-29
 |   #  ..or
 3[01]   #  30, 31
)    #end of group #1
  /   #  follow by a "/"
   (   #    start of group #2
    0?[1-9]  # 01-09 or 1-9
    |   # ..or
    1[012]  # 10,11,12
    )   #    end of group #2
     /   # follow by a "/"
      (   #   start of group #3
       (19|20)\\d\\d #     19[0-9][0-9] or 20[0-9][0-9]
       )  #   end of group #3





html regular exprerssion

<("[^"]*"|'[^']*'|[^'">])*>

<    #start with opening tag "<"
 (  #   start of group #1
   "[^"]*" # only two double quotes are allow - "string"
   |  # ..or
   '[^']*' # only two single quotes are allow - 'string'
   |  # ..or
   [^'">] # cant contains one single quotes, double quotes and ">"
 )  #   end of group #1
 *  # 0 or more
>  #end with closing tag ">"
For advanced regular expressions the java.util.regex.Pattern and java.util.regex.Matcher classes are used. You first create a Pattern object which defines the regular expression. This Pattern object allows you to create a Matcher object for a given string. This Matcher object then allows you to do regex operations on a String.