Monday, 30 December 2013

JIT (Just In Time) Compiler

The Just-In-Time (JIT) compiler is a component of the Java™ Runtime Environment. It improves the performance of Java applications by compiling bytecodes to native machine code at run time.
Java programs consists of classes, which contain platform-neutral bytecodes that can be interpreted by a JVM on many different computer architectures. At run time, the JVM loads the class files, determines the semantics of each individual bytecode, and performs the appropriate computation. The additional processor and memory usage during interpretation means that a Java application performs more slowly than a native application. The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time.
The JIT compiler is enabled by default, and is activated when a Java method is called. The JIT compiler compiles the bytecodes of that method into native machine code, compiling it "just in time" to run. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it. Theoretically, if compilation did not require processor time and memory usage, compiling every method could allow the speed of the Java program to approach that of a native application.
JIT compilation does require processor time and memory usage. When the JVM first starts up, thousands of methods are called. Compiling all of these methods can significantly affect startup time, even if the program eventually achieves very good peak performance.

Demo of Date class program

public class Date {

int dd,mm,yy;
void display(int a,int b,int c)
{
dd=a;
mm=b;
yy=c;
System.out.println("Date is:"+dd +"/"+mm +"/"+yy);
}
public static void main(String[] args) {
Date dt=new Date();
dt.display(30,12,2013);
}

}
Output: Date is:30/12/2013





Sunday, 29 December 2013

How to run java file on dos

1.       Create a text document, write your code in it and save it as “.java” file.


2.       To compile the java file go to dos prompt. Go to Run and type cmd click ok.

3.       Go to the directory where file is saved.


4.       Set path of java compiler so that dos prompt will find it.
4.1. Go to computer right click and click on properties

4.2.  Click advanced settings   

4.3. Click environment variables       
                   
4.4.  Edit path and at the end of the path put a semicolon(;) and write path of your jdk bin after semi colon and click ok 
                 path of your jdk
 
               put a semi colon and copy that path in system variable value 

If path is not set dos will not be able to find the java compiler and will get a message. 


5.       Once the path is set run your java file using the command- javac filename.java 


6.       Your file is compiled and  .class file is created which is platform independent. 

7.       Now you can see the output of your file using the command- java classname. 


 While compiling your file compile your .java file and when you run your file run it with the classname without extensions, eg. java Helloworld 

Features of Java

There is given many features of java. They are also called java buzzwords.

1.Simple:
syntax is based on C++ (so easier for programmers to learn it after C++).
2.Object-oriented:
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing some rules.
Basic concepts of OOPs are:
  1. Object
  2. Class
  3. Inheritance
  4. Polymorphism
  5. Abstraction
  6. Encapsulation
3.Platform independent:
The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:
  1. Runtime Environment
  2. API(Application Programming Interface)
4.Secured:
Java is secured because:
  • No explicit pointer
  • Programs run inside virtual machine sandbox.
5.Robust:
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
6.Architecture neutral:
There is no implementation dependent features e.g. size of primitive types is set.
7.Portable:
We may carry the java bytecode to any platform.
8.High Performance:
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++).
9.Distributed:
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
10.Multithreaded:
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multi-media, Web applications etc.

History Of Java

Java  was designed by  sun microsystems in early 1990s. Crater of java james gosling. Java was publicly released on May 27, 1995.

JDK Alpha and Beta (1995)

-Alpha and Beta Java public releases had highly unstable APIs and ABIs. The supplied Java web browser was named WebRunner.

JDK 1.0 (January 23, 1996)

-Codename Oak.
-The first stable version was the JDK 1.0.2. is called Java 1.

JDK 1.1 (February 19, 1997)

-Major additions included:
an extensive retooling of the AWT event model
inner classes added to the language
JavaBeans
JDBC
RMI
reflection which supported Introspection only, no modification at runtime was possible.
JIT(Just In Time) compiler on Microsoft Windows platforms, produced for JavaSoft by Symantec.

J2SE 1.2 (December 8, 1998)

-Codename Playground.

This was a very significant release of Java as it tripled the size of the Java platform to 1520 classes in 59 packages. Major additions included:

-strictfp keyword
-the Swing graphical API was integrated into the core classes
-Sun's JVM was equipped with a JIT compiler for the first time
-Java plug-in
-Java IDL, an IDL implementation for CORBA interoperability
-Collections framework


J2SE 1.3 (May 8, 2000)

-Codename Kestrel.

Major additions included:

-HotSpot JVM included (the HotSpot JVM was first released in April 1999 for the J2SE 1.2 JVM)
-RMI was modified to support optional compatibility with CORBA
-Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension)
-Java Platform Debugger Architecture (JPDA)
-JavaSound
-Synthetic proxy classes

