Saturday, July 11, 2015

Explain "final" keyword

final is a keyword in java which is used as a modifier for variables, methods and classes.
Final variables cannot be reassigned values. Once given, the value of a final variable cannot be changed. For final instance variables, you may assign value then and there, or in the constructor once. For final local variables within methods, value must be assigned before using the variable. The value cannot be changed for final variable. Final and static when used together with variables, define a constant in java. static means single copy and final means value cannot change. - Show simple example.
Final methods cannot be overridden. The subclass cannot redefine the method if superclass declares the method to be final. – Show simple example.

Final classes cannot be extended. Subclasses cannot be created for a final class. So a final class is typically a leaf class in the class heirarcgy – Show simple example

Explain "static" keyword

a.       static is a keyword in java which is used as a modifier for variables and methods within a class. static means something which belongs to the class and not to every object. If a property is static, only 1 copy is maintained for that property per class. Separate copies are not created for every object. Similary static methods are also invoked on the class and not on objects. Since static methods are not invoked on objects, we cannot use “this” keyword within static methods. Syntax of using static variables and methods is

ClassName.variable= value  (or)  ClassName.method();

In java we also have a concept of a static block which is written within a class. A static block of code is executed when the class is initially loaded by the class loader of jvm.

How to declare static?
 class A{
      static int I;           // static variable
      static void m1(){
                                      // static method
}
      static{
                                      // static block
}
}
How to use?
A.i=5;                          // assigning value to static variable: ClassName.variable
A.m1();                       //invoking a static method: ClassName.method()
     

A static variable is often called as a class variable as it is a property of the class. A static method cannot use instance variables. It can use static variables only. Static variables are often used to count the number of objects created or to manage some global constant accessible from anywhere by using the class name. Also write a simple code to show use of static. 

Garbage Collection in Java

·         objects are created on heap area in Java  irrespective of their scope e.g. local or member variable.
·         Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
·         Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
·         Garbage collector works on Mark and Sweep algorithm and is lineant in its operation.
·         Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
(daemon=background)
·         Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
·         You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
·         There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
·         JVM supports many different implementations of Garbage collectors.. Many are bundled into J2SE also. An application may choose the GC according to the needs (In case of advance programming needs).
·         One thing is assured, that before the Garbage Collector reclaims and object and releases its memore, it will invoke the protected method finalize() on the object. This method is invoked only once on an object during its life time and that too at the end of life time.


Since Garbage Collection is automatic in Java, memory management errors get reduced in java which may occur in case of manual memory allocation and de-allocation. Allocation part is take care of by constructors in java and de-allocation by Garbage Collector, thereby automating the memory mgmt. in java completely.

JVM Understanding

à  Bytecode is a special machine language that can be understood by the Java Virtual Machine (JVM) independent of any particular computer hardware, so any computer with a Java interpreter can execute the compiled Java program, no matter what type of computer the program was compiled on. Java Virtual Machine (JVM) can now be understood

à All languages compiler translate source code into machine code for a specific computer. Java
compiler also does the same thing. Then how does java achieve architecture neutrality? The
answer is that the java compiler produces an intermediate code known as bytecode for a machine that physically does not exist, this so called virtual machine is known as the java virtual machine (JVM) & it exists only inside the computer memory. The machine language for the java virtual machine is called java bytecode.

à The process of compiling a java program into bytecode which is also referred to as virtual
machine code is not machine specific. The machine specific code generated by the java
interpreter by acting as intermediary between the virtual machine & the real machine as given in
following fig. the interpreter is different for different machine.

àJava bytecode can run on any computer that has an interpreter this is one of the essential features of java: the same compiled program can be run on many different types of computer but JVM must be installed.

àA Java Virtual Machine (JVM) is a set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. This language conceptually represents the instruction set of a stack-oriented, capability architecture. As of 2006, there are were estimated four billion JVM-enabled devices worldwide.

Overview of JVM:

àJava Virtual Machines operate on Java bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be used to implement programming languages other than Java. For example, a source code can be compiled to Java bytecode, which may then be executed by a JVM. JVMs can also be released by other companies besides Sun (the developer of Java) — JVMs using the "Java" trademark may be developed by other companies as long as they adhere to the JVM specification published by Sun (and related contractual obligations).

