Java in Easy Ways

Download Java in Easy Ways

Post on 08-Apr-2018

218 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

  • 8/6/2019 Java in Easy Ways

    1/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 1

    Java in Easy

    Ways

  • 8/6/2019 Java in Easy Ways

    2/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 2

    JAVA AN INTRODUCTION

    INTRODUCTION TO JAVA

    Java is a simple and yet powerful object oriented programming language and it is in

    many respects similar to C++. Java was given birth at Sun Microsystems, Inc. in 1991. Java was

    conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at

    Sun Microsystems, Inc. It was developed to provide a platform-independent programming

    language.

    Java (with a capital J) is a high-level, third generation programming language, like C, Fortran,

    Smalltalk, Perl, and many others. You can use Java to write computer applications that crunch

    numbers, process words, play games, store data or do any of the thousands of other things

    computer software can do.

    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 byte

    code is distributed over the web and interpreted by Java virtual Machine (JVM) on whichever

    platform it is being run.

    Compared to other programming languages, Java is most similar to C. However although Java

    shares much of C's syntax, it is not C. Knowing how to program in C or, better yet, C++, will

    certainly help you to learn Java more quickly, but you don't need to know C to learn Java. Unlike

    C++ Java is not a superset of C. A Java compiler won't compile C code, and most large C

    programs need to be changed substantially before they can become Java programs.

    Java Virtual Machine

    Java was designed with a concept of write once and run everywhere. Java Virtual Machine

    plays the central role in this concept. The Java Virtual Machine (JVM) is the environment in

    which Java programs execute. It is a software that is implemented on top of real hardware and

    operating system. When Java source code (.java files) is compiled, it is translated into Java

  • 8/6/2019 Java in Easy Ways

    3/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 3

    bytecodes and then placed into (.class) files. The JVM executes Java bytecodes. So Java

    bytecodes can be thought of as the machine language of the JVM. A Java virtual machine can

    either interpret the bytecode one instruction at a time or the bytecode can be compiled further for

    the real microprocessor using what is called a just-in-time compiler. The JVM must beimplemented on a particular platform before compiled Java programs can run on that platform.

    Java has powerful features. The following are some of them:-

    Java is object oriented

    Since Java is an object oriented programming language it has following advantages:

    y Reusability of Codey Emphasis on data rather than procedurey Data is hidden and cannot be accessed by external functionsy Objects can communicate with each other through functionsy New data and functions can be easily added

    Java is Distributed

    With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and

    access the objects across net via URLs.

    Java is Multithreaded

    One of the powerful aspects of the Java language is that it allows multiple threads of execution to

    run concurrently within the same program A single Java program can have many different

    threads executing independently and continuously. Multiple Java applets can run on the browser

    at the same time sharing the CPU time.

    Java is Secure

  • 8/6/2019 Java in Easy Ways

    4/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 4

    Java was designed to allow secure execution of code across network. To make Java secure many

    of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot

    access arbitrary addresses in memory.

    Garbage collection

    Automatic garbage collection is another great feature of Java with which it prevents inadvertent

    corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap

    for a new object. But it does not use delete operator to free the memory as it is done in C++ to

    free the memory if the object is no longer needed. It is done automatically with garbage

    collector.

    Application of Java

    Java has evolved from a simple language providing interactive dynamic content for web pages to

    a predominant enterprise-enabled programming language suitable for developing significant and

    critical applications. Today, Java is used for many types of applications including Web based

    applications, Financial applications, Gaming applications, embedded systems, Distributed

    enterprise applications, mobile applications, Image processors, desktop applications and many

    more.

    The most special about Java in relation to other programming languages is that it lets you write

    special programs called applets that can be downloaded from the Internet and played safely

    within a web browser. Traditional computer programs have far too much access to your system

    to be downloaded and executed willy-nilly. Although you generally trust the maintainers of

    various ftp archives and bulletin boards to do basic virus checking and not to post destructive

    software, a lot still slips through the cracks. Even more dangerous software would be

    promulgated if any web page you visited could run programs on your system.

    JAVA VS. C++

    Java C++

  • 8/6/2019 Java in Easy Ways

    5/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 5

    Method bodies must be defined inside the class

    to which they belong.

    Method bodies must be defined inside the class

    to which they belong.

    No forward referencing required. Explicit forward referencing required.

    No preprocessor. Heavy reliance on preprocessor.

    No comma operator. Comma operator.

    No variable-length parameter lists. Variable-length parameter lists.

    No optional method parameters. Optional function parameters.

    No const reference parameters. const reference parameters.

    No goto Goto

    Labels on break and continue. No labels on break and continue.

    Command-line arguments do not include the

    program name.

    Command-line arguments do not include the

    program name.

    Main method cannot return a value. Main function can return a value.

    No global variables. Global variables.

    Character escape sequences can appear in a

    program.

    Character escape sequences must appear in astring

    or character literal.

    Cannot mask identifiers through scope. Can mask identifiers through scope.

    DATA TYPES IN JAVA

    Data type defines a set of permitted values on which the legal operations can beperformed. In java, all the variables needs to be declared first i.e. before using a particular

    variable, it must be declared in the program for the memory allocation process. Like

    int pedal = 1;

    This statement exists a field named "pedal" that holds the numerical value as 1. The value

    assigned to a variable determines its data type, on which the legal operations of java are performed. This behavior specifies that, Java is a strongly-typed programming language.

    The data types in the Java programming language are divided into two categories and can be

    explained using the following hierarchy structure :

  • 8/6/2019 Java in Easy Ways

    6/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 6

    Primitive Data Types

    The primitive data types are predefined data types, which always hold the value of the same

    data type, and the values of a primitive data type don't share the state with other primitive

    values. These data types are named by a reserved keyword in Java programming language.

    There are eight primitive data types supported by Java programming language :

    byteThe byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127(inclusive). This type of data type is useful to save memory in large arrays.. We can also use

    byte instead ofint to increase the limit of the code. The syntax of declaring a byte type variableis shown as:

    byte b = 5;

    shortThe short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to

    32,767. short is used to save memory in large arrays. The syntax of declaring a short typevariable is shown as:

    short s = 2;

    intThe int data type is used to store the integer values not the fraction values. It is a 32-bit signed

    two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647 that is more

    enough to store large number in your program. However for wider range of values uselong. Thesyntax of declaring a int type variable is shown as:

    int num =50;

    longThe long data type is a 64-bit signed two's complement integer. It ranges from -

  • 8/6/2019 Java in Easy Ways

    7/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 7

    9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger rangeof values. The syntax of declaring a long type variable is shown as:

    long ln = 746;

    floatThe float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float

    (instead of double) to save memory in large arrays. We do not use this data type for the exactvalues such as currency. For that we have to use java.math.BigDecimal class. The syntax of

    declaring a float type variable is:

    float f = 105.65;

    float f = -5000.12;

    double

    This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This datatype is generally the default choice for decimal values. The syntax of declaring a double type

    variable is shown as:

    double d = 6677.60;

    charThe char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.They are not integral data type like int, short etc. i.e. the char data type can't hold the numeric

    values. The syntax of declaring a char type variable is shown as:

    char caps = 'c';

    boolean

    The boolean data type represents only two values: true and false and occupy is 1-bit in the

    memory. These values are keywords in Java and represents the two boolean states: on oroff,

    yes orno. We use boolean data type for specifying conditional statements as if, while, do, for.In Java, true and false are not the same as True and False. They are defined constants of the

    language. The syntax of declaring a boolean type variable is shown as:

    boolean result = true;

    Integer Data Types

    An integer number can hold a whole number. Java provides four different primitive integer datatypes that can be defined as byte, short, int, and long that can store both positive and negative

    values. The ranges of these data types can be described using the following table:

  • 8/6/2019 Java in Easy Ways

    8/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 8

    Data Type Size (in bits) Minimum Range Maximum Range

    ByteOccupy 8 bits

    in memory-128 +127

    ShortOccupy 16 bitsin memory

    -32768 +32767

    IntOccupy 32 bitsin memory

    -2147483648 +2147483647

    LongOccupy 64 bits

    in memory-9223372036854775808 +9223372036854775807

    Examples of floating-point literals are:

    0

    1123

    -42000

    Floating-point numbers

    A floating-point number represents a real number that may have a fractional values i.e. In the

    floating type of variable, you can assign the numbers in an in a decimal or scientific notation.Floating-point number have only a limited number of digits, where most values can be

    represented only approximately. The floating-point types are float and double with a single- precision 32-bit IEEE 754 floating point and double-precision 64-bit IEEE 754 floating point

    respectively. Examples of floating-point literals are:

    10.0003

    48.9-2000.15

    7.04e12

  • 8/6/2019 Java in Easy Ways

    9/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 9

    Reference Data Types

    In Java a reference data type is a variable that can contain the reference or an address of

    dynamically created object. These type of data type are not predefined like primitive data type.The reference data types are arrays, classes and interfaces that are made and handle according

    to a programmer in a java program which can hold the three kind of values as:

    array type

    // Points to an array instance

    class type

    // Points to an object or a class instance

    interface type// Points to an object and a method, which is

    implemented to the corresponding interface

    Interface Type:

    Java provides an another kind of reference data type or a mechanism to support multipleinheritance feature called an interface. The name of an interface can be used to specify the type

    of a reference. A value is not allowed to be assign to a variable declared using an interface typeuntil the object implements the specified interface.

    When a class declaration implements an interface, that class inherits all of the variables andmethods declared in that interface. So the implementations for all of the methods declared in the

    interface must be provided by that class. For example, Java provides an interface called

    ActionListener whose method named actionPerformed() is used to handle the different kind of

    event . Java also provides a class called Thread that implements Runnable interface.Thus the following assignment can be allowed:

    Runnable r;

    r = new Thread();

  • 8/6/2019 Java in Easy Ways

    10/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 10

    OPERATORS IN JAVA

    Java provides a rich operator environment. Most of its operators can be divided

    into the following four groups: arithmetic, bitwise, relational, and logical. Java also

    defines some additional operators that handle certain special situations.

    The Simple Assignment Operator

    One of the most common operators that encounter is the simple assignment operator "=". it

    assigns the value on its right to the operand on its left:

    int cadence = 0;int speed = 0;

    int gear = 1;

    This operator can also be used on objects to assign object references

    The Arithmetic Operators

    The Java programming language provides operators that perform addition, subtraction,

    multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one

    operand by another and returns the remainder as its result. OperatorResult

    + Addition Subtraction (also unary minus)

    * Multiplication/ Division

    % Modulus++ Increment

    += Addition assignment= Subtraction assignment

    *= Multiplication assignment/= Division assignment

    %= Modulus assignment Decrement

    The following program, ArithmeticDemo, tests the arithmetic operators.

    class ArithmeticDemo {

    public static void main (String[] args){

  • 8/6/2019 Java in Easy Ways

    11/73

    JJAAVVAA IINN EEAASSYY WWAAYYSS

    Compilation : Randjithkumar, B.TechPage 11

    int result = 1 + 2; // result is now 3System.out.println(result);

    result = result - 1; // result is now 2

    System.out.println(result);

    resu...