Java

 

 Java Basics

Robust and Reliable
Dynamic and Networking Support



-> Platform independent(Write Once and Run Anywhere i.e , can be used on any platform windows ,mac,android .. since after compiling code is coverted to byte-code).

-> Portable(we can take our byte code on any portable device such as pen drive or any storage and can run it on any platform)

->which ever object is taking space dynamically in the memory is taking space in HEAP and the reference that is being given to them is stored in STACK.
heap is such kind of memory area that it does not delete any memory allocation until developer is not writing any code for it. So if any reference of object is made null in stack so now that object is garbage in heap so in java we have concept of GARBAGE COLLECTOR (it is a thread) it runs in background it keeps on checking for this kind of any garbage in heap memory so as the garbage is found garbage collector removes all the resources allocated to it if any and frees up the memory and make it available to be used ,So if this doesn't there will be MEMORY LEAK in heap so we will not get enough space since those object will be taking place which are not pointed to any reference .

Here the reference stored in 's' i.e 02X is stored in stack
While the actual data is stored in heap.



->Object created using new operator is used to allocate us memory dynamically in heap memory. 

NullPointerException comes when reference is pointing to nothing in the heap



Virus free since virus is .exe or attacks on .exe file but in java we have .java or .class file so its virus free


-> In public static void main(String args[])
    args are command line arguments which are passed while we execute a program


-> In System.out.println("hello world")
    out is static reference variable of Printstreamtype in System class and println is the method in it. 


->

->  when java source code is compiled it converts file from .java(source code) to .class (byte code) 
if there are 'n' classes present in your java program 'n' number of bytecode files will get created. 

>  bytecode is platform independent 
>  jvm and jre (used for running bytecode) is platform dependent since it is present in jdk.


>  The text storing standard we use in C/C++ is ASCII code but in java we store using UNICODE .





> SCANNER class present in java.util package used to read the values from given source.
    given source here can be -> keyboard(user)/network/file... etc.

>PACKAGES are set of classes.



> javap is a command which you can use in command promt to see the members (constructors , methods .. etc) of a class in particular package. 
    Ex javap java.util.Scanner




> in JAVA java.lang package consist of some basic classes that we need in a program so it is imported by default in our program we don't need to import it externally. Ex System class..



same as cin>> in C++
we can use scanner class methods for taking input from user 


>only 1 public class should be there per java program and that program will have same name as that public class.


> STATIC members of a class are accessed by there class name and also by object of the class.
    Ex Math class in java.lang package   ->   Math.pow(2,3);     Math.sqrt(4);
    Similarly in System.out out is static member of System class.

    So if we don't want to write class name again and again we can import that class static so we can
    directly use static members as in example below 





>A static class can contain only the static members while a non-static class can contain static members


>non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.


>STATIC initializer it is a block which is labeled as static ,it is used to initialize static variables,we can not access non static member from static block.

>Static data member ,Static initializer is the first one to be called even before loading of the class.

>Since static variable takes it space in memory even before creation of object so it has common value for all the objects of a class, because it is stored only once so same value is shared among all objects.


> Access Specifiers :

    1. Private 
  • Accessible only in that class
    2. Default 
  • Accessible anywhere (in any class) in same package.
    3. Protected
  • Accessible anywhere (in any class) in same package and can also be accessed in  child class of different package.
           But u will still wont be able to access it by parent class object u will have to create object of                   child class which will access protected member of parent class. Ex below diagram




                In above diagram put() is the protected method present in parent class but we are accessing it                 by object of child class i.e the current class.



    4. Public
  • Everywhere








 
We use .  for accessing data member of a class. Ex->  this.dataMember
We can also use parentheses to call constructor from a constructor of current class. Ex -> this();








>When u create a java class with private properties with camel-case naming convention with getters and setters then this class is called BEAN.

>Constructor of a class can be private but it can be accessed only within the class.
    i.e its object can't be created outside that class.
    Benefit of this is only the one who have authority to access that class can only create its object.


so the object can be created as show above.


and called by class name.



>ARRAY in java are supposed to take space in memory at run time.
>java has many methods of searching ,sorting ,.. and many more in Array class.