J2SE 1.4 (February 6, 2002)

-Codename Merlin

Language changes
-assert keyword (Specified in JSR 41.)

Library improvements
-exception chaining allows an exception to encapsulate original lower-level exception
-Internet Protocol version 6 (IPv6) support
-logging API

J2SE 5.0 (September 30, 2004)

-Codename Tiger.
-Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
-Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer).
-Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.).
-Static imports

Java SE 6 (December 11, 2006)

Major changes included in this version:

-Codename Mustang
-Improved Web Service support through JAX-WS
-JDBC 4.0 support
-Upgrade of JAXB to version 2.0

Java SE 7 (July 28, 2011)

-Java 7 (codename Dolphin[83])
-Automatic resource management in try-statement[94]
-Improved type inference for generic instance creation, aka the diamond operator.
-Simplified varargs method declaration.
-Binary integer literals.
-Allowing underscores in numeric literals.
-Catching multiple exception types and rethrowing exceptions with improved type checking.

Friday, 27 December 2013

Modularity and three minor pillars of OOPs

Modularity: Modularity refers to breaking down software into different parts. A rigid object is broken into small pieces.

Modularity provides:
  • re-usability
  • parallel development of different modules making development faster
  • module is easier to debug, update and modify.
  • maintainability 
IS-A Relationship: It is like apple is a fruit. This has dependency ie. child class is dependent on parent class. It has tight coupling.

HAS-A Relationship: It is like apple has seeds. This is independent ie. child class has existence without parent class, eg. car has an engine where engine has existence without car.

Three minor pillars of OOPs: 
  • Strong type-casting: Enforcement of th entity, such that objects of different types may not be interchanged, or at the most interchanged only in very restricted ways
  • Persistence: Storing or saving the data for future use.
  • Concurrency: Performing several tasks simultaneously or in parallel.

Thursday, 26 December 2013

Object and pillars of OOPs

Object

Object is a real world entity who has well define structure and behaviour. For example: chair, table, pen etc. It can be tangible or intangible (physical or logical).

Characteristics of object:

  • State: represents the data of an object

  • Behaviour: represents the behaviour of an object.

  • Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user, but is used internally by the JVM to identify each object uniquely

  • Responsibility


Major pillars of OOPs : 

  • Abstraction

  • Encapsulation

  • Inheritance

  • Polymorphysim

Abstraction is a process of exposing essential features of an entity by hiding the other irrelevant details.
 
Encapsulation is the process of putting data and the operations (functions) that can be performed on that data into a single container called class.
 
Inheritance is a process of creating new class from the existing one. Child class inheriting properties from base class.

Polymorphism refers to the ability to take multiple forms. Different  ways or reactions for same instruction is polymorphism.

Why array index starts from zero 
 
The index of array, which is of the form a[i], is converted
by the compiler in the form [a+i]. So, the index of first
element is zero because [a+0] will give 'a' & the first
array element can be accessed. Due to this, we can also
access the array elements as' i[a]' instead of 'a[i]' , &
this will not produce an error. 
 

Wednesday, 25 December 2013

Difference

 Difference between if and switch

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple  alternatives. It uses an int expression to determine which alternative should be executed.

 Difference between for and while

One first basic rule is that you should use the for loop when the number of iterations is known. For instance: The loop iterates over the elements of a collection. The loop iterates over a range of  values which is known in advance at execution time. The object provides a way to iterate over its elements with a for statements (e.g files). The while loop is the more general one because its loop condition is more flexible and can be more complicated than that of a for loop. The condition of a for loop is always the same and implicit in the construction. A for loop stops if there are no more elements in the collection to treat. For simple traversals or iterations over index ranges it is a good advice to use the for statement because it handles the iteration variable for you, so it is more  secure than while where you have to handle the end of the iteration and the change of the iteration variable by yourself. The while loop can take every boolean expression as condition and permits therefore more complex end conditions. It is also the better choice if the iteration variable does not change evently by the same step or if there are more than one iteration variable. Even if you can handle more than one iteration variable in a for statement, the collections from which to choose the values must have the same number of elements. Note: In C 'for' and 'while' can be easily replaced by each other: while (exp) stmt for (;exp;) stmt for (exp1;exp2;exp3) stmt { exp1; while (exp2) { stmt exp3}}

Declaration of int array


 #include<stdio.h>
 int main()
 {
  int a[4];      // declaration of an array of size 4
  int i;
  for ( i = 0; i < 4; i++ )
   a[i] = 0; //initailisation of array
  for ( i = 0; i < 4; i++ )
   printf("a[%d] = %d\n", i , a[i]);
  return 0;
 }

