Thursday, November 14, 2013

JAVA Basics

System.out.println()

‘out’ is a static member variable belonging to the System class.

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut(). 

Thus out is  a static variable of system class of type PrintStream which is having a method println().

//the System class belongs to java.lang package
class System {
  public static final PrintStream out;
  //...
}

//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
} 

Java is platform independent

Every Java program is first compiled into an intermediate language called Java bytecode. The JVM is used primarily for 2 things: the first is to translate the bytecode into the machine language for a particular computer, and the second thing is to actually execute the corresponding machine-language instructions as well. The JVM and bytecode combined give Java its status as a "portable" language – this is because Java bytecode can be transferred from one machine to another.

But the JVM depends on the operating system – so if you are running Mac OS X you will have a different JVM than if you are running Windows or some other operating system. This fact can be verified by trying to download the JVM for your particular machine – when trying to download it, you will be given a list of JVM’s corresponding to different operating systems, and you will obviously pick whichever JVM is targeted for the operating system that you are running.

Method Overloading :-
Overloading in Java can occur when two or more methods in the same class share the same name or even if a child class shares a method with the same name as one of it’s parent classes but
1.) The number of parameters is different for the methods 
2.) The parameter types are different. 

But it is not overloading if :-
1. Changing the return type of the method 
2. Changing the name of the method parameters, but not changing the parameter types.

Method Overriding :- 
Overriding occurs when an overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.

Overriding is a runtime phenomenon whereas overloading is a compile time phenomenon.

Private Constructor :- 
  1. It is used to limit the access of the constructor to class only.The object of class can not be instantiated outside the class. Like in case of singleton design pattern.
  2. It is used to prevent the creation of any object of the class entirely. This is used when a class has only static members which can be accessed using only the class name 
Copy Constructor :-
  1. It is a constructor of a class that accepts only one parameter and even that parameter is of the type as the class.
    public class A{
              public A(A a){
                 System.out.println("This is a copy constructor");
              }
    }
  2. It is used to create an object identical to the original one and to prevent the original object being altered.
Final modifier:-
  1. If used before method, the method can not be overridden.
  2. If used before class, the class can not be subclassed.
  3. If used before a variable, the variable can not be changed.
package com.arsoft.tutorial.javabasics;
public final class FinalModifier {
    public static final int a = 50;
    public static void main(String args[]){
        //Compile time error that final variable can not be reassigned
        a = 50;
    }
}
//Compile time error that final class can not be extended
class FinalModifierA extends FinalModifier{
   
}
class FinalModifierB {
    public final String sayHi(){
        return "Hi";
    }
}
class FinalModifierC extends FinalModifierB{
    //Compile time error that final method can not be overridden
    public final String sayHi(){
        return "Hi Anshul";
    }
}

Finally block :-

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block.

It will be called in any of the below scenario's:-
  1. The try block runs without any exception
  2. An exception is caught in catch block
  3. An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception. In this scenario, the call to the method ends, and the exception object is thrown to the enclosing method - as in the method in which the try-catch-finally blocks reside. But, before the method ends, the finally block is executed. 
  4. Finally takes precedence over the return statement. Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block will still be executed even if there is a return statement somewhere in the try block.
It will not be called in below scenario's:-
  1. System.exit() is called.
  2. JVM crashes. 
If there is a return statement in finally block as well, the values returned in try or catch block will be overridden but this is a bad idea to return a value in finally block


Virtual Memory and Paging ;-
Real, or physical, memory exists on RAM chips inside the computer. Virtual memory, as its name suggests, doesn’t physically exist on a memory chip. It is an optimization technique and is implemented by the operating system in order to give an application program the impression that it has more memory than actually exists. Virtual memory is implemented by various operating systems such as Windows, Mac OS X, and Linux. Let’s say that an operating system needs 120 MB of memory in order to hold all the running programs, but there’s currently only 50 MB of available physical memory stored on the RAM chips. The operating system will then set up 120 MB of virtual memory, and will use a program called the virtual memory manager (VMM) to manage that 120 MB. The VMM will create a file on the hard disk that is 70 MB (120 – 50) in size to account for the extra memory that’s needed. The O.S. will now proceed to address memory as if there were actually 120 MB of real memory stored on the RAM, even though there’s really only 50 MB. So, to the O.S., it now appears as if the full 120 MB actually exists. It is the responsibility of the VMM to deal with the fact that there is only 50 MB of real memory. The VMM creates a file on the hard disk that holds the extra memory that is needed by the O.S., which in our case is 70 MB in size. This file is called a paging file (also known as a swap file), and plays an important role in virtual memory. The paging file combined with the RAM accounts for all of the memory. Whenever the O.S. needs a ‘block’ of memory that’s not in the real (RAM) memory, the VMM takes a block from the real memory that hasn’t been used recently, writes it to the paging file, and then reads the block of memory that the O.S. needs from the paging file. The VMM then takes the block of memory from the paging file, and moves it into the real memory – in place of the old block. This process is called swapping (also known as paging), and the blocks of memory that are swapped are called pages. The group of pages that currently exist in RAM, and that are dedicated to a specific process, is known as the working set for that process.