> INHERITANCE 

 


>In java multiple inheritance is not allowed (for multiple inheritance we use interface concept).

>multilevel , hierarchal are allowed.






> whenever object of child class is created firstly parent class constructor is called before calling child class constructor by default.

>super( argumentsOfParentConstructor ); this is called in child constructor to invoke parameterized constructor of parent class while creating object.
    super(); should always be the first statement in child constructor.
    same is for this();


>Static method of parent class is also inherited and accessed by child class .


> POLYMORPHISM 




> METHOD OVERIDING




    In overriding we can not reduce the level visibility that is if in parent class method access specifier is     public then in child it can not be changed to private /default /protected in child class.
    And so on............
    We can increase the level from  private to public/protected/default ..

            Levels from least visible to most visible 
                                                            (PRIVATE -> DEFAULT -> PROTECTED -> PUBLIC)

here we can use super keyword in child class overriding method to access parent class overridden method.
Ex : super.Sound(); in lion class this will call cat class sound method.









>Relationships in java

IS-A is for inheritance

HAS - A is for Aggregation(other Exmple: person has a address)





 

>Object Class in Java




by default compiler inherits Object class to any class that u create.


>Object class has many methods which we can use basic this like getClass, hashCode , equals, and many more .

>we have to override toString() method as per our requirement for output bydefault it will give the hashcode of object .



>EQUALS method returns true when both objects references are same .

here both 1 and 2 will return false ,Since both are checking the reference of the object but they found it to be different.
So here we can override .equals() method in student class as shown below
along with equal it is mandatory to override hashcode also.






>Similarly for equals method we can override as per requirement.





>FINAL - means there can be no further changes made .
        variable ,methods and class can be final.

        ->variable it remains constant i.e value cant be changed. 
        ->methods cant be overriden
        ->classes cant be inherited.
    coz by this only there will be changes in them so all are prohibited.

> final variable should be initialized either while creation or in constructor .

in case u want variable to be fixed as well as unique for each object, it can be done with help of parameterized constructor.


>CLONE - clone() method of Object class create copy of object with different space in memory. 
                    i.e different reference ,different hashcode ....

Overriding clone object for employee class.




> In SHALLOW COPY - changes are not reflected i.e they take different space in memory. Clone makes shallow copy for normal object.

> In DEEP COPY - changes are reflected in copied object . Clone makes deep copy for Collection object.

>finalize() method of Object class is executed while garbage collection is performed or we can say when the object has no reference.

>System.gc() brings garbage collector forcefully in our program.
>Runtime.getRuntime().gc() is also used for collecting garbage in program.



> ABSTRACT class
  • can't be instantiated i.e we cant create its object.
  • abstract class may or may not have abstract method.
  • can have non abstract method too but since we cant instantiate it we can access abstract method from child class.
  • Abstract class can have constructor.
  • We can create array of abstract type coz here the array of refrence is created not the object ,So it can be used for storing child class object of abstract class.
we need to provide body to abstract method after inheritance.


    











>InstanceOf is used to check class .i.e it will return true in case the object is some how connected to the class i.e parent or child.


    Mainly used if many child class is inherited from same parent so to check which class it belongs to because we can have same parent reference variable for all the child classes.
                As in diagram below

 




subclass1 will return true for instanceof for  subclass1 and superclass
subclass2 will return true for instanceof for  subclass2 and superclass
subclass3 will return true for instanceof for  subclass3 and superclass 





 



will return false.
will return true only in case of -> s1 instanceof Student
                                                 -> s1 instanceof Person
            




>INTERFACE 

Interface can inherit interface.












>Difference b/w Interface and Abstraction(Abstract class)
  • In interface we can have multiple inheritance but not in abstract class.



>COUPLING and COHESION

>COUPLING 
    When you have 2 or more class are in picture.
    Dependency from outside class- Making changes in one class will make change in other class (Ex tight coupling ,loose coupling)

>COHESION
    When you have only 1 class is in picture.
    Dependency within a class - Making changes in one functionality of class you should make changes in other functionalities too since they are dependent on each other.

>So it is said that our code should be high cohesive and less coupled.

> SOLID DESIGN PRINCIPLES




 1 . Single Responsibility Principle.