demo of loop, If and switch

 demo of for loop

 #include<stdio.h>
 int main()
 {
       int i;
  /* in this the loop the counter is initialised also the condition is provided ie how many times
     the loop should run and counter is incremented. It is used when we know how many times a loop will run */
       for (i = 0; i < 10; i++)
       {
            printf ("Hello\n");
           printf ("World\n");
       }
      return 0;
 }

 demo of while loop

 #include<stdio.h>
 int main()
 {
      int counter, val;
      scanf("%d", &val);
      counter = 0;
  /*In this loop the counter is initialised outside before the loop, and the counter is incremented. It is used when we do not      know how many times the loop will run */
      while ( counter < val)
      {
            counter++;
            printf("%d\n", counter);
      }
      return 0;
 }

 demo of if statement

 #include<stdio.h>
 int main()
 {
  int number;
  /*  if statement can be used to test conditions so that we can alter the flow of a program ie. if statement is true execute the      instruction if not true execute the instruction */
  scanf("%d",&number);
  if ( number == 10 )
   printf("Is equal\n");
  return 0;
 }

 demo of switch statement

 #include<stdio.h>
 int main()
 {
  char myinput;
  printf("Which option will you choose:\n");
  printf("a) Program 1 \n");
  printf("b) Program 2 \n");
  scanf("%c", &myinput);
  /*  switch statement can have many conditions. Switch statement starts with a condition. If one of the variable equals the        condition, the instructions are executed */
  switch (myinput)
  {
   case 'a':
      printf("Run program 1\n");
      break;
   case 'b':
    {
      printf("Run program 2\n");
     printf("Please Wait\n");
     break;
    }
   default:
     printf("Invalid choice\n");
     break;
  }
  return 0;
 }

Conversion of data types


A data type of lower size (occupying less memory) is assigned to a data type of higher size.
int x = 10; // x occupies 4 bytes
double y = x; // y occupies 8 bytes

A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size.requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size. Eg:
 double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
we need to explicitly convert it
 double x = 10.5;
 int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type should exist.
A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion. Maximum we can assign a boolean value to another boolean.
Following raises error.
       boolean x = true;
       int y = x;                    // error
       boolean x = true;
       int y = (int) x;           // error
byte –> short –> int –> long –> float –> double
In the above statement, left to right can be assigned implicitly and right to left requires explicit casting. That is, byte can be assigned to short implicitly but short to byte requires explicit casting.
int to char requires explicit casting.
byte to char and char to byte requires expilcit casting.
char to short or short to char requires explicit casting.
float to char requires explicit casting.

Primitive data types

There are 8 primitive data types: byte, short, int, long, float, double,
char, Boolean

    byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

    short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

    int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

    long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The unsigned long has a minimum value of 0 and maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

    float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

    double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

    boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

    char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Types of computer languages

 Computer languages have several contrasting points, but the major ones are as follows: High Level vs. Low Level: High Level allows abstract programming, but programmers lose control over hardware optimization. Applications are written faster and with better stability, at the cost of performance. Low level provides better programmer optimization, but is prone to logic and programming errors  that an abstract language would prevent.
Interpreted vs. Compiled: Compiled languages can only run on the platform they are compiled for, but tend to have higher performance. They also tend to crash more frequently in the event of a programming error. Scripting languages run slower, but will run on any platform that supports that scripting language. Since they are interpreted, the system can catch errors and recover from otherwise fatal conditions (note: yes, compiled languages can do so, too, but usually requires more programmer intervention to catch these conditions).
Procedural vs.  Functional vs. Object-Oriented: Procedural languages follow a given order by the programmer, branching when the programmer tells it to, etc, etc. This allows greater control over the flow of a program at the expense of a longer development cycle. Functional languages define a program as a series of interrelated functions; however, the compiler (or interpreter) determines the order of execution  based on dependencies in the functions, rather than programmer-defined flow. Object-Oriented is usually a procedural language set, but with the additional concept that code and data are organized into discrete units called objects; they can protect their own internal pieces in order to avoid being damaged by poor logic written in another module.

When to use which language

Below are the points that influence the choice of programming language :

· The language must be fit-for-purpose. Normal business-application development can be done in Java or COBOL, but specialist applications might need C++ or some other language.

· The choice of platform is critical. It’s better to let the platform dictate the programming language, instead of letting the programming language dictate the platform.

· The skills of the programmers. Programmers are much more productive when they are working in a language that they know well, instead of working in a new language or on a new platform.

Factors to consider when selecting a programming language are:

   - The targeted platform
   - The elasticity of a language
   - The time to production
   - The performance
   - The support and community