Memory Management in JAVA
All the objects in JAVA are stored in heap while all the references or variables are stored in stack.  The stack is for transient data objects (like variables in your methods). The heap is for things that have to persist awhile longer.

1. Heap and Nursery:- All JAVA objects reside on a heap. This heap is created when JVM is initialized.The heap is divided into two parts
  • Young space where the new and short lived objects reside
  • Old space where long living objects reside
Young collection removes the garbage from Young space swiftly and promotes the long living objects to old space while old collection removes garbage from old space only after it is full.

Large Objects (size >2kb) are allocated directly on heap while the small objects are allocated in thread local areas (TLAs)

Any java objects needs
  1. 12 bytes for object header
  2. 8 bytes for boundary
  3. rest depends on the datatype of member variables
    1. byte, booleans          1 byte
    2. short, char                2 bytes
    3. int, float                   4 bytes
    4. long, double             8 bytes
 Any java reference variables needs
  1.  4 bytes if heap is under 32G 
  2. 8 bytes ig heap is more 
Difference between == and equals:-
“==” tests if references are equal and equals() tests if values are equal

char[] is preferred over String for security sensitive information:-
Because String is immutable and will be present in heap until garbage collection kicks in.
Volatile is used to indicate that a variable's value will be modified by different threads.

static class : A class can be static only if it is declared inside another class. In this case we can use the nested class without having an instance of the outer class.

E.g.
class OuterClass{
    public static class StaticNestedClass{
    }
} 

Types of JAVA classes
  • Top-level classes
  • Inner classes

Top Level classes
A normal java class is a top level class

Inner classes
A class defined inside a top level class is called inner class. They are of below types
  • Anonymous class
  • Local class
  • Member class
    • Static
    • Non static

Anonymous class
Classes that are declared and instantiated within the same statement. They do not have names, and they can be instantiated only once. They can not be static

E.g.
    okButton.addActionListener( new ActionListener(){
       public void actionPerformed(ActionEvent e){
          dispose();
       }
    });

Local Class
Classes that are created and used inside a block. They can not be static

E.g.
    //some code block .......{
       class ListListener implements ItemListener {
          List list;
          public ListListener(List l) {
         list = l;
          }
          public void itemStateChanged(ItemEvent e) {
         String s = l.getItemSelected();
         doSomething(s);
          }
       }
       List list1 = new List();
       list list2 = new List();
       list1.addItemListener(new ListListener(list1));
       list2.addItemListener(new ListListener(list2));
    }

Member
Classes that are defined within the body of a class.
The member class is the only class that you can declare static or non static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared
To initialize a static inner class we can use
             StaticInnerClass sic = new StaticInnerClass ();
but to initilaize a non static inner class we will need an instance of OuterClasse
             OuterClass oc = new OuterClass();
             NonStaticInnerClass nsic = oc.new NonStaticInnerClass();
A static member class is also called Nested top-level class

Default Initial Values
boolean                                              false
byte                                                    (byte) 0
short                                                   (short) 0
int                                                       0
long                                                    0L
char                                                    \u0000
float                                                    0.0f
double                                                0.0d
object reference                                 null

PS:- Each variable value is initialized twice, first time to the default initial value and then to the given value.

Features of Constructors: 
  • They are used to initialize the variables of class
  • They can have parameters but no return type
  • The public, private and protected access levels can not be inherited by subclass. The access level only determines the ability to initialize object
  • It is always used with new operator
  • A class can have any number of overloaded constructor
  • A class can have no-argument constructor
  • A constuctor of a class can be called from another constuctor of the same class using this() and it should be first statement in the constructor
  • It has always the name as that of class
  • Every class which is having no class constructor, has a default no argument constructor which is initialized by JVM. So every class in indeed has at least one constructor.






Differences between JDK6 and JDK 7:-

1. substring():- In case of jdk6




No comments:

Post a Comment

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...