Basic Java
admin admin

Overview of Java

Java is one of the world's most important and widely used computer languages, and it has held this distinction for many years. Unlike some other computer languages whose influence has weared with passage of time, while Java's has grown.

As of 2015, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers using and working on it.

Creation of Java

Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun Microsystems Inc. in 1991. It took 18 months to develop the first working version.

The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered trademark of another Tech company.

Evolution of Java

Java was initially launched as Java 1.0 but soon after its initial release, Java 1.1 was launched. Java 1.1 redefined event handling, new library elements were added.

In Java 1.2 Swing and Collection framework was added and suspend()resume() and stop() methods were deprecated from Thread class.

No major changes were made into Java 1.3 but the next release that was Java 1.4 contained several important changes. Keyword assert, chained exceptions and channel based I/O System was introduced.

Java 1.5 was called J2SE 5, it added following major new features :

  • Generics
  • Annotations
  • Autoboxing and autounboxing
  • Enumerations
  • For-each Loop
  • Varargs
  • Static Import
  • Formatted I/O
  • Concurrency utilities

Next major release was Java SE 7 which included many new changes, like :

  • Now String can be used to control Switch statement.
  • Multi Catch Exception
  • try-with-resource statement
  • Binary Integer Literals
  • Underscore in numeric literals, etc.

And the latest addition to the lot is, Java SE 8, it was released on March 18, 2014. Some of the major new features introduced in JAVA 8 are,

  • Lambda Expressions
  • New Collection Package java.util.stream to provide Stream API.
  • Enhanced Security
  • Nashorn Javascript Engine included
  • Parallel Array Sorting
  • The JDBC-ODBC Bridge has been removed etc.

Application of Java

Java is widely used in every corner of world and of human life. Java is not only used in softwares but is also widely used in designing hardware controlling software components. There are more than 930 million JRE downloads each year and 3 billion mobile phones run java.

Following are some other usage of Java :

  1. Developing Desktop Applications
  2. Web Applications like Linkedin.com, Snapdeal.com etc
  3. Mobile Operating System like Android
  4. Embedded Systems
  5. Robotics and games etc.

Download JDK

For running Java programs in your system you will have to download and install JDK kit from here (current version is jdk 1.8).

Features of Java

The prime reason behind creation of Java was to bring portability and security feature into a computer language. Beside these two major features, there were many other features that played an important role in moulding out the final form of this outstanding language. Those features are :

1) Simple

Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way.

Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.

2) Object Oriented

In java everything is Object which has some data and behaviour. Java can be easily extended as it is based on Object Model.

3) Robust

Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime checking. But the main areas which Java improved were Memory Management and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.

4) Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere language.

On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on any machine, plus this bytecode format also provide security. Any machine with Java Runtime Environment can run Java Programs.

Java is platform Independent Language

5) Secure

When it comes to security, Java is always the first choice. With java secure features it enable us to develop virus free, temper free system. Java program always runs in Java runtime environment with almost null interaction with system OS, hence it is more secure.

6) Multi Threading

Java multithreading feature makes it possible to write program that can do many tasks simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads at the same time, like While typing, grammatical errors are checked along.

7) Architectural Neutral

Compiler generates bytecodes, which have nothing to do with a particular computer architecture, hence a Java program is easy to intrepret on any machine.

8) Portable

Java Byte code can be carried to any platform. No implementation dependent features. Everything related to storage is predefined, example: size of primitive data types

9) High Performance

Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java enables high performance with the use of just-in-time compiler.