2. Open-Closed Principle



But this is not the best practice coz for adding an extension here we are modifying the class

So as given below we should override vehicleNumber() method for each class. Instead of defining it all together in same class.





3. Liskov Substitution Principle
 



4. Interface Segregation Principle






5. Dependency Inversion Principle



















>JAVA 8 Features


                                                        For INTERFACE

1 ->from JAVA 8 Interface can have default body to it as if the implemented class is not overriding the method in interface so it will not give any error.
    It is done by providing default keyword before function returntype.
    By this all implemented class will have choice weather to use default method or override it.







2 ->If u want to bound a method to an interface only so that no implemented class can override it u can     use static keyword in place of default so now u can override it but it will be accessed only by interface     not by implemented class object.
Since set is made static it is bound for interface only.





3 -> Functional Interface - If a interface is made of one and only one ABSTRACT method then it is said         functional interface.



    java also gave annotation @FunctionalInterface if using it compiler will show error on adding more        then one abstract method to interface.

    But default and static methods can be added that will not give any error.

means functional interface says that u can have as many default and static methods as u want but it should have one abstract method.



Above image can be Avoided for now.

> Anonymous class in java - are class without name.

>LAMBDA EXPRESSIONS used for shortening the code, in java they are used with functional interface only



Parameter type can also be removed while calling





Above ex: If there is single parameter only


>Method Reference






This is called method referencing o/p here will be 10
Since somewhere in library println() (i.e return type and parameter) method is having same signature as for sum()








 Should have same signature (i.e return type and parameter)
here since sum() and get() have same signature








Similarly for parameter method referencing it can be done.

is for commented part (str1.indexOf(str2)) in above diagram.


> Instance method reference
    





> Constructor referencing 












>Java time API









>Functional Programming - 


> STREAM API- internally lambdas are used and all the collection api's are modified in java 8.
        basically used to perform any single functionality on each and every element of collection (Ex             List).
    Also stream does not modify the collection it makes the changes of modifications to the stream only.







Stream cannot be reused 





Here in filter the stream will/can be of new size since we will be eliminating some data , but in map the size will remain same since the data is being transformed.




used for transforming the data in stream.


also having getter setter and parameterized constructor for Employee class.















Final class means it can not be inherited to any class.
Reduction operation means aggregating elements to single element.
Ex mean ,average of integers, sum ,min ,max ,grouping .. etc
Accumulating means u have stream type u can collect/store it to any other type(List ,Map ,Set .. etc)
this will return sum of all salaries.








> Exception Handling : 
    





Java detects the exception automatically but does not handle it automatically so the program terminated abnormally ,without executing's further.
java.lang package has all exception classes in it.
So in which ever line exception occurs java starts searching for its class in java.lang package as the exception is found jvm creates object of that exception class and throws it to the program if it is catched then ok else the thrown object goes to console and program ends abnormally. 



















If there are multiple catch block never put general exception catch block on top because the catch block below it will be unreachable.














Ans: checked exception only, because by default the are not propagated to calling environment .









here will need custom exception for age.


can be extended from Throwable Class also or Exception Class or RuntimeException Class any of them in exception tree, and respectively its throw will show exception in the same way.






> In C++ we had different approach for different inputs and outputs ex : file, keyboard, network ,mobile     etc.


Diff  I/P                                                                 Diff O/P

>So it is drawback in C++.

> So overcome this drawback JAVA uses streams .





Having suffix as Reader ,writer are Character stream
Having suffix as InputStream , OutputStream are Byte stream

InputStream , OutputStream are abstract and super class for all byte stream
Reader ,writer are abstract and super class for all Character stream

> System.in is a byte stream (InputStream) , and the only stream used to take data from keyboard.

here since we used .read() only once so it gave ASCII value for A only i.e 65



Printing ASCII code for Arun i.e 65,114,117,110
and for enter key 13 and for (\n) next line10 


InputStreamReader used to bound character stream and byte stream together it takes data in byte stream and returns it in char stream.




1 . since stream type so need to convert byte to char by typecasting
2. with help of InputStreamReader bounded byte stream to char stream hence taking input was easy here.


