Monday, 1 May 2017

Java - High-Level Programming Language


             Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java.
         Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

          The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is −

·        Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
·        Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This bytecode is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
·        Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
·        Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
·        Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.
·        Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
·        Robust − Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error checking and runtime checking.
·        Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.
·        Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.
·     High-Performance − With the use of Just-In-Time compilers, Java enables high performance.
·        Distributed − Java is designed for the distributed environment of the internet.
·        Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
Tools You Will Need
     For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following software −
  • Linux 7.1 or Windows xp/7/8 operating system
  • Java JDK 8
  • Microsoft Notepad or any other text editor
     When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.
·        Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
·        Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
·      Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
·        Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program

   Let us look at a simple code that will print the words Hello World.

Example

public class MyFirstJavaProgram {
 
   /* This is my first java program.
    * This will print 'Hello World' as the output
    */
 
   public static void main(String []args) {
      System.out.println("Hello World"); // prints Hello World
   }
}

Basic Syntax

About Java programs, it is very important to keep in mind the following points.
·        Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java.
·        Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
·        Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
·        Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the filename and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
·        public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

Java Identifiers

      All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
·        All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
·        After the first character, identifiers can have any combination of characters.
·        A keyword cannot be used as an identifier.
·        Most importantly, identifiers are case sensitive.
·        Examples of legal identifiers: age, $salary, _value, __1_value.
·        Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
       Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −
·        Access Modifiers − default, public , protected, private
·        Non-access Modifiers − final, abstract, strictfp
Java Variables
     Following are the types of variables in Java −
  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static Variables)
Java Arrays
     Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.
    Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −
  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Parsing
   Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java −
  • Primitive Data Types
  • Reference/Object Data Types
·         A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
·         You must declare all variables before they can be used. Following is the basic form of a variable declaration −
·         data type variable [ = value][, variable [ = value] ...] ;

  Modifiers are keywords that you add to those definitions to change their meanings. Java language has a wide variety of modifiers, including the following −
·        Java Access Modifiers
·        Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable.
   Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −
  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Misc Operators
       There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
·         Programming languages provide various control structures that allow for more complicated execution paths.
·         A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages
·         Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.
·         The Java platform provides the String class to create and manipulate strings.
         Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
           A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
   Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.

Creating Method

Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
   // body
}
      An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
·        A user has entered an invalid data.
·        A file that needs to be opened cannot be found.
·        A network connection has been lost in the middle of communications or the JVM has run out of memory.
·         Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance, the information is made manageable in a hierarchical order.
·         The class which inherits the properties of other is known as a subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
   Syntax
·         class Super {
·            .....
·            .....
·         }
·         class Sub extends Super {
·            .....
·            .....
·         }
·         The benefit of overriding is: the ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.
·        In object-oriented terms, overriding means to override the functionality of an existing method.
      Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
        Abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send.
        Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
       Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
·        Declare the variables of a class as private.
·        Provide public setter and getter methods to modify and view the variables values.

No comments:

Post a Comment

Popular Posts