New Features of JAVA 8

Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go through them quickly, we will explore them in details later.

  • Enhanced Productivity by providing Optional Classes feature, Lamda Expressions, Streams etc.
  • Ease of Use
  • Improved Polyglot programming. A Polyglot is a program or script, written in a form which is valid in multiple programming languages and it performs the same operations in multiple programming languages. So Java now supports such type of programming technique.
  • Improved Security and performance.
  • Setting Classpath for Java

    Java is freely available on Oracle's Website. Download the latest version of JDK (Java Development Kit) on your machine. Do check whether your machine is 32 bit or 64 bit and download that particular Java version. Install JDK on your machine. Once you have installed Java on your machine you would need to set environment variable to point to correct installation directory.

    An Environment variable is a dynamic "object" on a computer that stores a value(like a key-value pair), which can be referenced by one or more software programs in Windows. Like for Java, we will set an environment variable with name "java" and its value will be the path of the /bin directory present in Java directory. So whenever a program will require Java environment, it will look for the java environment variable which will give it the path to the execution directory.

    Setting up path for windows ( 2000/XP/vista/Window 7,8 )

    Assuming that you have installed Java in C:\ Program files/ Java / JDK directory

    Step 1: Right click on my computer and select properties.

    setting classpath in java

    Step 2: Go to the Advance System Settings tab.

    setting classpath in java

    Step 3: Click on Environment Variables button.

    setting classpath in java

    Step 4: Now alter the path variable so that it also contains the path to JDK installed directory.

    setting classpath in java

    For e.g:- Change C:\windows/ system 32. to C:\windows/system 32; C:\program files / Java/ JDK.

    Setting up path for window 95/98/ME

    Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the following:

    Step 1: Edit the C:\autoexec.bat file and add the following line at the end.


    Setting up path for Linux , Unix , Solaris, free BSD

    Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the following:

    Step 1: Environment variable path should be set to point where java binaries have been installed. Refer to your shell if you have trouble doing this.

    For Example: If you use bash as your shell, then you would add following line to the end

    bash mc: export PATH=/ Path/to/java 

    What is JVM?

    Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute java byte code. The JVM doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.

    JVM control execution of every Java program. It enables features such as automated exception handling, Garbage-collected heap.

    JVM Architecture

    JVM architecture in Java

    Class Loader : Class loader loads the Class for execution.

    Method area : Stores pre-class structure as constant pool.

    Heap : Heap is in which objects are allocated.

    Stack : Local variables and partial results are store here. Each thread has a private JVM stack created when the thread is created.

    Program register : Program register holds the address of JVM instruction currently being executed.

    Native method stack : It contains all native used in application.

    Executive Engine : Execution engine controls the execute of instructions contained in the methods of the classes.

    Native Method Interface : Native method interface gives an interface between java code and native code during execution.

    Native Method Libraries : Native Libraries consist of files required for the execution of native code.

    Difference between JDK and JRE

    JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

    What is JRE

    JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

    What is JDK

  • First Java Program

    Let us look at a simple java program.

    class Hello
      public static void main(String[] args) 
         System.out.println ("Hello World program");

    class : class keyword is used to declare classes in Java

    public : It is an access specifier. Public means this function is visible to all.

    static : static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. The main() method here is called by JVM, without creating any object for class.

    void : It is the return type, meaning this function will not return anything.

    main : main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.

    String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.

    System.out.println : This is used to print anything on the console like printf in C language.

    Steps to Compile and Run your first Java program

    Step 1: Open a text editor and write the code as above.

    Step 2: Save the file as Hello.java

    Step 3: Open command prompt and go to the directory where you saved your first java program assuming it is saved in C:\

    Step 4: Type javac Hello.java and press Return(Enter KEY) to compile your code. This command will call the Java Compiler asking it to compile the specified file. If there are no errors in the code the command prompt will take you to the next line.

    Step 5: Now type java Hello on command prompt to run your program.

    Step 6: You will be able to see Hello world program printed on your command prompt.

    Now let us see What happens at Runtime

    After writing your Java program, when you will try to compile it. Compiler will perform some compilation operation on your program.

    Once it is compiled successfully byte code(.class file) is generated by the compiler.

    class-file at runtime in Java

    After compiling when you will try to run the byte code(.class file), the following steps are performed at runtime:-

    1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
    2. Byte Code verifier checks the code fragments for illegal codes that can violate access right to the object.
    3. Interpreter reads the byte code stream and then executes the instructions, step by step.

    Data Types in Java

    Java language has a rich implementation of data types. Data types specify size and the type of values that can be stored in an identifier.

    In java, data types are classified into two catagories :

    1. Primitive Data type
    2. Non-Primitive Data type

    1) Primitive Data type

    A primitive data type can be of eight types :

    Primitive Data types

    Once a primitive data type has been declared its type can never change, although in most cases its value can change. These eight primitive type can be put into four groups


    This group includes byteshortintlong

    byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default value zero. example: byte b=10;

    short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767. Default value zero. example: short s=11;

    int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to 2147483647. Default value zero. example: int i=10;

    long : It is 8 bytes(64-bits) integer data type. Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Default value zero. example: long l=100012;

    Floating-Point Number

    This group includes floatdouble

    float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;

    double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double db=11.123;


    This group represent char, which represent symbols in a character set, like letters and numbers.

    char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535. example: char c='a';


    This group represent boolean, which is a special type for representing true/false values. They are defined constant of the language. example: boolean b=true;

    2) Non-Primitive(Reference) Data type

    A reference data type is used to refer to an object. A reference variable is declare to be of specific and that type can never be change. We will talk a lot more about reference data type later in Classes and Object lesson.

    Identifiers in Java

    All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier. Identifier must follow some rules. Here are the rules:

    • All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
    • After the first character, an identifier can have any combination of characters.
    • A Java keyword cannot be used as an identifier.
    • Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

      Type Casting

      Assigning a value of one type to a variable of another type is known as Type Casting.

      Example :

      int x = 10;
      byte y = (byte)x;

      In Java, type casting is classified into two types,

      • Widening Casting(Implicit)
      • widening-type-conversion

      • Narrowing Casting(Explicitly done)
      • narrowing-type-conversion

      Widening or Automatic type converion

      Automatic Type casting take place when,

      • the two types are compatible
      • the target type is larger than the source type

      Example :

      public class Test
          public static void main(String[] args)
            int i = 100;	
            long l = i;	//no explicit type casting required  
            float f = l;	//no explicit type casting required  
            System.out.println("Int value "+i);
            System.out.println("Long value "+l);
            System.out.println("Float value "+f);

      Output :

      Int value 100
      Long value 100
      Float value 100.0

      Narrowing or Explicit type conversion

      When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.

      Example :

      public class Test
          public static void main(String[] args)
            double d = 100.04;  
            long l = (long)d;  //explicit type casting required  
            int i = (int)l;	//explicit type casting required  
            System.out.println("Double value "+d);
            System.out.println("Long value "+l);
            System.out.println("Int value "+i);

      Output :

      Double value 100.04
      Long value 100
      Int value 100


      What is a variable?

      When we want to store any information, we store it in an address of the computer. Instead of remembering the complex address where we have stored our information, we name that address.The naming of an address is known as variable. Variable is the name of memory location.

      Java Programming language defines mainly three kind of variables.

      1. Instance variables
      2. Static Variables
      3. Local Variables

      1) Instance variables

      Instance variables are variables that are declare inside a class but outside any method,constructor or block. Instance variable are also variable of object commonly known as field or property. They are referred as object variable. Each object has its own copy of each variable and thus, it doesn't effect the instance variable if one object changes the value of the variable.

      class Student
       String name;
       int age;
      Here name and age are instance variable of Student class.

      2) Static variables

      Static are class variables declared with static keyword. Static variables are initialized only once. Static variables are also used in declaring constant along with final keyword.

      class Student
       String name;
       int age;
       static int instituteCode=1101; 

      Here instituteCode is a static variable. Each object of Student class will share instituteCode property.

      Additional points on static variable:

      • static variable are also known as class variable.
      • static means to remain constant.
      • In Java, it means that it will be constant for all the instances created for that class.
      • static variable need not be called from object.
      • It is called by classname.static variable name

      Note: A static variable can never be defined inside a method i.e it can never be a local variable.


      Suppose you make 2 objects of class Student and you change the value of static variable from one object. Now when you print it from other object, it will display the changed value. This is because it was declared static i.e it is constant for every object created.

      package studytonight;
      class Student{
          int a;
          static int id = 35;
          void change(){
      public class StudyTonight {
          public static void main(String[] args) {
              Student o1 = new Student();
              Student o2 = new Student();
              Student.id = 1;

      3) Local variables

      Local variables are declared in method, constructor or block. Local variables are initialized when method, constructor or block start and will be destroyed once its end. Local variable reside in stack. Access modifiers are not used for local variable.

      float getDiscount(int price)
       float discount;
       return discount; 
      Here discount is a local variable.

      Concept of Array in Java

      An array is a collection of similar data types. Array is a container object that hold values of homogenous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.

      An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero to size-1.

      Features of Array

      • It is always indexed. Index begins from 0.
      • It is a collection of similar data types.
      • It occupies a contiguous memory location.

      Array Declaration

      Syntax :

      datatype[ ] identifier;
      datatype identifier[ ];

      Both are valid syntax for array declaration. But the former is more readable.

      Example :

      int[ ] arr;
      char[ ] arr;
      short[ ] arr;
      long[ ] arr;
      int[ ][ ] arr;   // two dimensional array.

      Initialization of Array

      new operator is used to initialize an array.

      Example :

      int[ ] arr = new int[10];    //this creates an empty array named arr of integer type whose size is 10.
      int[ ] arr = {10,20,30,40,50};  //this creates an array named arr whose elements are given.

      Accessing array element

      As mention ealier array index starts from 0. To access nth element of an array. Syntax


      Example : To access 4th element of a given array

      int[ ] arr = {10,20,30,40};
      System.out.println("Element at 4th place" + arr[3]);
      The above code will print the 4th element of array arr on console.

      Note: To find the length of an array, we can use the following syntax: array_name.length. There are no braces infront of length. Its not length().

      foreach or enhanced for loop

      J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using foreach loop you can access complete array sequentially without using index of array. Let us see an example of foreach loop.

      class Test
      public static void main(String[] args)
          int[] arr = {10, 20, 30, 40};
      	for(int x : arr)

      Output :


      Multi-Dimensional Array

      A multi-dimensional array is very much similar to a single dimensional array. It can have multiple rows and multiple columns unlike single dimensional array, which can have only one full row or one full column.

      Array Declaration

      datatype[ ][ ] identifier;
      datatype identifier[ ][ ];

      Initialization of Array

      new operator is used to initialize an array.

      int[ ][ ] arr = new int[10][10];    //10 by 10 is the size of array.
      int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
      // 3 by 5 is the size of the array.

      Accessing array element

      For both, row and column, the index begins from 0.

      int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
      System.out.println("Element at (2,3) place" + arr[1][2]);

      Jagged Array

      Jagged means to have an uneven edge or surface. In java, a jagged array means to have a multi-dimensional array with uneven size of rows in it.

      Jagged Array

      Initialization of Jagged Array

      new operator is used to initialize an array.

      int[ ][ ] arr = new int[3][ ];    //there will be 10 arrays whose size is variable
      arr[0] = new int[3];
      arr[1] = new int[4];
      arr[2] = new int[5];

      Java Operators

      Java provides a rich set of operators enviroment. Java operators can be devided into following categories

      • Arithmetic operators
      • Relation operators
      • Logical operators
      • Bitwise operators
      • Assignment operators
      • Conditional operators
      • Misc operators

      Arithmetic operators

      Arithmetic operators are used in mathematical expression in the same way that are used in algebra.

      +adds two operands
      -subtract second operands from first
      *multiply two operand
      /divide numerator by denumerator
      %remainder of division
      ++Increment operator increases integer value by one
      --Decrement operator decreases integer value by one

      Relation operators

      The following table shows all relation operators supported by Java.

      ==Check if two operand are equal
      !=Check if two operand are not equal.
      >Check if operand on the left is greater than operand on the right
      <Check operand on the left is smaller than right operand
      >=check left operand is greater than or equal to right operand
      <=Check if operand on left is smaller than or equal to right operand

      Logical operators

      Java supports following 3 logical operator. Suppose a=1 and b=0;

      &&Logical AND(a && b) is false
      ||Logical OR(a || b) is true
      !Logical NOT(!a) is false

      Bitwise operators

      Java defines several bitwise operators that can be applied to the integer types long, int, short, char and byte

      &Bitwise AND
      |Bitwise OR
      ^Bitwise exclusive OR
      <<left shift
      >>right shift

      Now lets see truth table for bitwise &| and ^

      aba & ba | ba ^ b

      The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence.Example

      a = 0001000
      b= 2
      a << b= 0100000
      a >> b= 0000010 

      Assignment Operators

      Assignment operator supported by Java are as follows

      =assigns values from right side operands to left side operanda=b
      +=adds right operand to the left operand and assign the result to lefta+=b is same as a=a+b
      -=subtracts right operand from the left operand and assign the result to left operanda-=b is same as a=a-b
      *=mutiply left operand with the right operand and assign the result to left operanda*=b is same as a=a*b
      /=divides left operand with the right operand and assign the result to left operanda/=b is same as a=a/b
      %=calculate modulus using two operands and assign the result to left operanda%=b is same as a=a%b

      Misc operator

      There are few other operator supported by java language.

      Conditional operator

      It is also known as ternary operator and used to evaluate Boolean expression

      epr1 ? expr2 : expr3
      If epr1Condition is true? Then value expr2 : Otherwise value expr3

      instanceOf operator

      This operator is used for object reference variables. The operator checks whether the object is of particular type (class type or interface type)

  • VIA
  • admin
  • TAGS


Facebook Conversations