here we are using (Parameterized) try catch to handle exception ,we have seen above benefits of parameterized try catch.













write byte value of string in external file using fileOutputStream.

here we create A.txt and wrote Hello in it using FileOutputStream




writing into file using filewriter here we didn't need to convert string to its byte.
also appending data here instead of replacing to previous data in file.


reading data from file.
here used InputStreamReader since input was as byte stream and we are using bufferedReader that is char stream.

reading data from file using fileReader.








> Serialization  : writing object into a file.


will need to implement marker interface i.e serializable here


object is written in encrypted format.






Similarly example for object deserialization i.e to read the file for object.


> Transient keyword in Serialization - this we use if we don't want to write a value in a file in an object.










> Similarly as transient , static members are also not serializable . 
    but if this is the case then why we used transient not static.


> if there is is-A relationship (inheritence) then if parent is serializable i.e it implements serializable then child class is automatically serializable.

> but if there is has-A relationship (aggregation) then if parent is serializable i.e it implements serializable then aggregated class is also needed to be made serializable separately.


> Serial Version UID









> COLLECTIONS in java: Collection is a framework which provides u the environment to create and manipulate different types of collections.






    


    Benefits of collections over arrays:
  • Variable size
  • Linear/ Non Linear Data Structure    
  • Easy Insertion and deletion of elements.
  • Heterogeneous elements are also allowed.


> Arraylist









> Vectors : are thread safe were as arrays are not








in both case arraylist and vector the default size provided is 10.

we can also use addElement instead of element in vectors. 


> Linked List 






for fetching data from collection.
In enhanced for loop we r taking temp as object type variable because data in collection is being stored as object only not as primitive datatype i.e integer or string ....

In case of vector we can access elements using Enumeration too.


> SETS
Will output randomly in hashset


output in same order


> Here in below example in case of object Hashset will have duplicate values in output since they are object and have different reference in memory so equals() will return false for them.
Even if the values are same.
since equals() and hashcode() are used to compare equality of hashset.






So here to overcome this we will need to override equals() and hashcode().







> for sorting hashset we need to first make it to List type since collections class have sort() for just list type only.
Similarly for Comparator interface we will need to convert hashset to list (Explained in Comparator example below).

and will need to override compareTo method from comparable class as shown below in tree set (Last).




In case of treeSet will get exception since data is not comparable tree set stores data in sorted order but the data here are of different types.
and this comparison is made at the time of insertion.
Also we can't have null values in tree set.



> COMPARABLE Interface :
    we need to override compareTo to compare data in object type in every collections .

    Ex List, Set .. etc

Below is the example for TreeSet

> now for sorting treeset with object type values other then primitive type we use sort() but how will it compare data in object type?
    So it is done by : compareTo() method of Comparable interface .
    
    compareTo returns int value :  
  • positive if first element is greater then second. (+1)
  • negative if first element is smaller then second. (-1)
  • 0 if first element is equal to second. (0)
    



now here we see the 1 compareTo() is the method of comparable interface .
but the 2 compareTo() is from String class since in this example we are sorting on the basis of employee name so.
compareTo() of string also returns same + for first greater then second ,- for first less then second, 0 for equals.
if here we had to compare/sort on the basis of empId then we would have simply written condition as:
  • negative if first element empId is greater then second. (-1)
  • positive if first element empId is smaller then second. (+1)
  • 0 if first element empId is equal to second. (0)



> COMPARATOR interface :


here we implement Comparator class in different class and override compare for any/all members for which want to make comparison while sorting.

here we are comparing on the basis of emloyeeId of employee class object.


here overriding on the basis of empName.



so in above ex we are comparing and sorting on the base of empId.



so in above ex we are comparing and sorting on the base of empName.
same can be done using lambda function by making it sort() attribute as per requirement name or id.




> Similary Comparator for hashset

so in above example we are comparing and sorting on the basis of empName  so second parameter in sort is for comparator interface method.



> Map  : it is not in collection map hierarchy . So it will have different methods for manipulating data. 












linked hashmap giving output in same order.



Sorted data according to the keys.




> Hash Table