àThe JVM is a crucial component of the Java Platform. Because JVMs are available for many
hardware and software platforms, Java can be both middleware and a platform in its own right -
hence the trademark write once, run anywhere. The use of the same bytecode for all platforms
allows Java to be described as "compile once, run anywhere", as opposed to "write once,  compile anywhere", which describes cross-platform compiled languages. The JVM also enables such features as Automated Exception Handling that provides 'root-cause' debugging information for every software error (exception) independent of the source code.

àThe JVM is distributed along with a set of standard class libraries that implement the
Java API (Application Programming Interface). An application programming interface is what a
computer system, library or application provides in order to allow data exchange between them.
They are bundled together as the Java Runtime Environment.

Execution environment

Programs intended to run on a JVM must be compiled into a standardized portable binary format, which typically comes in the form of .class files. A program may consist of many classes in different files. For easier distribution of large programs, multiple class files may be packaged together in a .jar file (short for Java archive).

The JVM runtime executes .class or .jar files, emulating the JVM instruction set by interpreting it, or using a just-in-time compiler (JIT) such as Sun's Hotspot. JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed. Ahead-of-time compilers that enable the developer to precompile class files into native code for a particular platforms also exist.
Like most virtual machines, the Java Virtual Machine has a stack-based architecture akin to a

microcontroller/microprocessor. The JVM, which is the instance of the JRE (Java Runtime Environment), comes into action when a Java program is executed. When execution is complete, this instance is garbage-collected. JIT is the part of the JVM that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.

Calci Example

import java.util.*;
class Calci{
int add(int a, int b){
return a+b;
}
int sub(int a, int b){
return a-b;
}
int mult(int a, int b){
return a*b;
}
int div(int a, int b){
return a/b;
}
}
class TestCalci{
public static void main(String[] args){
Calci c = new Calci();


int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[2]);


switch(args[1]){
case "+":
System.out.println(c.add(num1, num2));
break;
case "-":

System.out.println(c.sub(num1, num2));
break;

case "x":

System.out.println(c.mult(num1, num2));
break;

case "/":

System.out.println(c.div(num1, num2));
break;

default:
}

System.out.println("Thanks");


}
}

Friday, July 3, 2015

Shape class with Rect and Circle as Subclasses and area calculation facility

class Shape{
double area;
int perimeter;

}
class Rect extends Shape{
int l;
int w;

Rect(int length , int w){
this.l = length;
this.w = w;
}
Rect(){
this.l = 0;
this.w= 0;
}

double getArea(){
return this.l * this.w;
}


}
class Circle extends Shape{
int radius;
Circle(int r){
this.radius = r;
}
Circle(){
this.radius = 0;
}
double getArea(){
return 3.1428 * this.radius* this.radius;
}
}
class TestShapes{
public static void main(String args[]){
Rect r1 = new Rect(5,5);
Circle c = new Circle(5);
double area = r1.getArea();
System.out.println("Area of R1 is: "+ area);
System.out.println("Area of c is: "+ c.getArea());
}
}






Account Class with overloaded constructors, deposit, withdraw and print facility

class Account{
int accountNo;
String holderName;
double balance;

Account(){
accountNo=0;
holderName="Unnamed";
balance=0;
}

Account(int accountNo, String h, double b){
this.accountNo = accountNo;
this.holderName = h;
this.balance = b;
}

Account(int accountNo, String h){
this.accountNo = accountNo;
this.holderName = h;
this.balance = 0;
}

void printDetails(){
System.out.println("\n\nInfo of Account:"+ this.accountNo);
System.out.println("----------------------");
System.out.println("Balance of "+ this.accountNo +" is " +this.balance);
System.out.println("Name of object is "+this.holderName);
System.out.println("No of object is "+this.accountNo);
}

void deposit(double amt){
if(amt>0){
this.balance +=  amt;
}
else{
System.out.println("Negative Amount cannot be deposited");
}
}
void withdraw(double amt){
if(amt <= this.balance){
this.balance -= amt;
}
else{
System.out.println("Insufficient balance. Cannot do withdrawal");
}
}
}
class TestAccount{
public static void main(String[] args){
int i = 6;
Account a1 = new Account();
Account a2 = new Account(1001, "Abcd");
Account a3 = new Account(1001, "Efgh", 200);

a2.deposit(100);
a2.withdraw(500);

a2.printDetails();

}
}