> AUTOBOXING and UNBOXING-

 AUTOBOXING: In collection converting of primitive type to its reference type is autoboxing because it happens automatically.


UNBOXING : converting it back to primitive type manually.
by both ways unboxing can be done.


> Wrapper classes -




>  GENERICS :  used to assign a type to object of collection so the value other then specified type can't be inserted.
If done error will be shown only at compile time (CTE : Compile time error)




> Type Erasure : concept tells that when we give a generic type to collection in source code it checks for the error at compile time only , so in the byte code there is no generic type defined i.e it is erased. since we have removed all type errors at compile time only.
















creating generic method







creating generic method in ordinary class.




here Manager is child of Employee.
So
  • Left side its shown Manager extends Employee.
  • and Employee itself extends Employee
Similarly
  • Right side Employee is super to itself
  • And Object class is super to all class 


  • Contravariant
  • Covariant

so as per above diagram Object is not extending from A so it is giving error else all are its child so we can create their object, these are Covariant.



so as per above diagram Object is super of A and A as well , So they are Contravarient.




here in derived class we are taking generic type T just to call the base constructor of generic type.

in this case we can remove generic type angular brackets from derived class since here we have declare the base type will be string only.








? is for wildcard i.e T(object class variable) here.
  • derived class object is instance of base
  • derived class object is instance of derived
  • base class object is instance of base
but base class object is not instance of derived and also at compile time compiler doesn't know the Object is of Integer type so it will give error as shown in last scenario.








> MULTITHREADING - 




Process is a program/software used to perform multiple tasks.


Multiprocessing and multithreading both are used to achive multitasking .
In a nut shell.......
  • threads use shared memory area 
  • threads = faster content switching 
  • thread is light-weight where a process is heavyweight 

   for example = A word processor can have one thread running in foreground as an editor and another in the background auto saving the document ! 

    Flow of control in java 

    • Without  threading :


    • With threading : 



    > In below example code we have created 2 thread using both class and interface and a main thread


    //creating our thread using Runnable Interface
    class MyThread implements Runnable
    {
    public void run()
    {
    //task for thread...
    for(int i=1;i<=10;i++){

    System.out.println("value of i is "+i);
    try{
    Thread.sleep(1000);
    }catch(Exception e){
    }
    }
    }

    public static void main(String[] args) {
    //create object of MyThread class
    MyThread t1=new MyThread();
    Thread thr=new Thread(t1);
    //object of AnotherThread
    MyAnotherThread t2=new MyAnotherThread();
    thr.start();
    t2.start();
    }
    }


    //Creating thread using Thread class
    class MyAnotherThread extends Thread
    {
    public void run()
    {
    //task for thread
    for(int i=10;i>=1;i--)
    {
    System.out.println("another thread = "+i);

    try
    {
    Thread.sleep(2000);
    }catch(Exception e)
    {

    }
    }
    }

    }

      Creating a Threading 

       There are two ways to create a thread in java 

    1. By extending thread class 
    2. By implementing Runnable interface

    By extending thread.
    Since there are 2 threads working in this program so as it is happening at the same time so we are getting output mixed of main class thread as well as counter class thread.

    Here start() is method inside thread class it starts run method for thread class So , c1.start() is for starting the counter class thread.

    Why we don't directly c1.run() because it will not act as thread internally it will simply be a method call and act in that way.

    And this sequence will be random each and every time we execute our code. 



    By implementing Runnable interface
    here as we have implemented runnable interface so for using thread methods we created instance of thread class and passing counter class object as parameter to thread constructor.

    So here we can see again different output sequence and also the End of main statement is coming even before counter class thread has ended.





    As in java when we call getState() for thread it displays only 4 state :
    • new 
    • runnable
    • non - runnable
    • terminated
    Running is here for our understanding



    here by th1.getState() we can see in which state th1 thread is at that point of execution.
    And,
    when join () is used i.e th1.join() it will execute that thread till end as of now before any other thread in our program no other parallel activity will happen for that time .
    So, 
    the sysout statement after join() will show show state as terminated since thread is fully executed at this point 


    here by Thread.currentThread() we get the instance of current thread for which this run has started and getstate() is forgetting its state.
    Also,
    Thread.sleep() brings thread to blocked/NonRunnable state for mentioned milliseconds of duration.








    here the o/p will be MyMain since name is now changed



    here at a time producer can produce only one item till and till the time it is not consumed producer should not produce other item.
    So,
     it is done since both are synchronized and the communication between both thread are called inter-thread communication by which they are communicating weather the item is produced/consumed or not. 
    So,
    we need synchronization ,thread safety in a case when we have common resource to share for different threads.
    But we don't use synchronization until its needed because it slows down the process.

    > Code for above example is given below
        
        Comapany.java

        class Company
    {
    int n;
    boolean f=false;
    // f=false: chance: producer
    //f=true: chance :consumer
    synchronized public void produce_item(int n)throws Exception
    {
    if(f)
    {
    wait();
    }
    this.n=n;
    System.out.println("Produced : "+this.n);
    f=true;
    notify();
    }

    synchronized public int consume_item()throws Exception
    {
    if(!f)
    {
    wait();
    }
    System.out.println("Consumed : "+this.n);
    f=false;
    notify();
    return this.n;
    }
    }


        Producer.java

            class Producer extends Thread
    {

    Company c;
    Producer(Company c)
    {
    this.c=c;
    }
    public void run()
    int i=1;
    while(true)
    {
    this.c.produce_item(i);
    try{Thread.sleep(1000);}catch(Exception e){}
    i++;
    }
    }
    }

        Consumer.java

        class Consumer extends Thread{
    Company c;
    Consumer(Company c)
    {
    this.c=c;
    }

    public void run()
    {
    while(true)
    {
    this.c.consume_item();
    try{Thread.sleep(2000);}catch(Exception e){}
    }
    }
    }


        Main.java

        class Main
    {
    public static void main(String[] args) {
    Company comp=new Company();
    Producer p=new Producer(comp);
    Consumer c=new Consumer(comp);
    p.start();
    c.start();

    }
    }




    > wait(),notify and notifyAll() are the methods present in Object class.

        wait can act both as sleep (with parameter ex : wait(1000)) and suspend (without parameter ex wait())

    > So why we need wait(),notify and notifyAll()  if we have sleep(),suspend() and resume()
        because if a object is being used by multiple threads at a time then if we make that object to wait() state then it will not come to runnable state until any other thread (i.e inside other threads run method) is brining it to notify() state. 




    > Another Example on synchronize:
    • we can either make method synchronized
    • we can make block synchronized.    (Used when we want some satement of process to be synchronized)

    method synchronized example




    block synchronized example
    made statement synchronized in thread instead of method making synchronize else everything same.



    > 1 java thread  = 1 Operating System thread 
        So in quadcore processor there are 4 core i.e 4 threads So only 4 thread will be used from pool not whole 10.
        So, creating 'n' number of threads will make difficult to run the process that's why we got introduced with concept of THREAD POOL.

    so here we have to perform 1000 task so instead of creating 1000 thread we create a pool of 10 thread and assign each thread a task from queue of tasks whenever thread is free i.e completed the old job.




    here in variable n we are getting numbers of core in our system at runtime i.e 8 for octacore here
    implementation of above diagram ,created pool of 'n' threads and 50 task so each thread will take 'n' task iff time taken for processing is same for each thread.






    > 4 types of thread pools are there :



    1.  Fixed thread pool



    2.  Cached Thread pool : here we don't have fixed number of thread nor the queue that will hold all tasks.
    here pool hold only one task at a time




    3. Scheduled thread pool :




    4. Single Threaded executer:

    Its code will be same as fixed thread pool with size 1.



    > We have methods to shutdown the thread pool.
    1. service.shutdown() initiates shutdown - so it initiates shutdown but waits for currently running tasks and task in queue to get completed.
    2. service.shutdownNow() here it waits for the tasks that are currently being executed and returns the task that are pending in the queue.

    > there are some more methods here :
    • isShutdown() : it returns true even when the shutdown is initiated but not finished completely.
    • isTerminated() : it returns true only in the case of the shutdown has completely happened.


    > Callable v/s Runnable








    Comments

    Popular posts from this blog

    Durgesh - Exam Portal Project using Spring Boot and Angular