JAVA

 What is Java?

            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.

->According to SUN, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:

    Desktop Applications such as acrobat reader, media player, antivirus etc.

    Web Applications such as irctc.co.in, javatpoint.com etc.

    Enterprise Applications such as banking applications.

    Mobile & Embedded System

    Smart Card

    Robotics and Games etc.

___________________________________________________________________________________

History of Java.

            Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java.

-> James Gosling, Mike Sheridan, and Patrick Naughton initiated the java language project in june 1991. The small team of sun engineers called Green Team.

-> Originally designed for small, embedded systems in electronic appliances like set-top boxes.

-> Firstly, it was called "Greentalk" by James Gosling and file extension was .gt. 

->After that, it was called OAK and was developed as a part of the Green project.

___________________________________________________________________________________

Why OAK name for java Language?

            OAK is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania etc.

-> In 1995, OAK was renamed as "Java" because it was already a trademark by OAK Technologies.

___________________________________________________________________________________

Why Java name for java language?

            The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary", "Silk","Jolt","DNA" etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.

-> According to James Gosling "Java was one of the top choices along with Silk". Since java was so unique, most of the team members preferred java.

-> Notice that java is just a name not an acronym.

-> Originally developed by James Gosling at Sun Microsystems(Which is now a subsidiary of Oracle Corporation) and released in 1995.

-> In 1995, Time magazine called Java one of the Best products of 1995.

-> JDK1.0 released in january 23, 1996.

___________________________________________________________________________________

Symbol of Java

            When it comes to the nick name java, the explanation is fairly straightforward. When coffee became quite popular way back in the 1800s, the main source of the world's coffee at that time was the Indonasian island named Java.  So it was only natural that a mug of hot coffee would come to be known as Java.

___________________________________________________________________________________

Java Edition

1.) J2SE

2.) J2EE

3.) J2ME

___________________________________________________________________________________

What is Java? Explain Java features.

Java is a programming language that:

     Is exclusively object oriented

     Has full GUI support

     Has full network support

     Is platform independent

     Executes stand-alone or “on-demand” in web browser as applets

Features of JAVA :-

    1. Simple, 2. Secure, 3. Portable, 4. Object-oriented, 5. Robust, 6. Multithreaded, 7. Architecture-natural, 8. Interpreted, 9. High performance, 10. Distributed, 11. Dynamic, 

1. Simple

         Java was designed to be easy for the professional programmer to learn and use effectively.

         Assuming that you have some programming experience, you will not find java hard to master.

         If you already understand the basic concepts of object oriented programming, learning java will be even easier.

         If you are an experienced C++ programmer, moving to java will require very little effort. Because java inherits the C/C++ syntax and many of the object oriented features of C++, most programmers have little trouble learning Java.

2. Security :-

         Security is the benefit of java. Java system not only verifies all memory access but also ensure that no viruses are communicated with an applet.

3.Portable :-

        The most significant contribution of java over other language is its portability. Java programs can be easily moved from one computer system to another. Java ensures portability in two ways:

        1. Java compiler generates byte code instruction that can be implemented on any machine.

        2. The size of the primitive data types is machine-independent.

4. Object-Oriented :-

        Java is a true object oriented language. All program code and data reside within object and classes. The object model in java is simple and easy to extend.

5. Robust(healthy, strong) :-

        The multiplatform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of java.

         To gain reliability, java has strict compile time and run time checking for codes.

         To better understand how java is robust, consider two main reasons for program failure: memory management mistakes and mishandled exceptional conditions.

6. Multithreaded :-

        Java was designed to meet the real-world requirement of creating interactive, networked programs.

         To accomplish this, java supports multithreaded programming, which allows you to write programs that do many things simultaneously.

         The java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems.

         Java’s easy to use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem.

7. Architecture-Neutral :-

        A central issue of java programmers was that code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow- even on the same machine.

         Operating system upgrades, and changes in core system resources can al combine to make a program malfunction.

        The java designer made several hard decisions in the java language and the java virtual machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any time, forever.”

8. Interpreted :-

        Usually a computer language is either compiled or interpreted. Java combines these approaches thus making java a two-stage system.

         Java compiler translates source code into byte code instructions. Byte codes are not machine instructions and so java interpreter generates machine code that can be directly executed by the machine that is running the java program.

         We can thus say that java is both a compiled and an interpreted language.

9. High Performance :-

        Java performance is impressive for an interpreted language, mainly due to the use of intermediate byte code.

10. Distributed :-

        Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.

         Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.

11. Dynamic :-

        Java is capable of dynamically linking in new class libraries, methods and object.

         Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program.

Summary: Java is a object oriented programming language which has full supports of GUI and network.It is Platform Independent,Robust,Object Oriented,Multithreaded,High Performance and Portable and Dynamic and secure.

___________________________________________________________________________________

Java Edition

Java Platform, Micro Edition(J2ME) :-

    – Java ME, is designed for mobile phones (especially feature phones) and set-top boxes. Java ME was formerly known as Java 2 Platform, Micro Edition (J2ME).

    – Java ME was designed by Sun Microsystems, acquired by Oracle Corporation in 2010; the platform replaced a similar technology, PersonalJava.

    – The most common of these are the Mobile Information Device Profile aimed at mobile devices, such as cell phones, and the Personal Profile aimed at consumer products and embedded devices like set-top boxes and PDAs.

Java Platform, Enterprise Edition(J2EE) :-

    – Java EE is Oracle's enterprise Javacomputing platform .

    – The platform provides an APIand runtime environment for developing and running enterprise software , including network and web services ,and other large-scale, multitiered, scalable, reliable, and secure network applications.

    – Java EE extends the Java Platform, Standard Edition(Java SE),providing an API for objectrelational mapping , distributedand multi-tier architectures, and web services .The platform incorporates a design based largely on modular componentsrunning on an application server .

Java Platform, Standard Edition(J2SE) :_

    – Java SE is a widely used platformdevelopment and deployment of portable applicationsfor desktop and server environments.

    – Java SE uses the object-oriented Java programming language. Java SE is a platform specification. It defines a wide range of general purpose APIssuch as Java APIsfor the Java Class Library

Summary: J2ME is designed for mobile phones and set top boxes.J2EE extends J2SE and designed for developing an enterprise software .J2SE is used for developing and deploying Desktop applications

___________________________________________________________________________________

JDK,JVM,JRE

JDK :-

        The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or Java ME platforms released by Oracle Corporationin the form of a binary product aimed at Javadevelopers on Solaris, Linux, Mac OS or Windows. Since the introduction of the Javaplatform, it has been by far the most widely used Software Development Kit (SDK) On 17 November 2006, Sun announced that it would be released under the GNU General Public License (GPL), thus making it free software. This happened in large part on 8 May 2007, when Sun contributed the source code to the OpenJDK.


JVM :-

        JVM stands for Java Virtual Machine.

         All language compilers translate source code into machine code for a specific computer. Java compiler also does the same thing.

         Java compiler produces an intermediate code known as byte code for a machine that does not exist.

         This machine is called the Java Virtual Machine and it exists only inside the computer memory.


     The virtual machine code (Byte Code) is not machine specific.
     The machine specific code is generated by the Java Interpreter by acting as an intermediary between the virtual machine and the real machine as shown in fig. Interpreter is different for different machine.



JRE :-

        The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development Kit (JDK), a set of programming tools for developing Java applications. The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.

Summary: JDK is implementing a J2SE ,J2EE or J2ME and uses Standard Development Kit(SDK) for developing softwares.JVM is used to convert java code into byte code and that byte code is convert into machine code and byte code can run anywhere.JRE is a runtime environment provided for developing java applications.

___________________________________________________________________________________

Explain JDK and its components.

        JDK stands for Java Development Kit.

         It is a collection of tools which are used for developing and running the java program.

Components:-

    1) Appletviewer :- it used to view the java applets without using the browser.

    2) Javac :- the java compiler translate source code to byte code.

    3) Java :- java interpreter runs the applets and application by reading the byte code.

    4) Javadoc :- it creates html format documentation from java source code.

    5) Javah :- it produce header file.

    6) Javap :- it enables to convert byte code into program description.

    7) Jdb :- it is java debugger used for find errors from the programs.

Summary: JDK is used for develoing a java program by using components like appletviewer and javadoc,jdb,javah,javap

___________________________________________________________________________________

BASIC JAVA PROGRAM

HelloWorld.java - the source code for the "Hello, world!" program

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

        }

}

How to save :-

        To run this program, save it in a file with the name HelloWorld.java. It must be sure that the file name must match the name of the class.

Compile the program :-

        javac HelloWorld.java command is used to compile the source code.

        When you compile the program you'll create a byte-code file named HelloWorld.class. You can confirm this with the dir command in the DOS/Windows world.

Execute the byte code :- 

        Now you can execute the byte code in the Java interpreter with this command: java HelloWorld

Output of the program :-

        When you run the program at the command line, you'll see this output Hello, world!

Understanding the HelloWorld.java code :-

        Let's examine the HelloWorld.java file. Class is the basic building block of the java program, java codes are written in the java class.

___________________________________________________________________________________

JAVA IDE

NetBeans :-

        NetBeans is an integrated development environment (IDE) for developing primarily with Java, but also with other languages, in particular PHP, C/C++, and HTML5 .It is also an application platform framework for Java desktop applications and others.

        The NetBeans IDE is written in Java and can run on Windows, OS X, Linux, Solaris and other platforms supporting a compatible JVM.

        The NetBeans Platform allows applications to be developed from a set of modular software components called modules. Applications based on the NetBeans Platform (including the NetBeans IDE itself) can be extended by third party developers.

        NetBeans IDE is an open-source integrated development environment. NetBeans IDE supports development of all Java application types (Java SE (including JavaFX), Java ME, web, EJB and mobile applications).

Eclipse :-





            Eclipse is an Integrated development environment (IDE). It started in 2001, when IBM released Eclipse into open source. It contains a base workspace and an extensible plug-in system for customizing the environment. Written mostly in Java, Eclipse can be used to develop applications in Java. By means of various plug-ins, Eclipse may also be used to develop applications in other programming languages: Ada, C, C++, COBOL, Fortran, Haskell, JavaScript, Lasso, Perl, PHP, Python, R, Ruby (including Ruby on Rails framework), Scala, Clojure, Groovy, Scheme, and Erlang. It can also be used to develop packages for the software Mathematica. Development environments include the Eclipse Java development tools (JDT) for Java and Scala, Eclipse CDT for C/C++ and Eclipse PDT for PHP, among others.

        The Eclipse software development kit (SDK), which includes the Java development tools, is meant for Java developers. Users can extend its abilities by installing plug-ins written for the Eclipse Platform, such as development toolkits for other programming languages, and can write and contribute their own plug-in modules.

Summary: Netbeans an declipse are IDE designed for developing a java application as well as PHP,C/C++,Ruby,and Android .IDE provides GUI support for the beginners to develop an effective application.

___________________________________________________________________________________

Datatype

        Every variable has a type, every expression has a type, and every type is strictly defined.

         All assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility.

         There are no automatic coercions or conversions of conflicting types as in some languages.

         The java compiler checks all expressions and parameters to ensure that the types are compatible.

         There are two types of data types

                o Primitive types

                o Non primitive types

Primitive Types :-

         Java provides eight primitive types of data:

        1. Byte, 2. Short, 3. Int, 4. Long, 5. Char, 6. Float, 7. Double, 8. Boolean

         The primitive types are also commonly referred to as simple types.

         These can be put in four groups:

            =>Integer

            =>Floating-point numbers

            =>Characters

            =>Boolean

    Integer :-

         Java provides four integer types: byte, short, int, long.

         All of these are signed, positive and negative values.

                Type         Size/bits         Range

                Byte               8              -128 to 127

                Short             16             -32,768 to 32,767

                Int                 32             -2,147,483,648 to 2,147,483,647

                Long             64             -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating-Point Types :-

        Floating-Point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision.

        For example, calculations such as square root, or transcendental such as sine and cosine, result in a value whose precision requires a floating-point type.

         There are two kinds of floating-point types, float and double, which represent single and double-precision numbers, respectively.

                Type         Size/bytes         Range

                Float         32                     1.4e – 045 to 3.4e + 038

                Double      64                     4.9e - 324 to 1.8e + 308

Character :-

        The data type used to store characters is char.

                Type         Size/bytes         Range

                Char             16                 0 to 65,536

Boolean :-

        Java has primitive type, called boolean, for logical values.

         It can have only one of two possible values, true or false.

                Type         Size/bytes         Range

                Boolean         1                 True/False , Yes/No , 0/1

Summary: Java has 8 primitive typeByte,Short,Int ,Long,Char,Float,Double,Boolean and Non Premitive Types like Array in Java.(Trick:According to size…. BBSCIFDL)

Variable :-

        The variable is the basic unit of storage in a java program.

         A variable is defined by the combination of identifiers, a type and an optional initialize.

         All variables have a scope, which defines their visibility and a life time.

Declaring a Variable: -

        All variables must be declared before they can be used. The basic form of a variable declaration is shown here.

Type identifier [= value] [, identifier [=value]...];

int a,b,c; // declare 3 integers

Byte z = 22; // initialize z

Char x = ‘X’; // the variable x has the value ‘X’

Dynamic Initialization:

        Java allows variables to be initialized dynamically using any valid expression at the time the variable is declared.

Example:

class DynamicInt

{

        public static void main(String args[])

        {

                double a= 3.0, b= 5.0;

                // c is dynamically initialized

                double c = Math.sqrt (a * a+b * b);

                System.out.println(“The value of C is: - “ + c);

        }

}

        In above example method sqrt (), is the member of the Math class.

The Scope & Lifetime of Variable

        All the variables used have been declared at the start of the main () method. Java allows variables to be declared within any block.

        A block defines a scope. Thus, each time you start a new block, you are creating a new scope.

        A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.

        Many other computer languages define two general categories of scopes: Global and Local. In java, the two major scopes are those defined by a class and those defined by method.

        As a general rule, variables declared inside a scope are not visible (accessible) to code that is defined outside that scope.

        Thus, when you declare a variable within a scope you are localizing that variable and the scope rules provide the foundation for encapsulation.

        Scopes can be nested. For example, each time you create a block of code, you are creating a new rested scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.

        To understand the effect of nested scopes consider the following program.

class Scope

{

        public static void main(String args[])

        {

                int x;

                x = 10; // known to all code within main

                if (x == 10)

                {

                            int y =20; // known to only this block

                            system.out.println (“x and y: - “+ x+” “+y);

                            x = y*2;

                }

                y = 100; // error y is not known here

                system.out.println (“x is “+x);

        }

}

         Variables are created when their scope is entered and destroyed when their scope is left.

         This means that a variable will not hold its value once it has gone out of scope.

         Therefore, variables declared within a method will not hold their values between calls to that method.

         A variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.    

         If a variable declaration includes an initializer then that variable will be reinitialized each time the block in which it is declared is entered

         For example, consider the next program.

// demonstrate lifetime of a variable

class LifeTime

{

        public static void main (String args[])

        {

                int x;

                for (x=0 ; x< 3 ; x++)

                { //y is initialized each time block is entered.

                            int y = -1;

                            system.out.println (“Y is: - “+y);

                            y = 100;

                            system.out.println (“Y is now: -“+ y);

                }

        }

}

___________________________________________________________________________________

Tokens

        Java Tokens:- A java Program is made up of Classes and Methods and in the Methods are the Container of the various Statements And a Statement is made up of Variables, Constants, operators etc .

        Tokens are the various Java program elements which are identified by the compiler. A token is the smallest element of a program that is meaningful to the compiler. Tokens supported in Java include keywords, variables, constants, special characters, operations etc.

            When you compile a program, the compiler scans the text in your source code and extracts individual tokens. While tokenizing the source file, the compiler recognizes and subsequently removes whitespaces (spaces, tabs, newline and form feeds) and the text enclosed within comments. Now let us consider a program

//Print Hello

Public class Hello

{

        Public static void main(String args[])

        {

                System.out.println(“Hello Java”);

        }

}

        The source code contains tokens such as public, class, Hello, {, public, static, void, main, (, String, [], args, {, System, out, println, (, "Hello Java", }, }. The resulting tokens· are compiled into Java bytecodes that is capable of being run from within an interpreted java environment. Token are useful for compiler to detect errors. When tokens are not arranged in a particular sequence, the compiler generates an error message.

            Tokens are the smallest unit of Program

There is Five Types of Tokens

(1) ReserveWordorKeywords

(2) Identifier

(3) Literals

(4) Operators

(5) Separators

Summary: Tokens are the smallest unit of Program .tokens are used to detect errors and five types of tokens are used like reserve word/keyword,identifier,literals,operator and separators.

___________________________________________________________________________________

Operator

        An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

         Operators are used in programs to manipulate data and variables.

         Java operators can be classified into a number of related categories as below:

        1. Arithmetic operator, 2. Relational operator, 3. Logical operator, 4. Assignment operators, 5. Increment and decrement operator, 6. Conditional operators, 7. Bitwise operators, 8. Special operators

Arithmetic operator

        Java provides all the basic arithmetic operators.

                Operator        Meaning

                    +                 Addition or unary plus

                    -                 Subtraction or unary minus

                    *                 Multiplication

                    /                  Division

                   %                 Modulo division

1. Integer Arithmetic

        When both the operands in a single arithmetic expression such as a+b are integers, the expression is called an integer expression, and the operation is called integer arithmetic.

         Integer arithmetic always yields an integer value.

         If we have a=14 and b=4 then

                o a+b=18

                o a-b=10

                o a*b=56

                o a/b=3 (decimal part truncated)

                o a%b=2 (remainder of integer division)

         For modulo division, the sign of the result is always the sign of the first operand.

                o -14%3 = -2

                -14%-3 = -2

                14%3 = 2

2. Real Arithmetic

        An arithmetic operation involving only real operands is called real arithmetic.

         A real operand may assume values either in decimal or exponential notation.

         Modulus operator % can be applied to the floating point data as well.

class FloatArith

{

        public static void main(String args[])

        {

                float a=20.5f,b=6.4f;

                System.out.println("a="+a);

                System.out.println("b="+b);

                System.out.println("a+b="+(a+b));

                System.out.println("a-b="+(a-b));

                System.out.println("a*b="+(a*b));

                System.out.println("a/b="+(a/b));

                System.out.println("a%b="+(a%b));

        }

}

3. Mixed-mode Arithmetic

        When one of the operands is real and the other is integer, the expression is called a mixed-mode arithmetic expression.

         If either operand is of the real type, then the other operand is converted to real and the real arithmetic is performed. The result will be a real.

                o 15/10.0 = 1.5

                o 15/10 = 1

Relational Operator

        For comparing two quantities, and depending on their relation, we take certain decision.

         For example, we may compare the age of two persons, or the price of two items, and so on. These comparison can be done with the help of relational operators.

                Operator         Meaning

                <                         is less than

                <=                       is less than or equal to

                >                         is greater than

                >=                       is greater than or equal to

                ==                       is equal to

                !=                        is not equal to

class Relational

{

        public static void main(String args[])

        {

                float a=15.0f,b=20.75f,c=15.0f;

                System.out.println("a="+a);

                System.out.println("b="+b);

                System.out.println("c="+c);

                System.out.println("a<b is "+(a<b));

                System.out.println("a>b is "+(a>b));

                System.out.println("a==c is "+(a==c));

                System.out.println("a<=c is "+(a<=c));

                System.out.println("a>=b is "+(a>=b));

                System.out.println("b!=c is "+(b!=c));

                System.out.println("b==a+c is "+(b==a+c));

        }

}

Logical Operator

        Java has three logical operators:

                    Operator        Meaning

                    &&                 logical AND

                    ||                     logical OR

                    !                     Logical NOT

class Logic

{

        public static void main(String args[])

        {

                int a=15,b=30,c=15,d=30;

                if (a==c && b==d)

                        System.out.println("Equal");

                else

                        System.out.println("Not Equal");

                if (a<b || a<c)

                        System.out.println("a is smaller than any other values");

                else

                        System.out.println("a is greater than any other values");

                if(a!=b)

                        System.out.println("the value of a and b are not equal");

                Else

                        System.out.println("The value of a and b are equal");

        }

}

Assignment Operator :-

        Assignment operators are used to assign the value of an expression to a variable.

         Java has a set of ‘shorthand’ assignment operators which are used in the form

         var-name op= exp;

                o which is equivalent to

         var-name=var-name op (exp);

         For the statement:

                o x=x+(y+1);

                o x+=y+1;

        Statement with Simple assignment operators             Statement with Shorthand operator

        a=a+1                                                                                     a+=1

        a=a*1                                                                                     a*=1

        a=a*(n+1)                                                                              a*=n+1

        a=a/(n+1)                                                                              a/=n+1

        a=a%b                                                                                   a%=b

Increment and Decrement Operator :-

        java has two increment and decrement operators:

                o ++ and - -

         The operator ++ adds 1 to the operand while - - subtracts 1. both are used in the following format:

        o ++m; or m++;

        o --m or m--;

Where:

        ++m is equivalent to m=m+1;

        -- m is equivalent to m=m-1;

class Increment

{

        public static void main(String args[])

        {

                int m=10, n=20;

                System.out.println("m=" + m);

                System.out.println("n=" + n);

                System.out.println("++m=" + ++m);

                System.out.println("n++" + n++);

                System.out.println("m=" + m);

                System.out.println("n=" + n);

        }

}

Conditional Operator :-

        The character pair ? : is a ternary operator available in java. This operator is used to construct conditional expressions of the form

                Exp1 ? Exp2: Exp3

         Consider the following example:

                o a=10;

                o b=15;

                o x=(a>b) ? a: b;

        It is same as:

                if (a>b)

                        x=a;

               else

                        x=b;

import java.util.Random;

class Condition

{

        public static void main(String args[])

        {

                Random random= new Random();

                float x= random.nextFloat();

                System.out.println("x=" +x);

                float y= random.nextFloat();

                System.out.println("y=" +y);

                float min=(x<y ? x : y);

                float max=(x>y ? x : y);

                System.out.println("min="+min);

                System.out.println("max="+max);

        }

}

Bitwise Operators :-

        Java has a distinction of supporting special operators known as bitwise operators for manipulation of data at values of bit level.

         These operators are used for testing the bits, or shifting them to the right or left.

         Bitwise operators may not be applied to float or double.

                Operator        Meaning

                        &             bitwise AND

                        !               Bitwise OR

                        ^               Bitwise exclusive OR

                        ~               one’s complement

                        <<            shift left

                        >>             shift right

Logical Bitwise Operations

                    bit 1     bit 2     OR (|)     AND (&)     XOR (^)

                        0         0             0             0                 0

                        1         0             1             0                 1

                        0         1             1             0                 1

                        1         1             1             1                 0

Special Operator :-

        Java supports some special operators of interest such as instanceof operator and member selection operator(.)

Instanceof Operator

        the instanceof is an object reference operator and returns true if the object on the left-hand side is an instance of the class given on the right-hand side. This operator allows us to determine whether the object belongs to a particular class or not.

         For example:

                person instanceof studentis true if the object person belongs to the class student; otherwise it is false.

Dot operator :_

        The dot operator(.) is used to access the instance variables and methods of class objects.

         For example:

                o person1.age //reference to the variable age

                o person1.salary() //reference to the method salary()

         It is used to access classes and sub-packages form a package.

Summary : Operators are used in programs to manipulate data and variables.operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.Arithmetic operator is used to perform arithmetic operation and comparing two quantities, and depending on their relation, we take certain decision.Assignment operators are used to assign the value of an expression to a variable. Increment and Decrement operator is used to increment and decrement the value of a variable.Dot operator is used to access the instance variable and methods of class objects.

___________________________________________________________________________________

Type Casting

        It is common to assign a value of one type to a variable of another type.

        If the two types are compatible then java will perform the conversion automatically. For example it is possible to assign an integer value to a long variable.

        However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For example there is no conversion defined from double to byte

        It is still possible to obtain a conversion between incompatible types.

        For that you must use a cast, which performs an explicit conversion between incompatible types.

Java’s Automatic Type Conversion :-

        When one type of data is assign to another type of variable, an automatic type conversion will take place if the following two conditions are met:

        o The Two types are compatible.

        o The destination type is larger than the source type.


        The int type is always large to hold all valid byte values. So no explicit cast statement is required.

        For widening conversions, the numeric types, including integer and floating-point types are not compatible with each other.

        However, numeric types are not compatible with char or Boolean. Char and Boolean data types are not compatible with each other.

        Java performs an automatic type conversion when storing a literal integer constant into variables of type byte, short or long.

Casting Incompatible Types :-

        Automatic type conversion will not fulfill all needs. For example if you want to assign an int value to a byte variable?

        This conversion will not be performed automatically, because a byte is smaller than int.

        This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type.

        To create conversion between two incompatible types, you must use a cast.

        A cast is an explicit type conversion. It has this general form: (target-type) value

        Here target-type specifies the desired type to convert the specified value to:

        For example, The following fragment casts an int to a byte. If the integer’s value is larger then the range of byte, it will be reduced modules (the reminder of an integer divisionby the) byte’s range.

                                            int a;

                                            byte b;

                                            b = (byte) a;

        A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation.

        Integers do not have fractional components. Thus, when a floating-point value is assigned to an integer type, the fractional component is lost.

        For example, if the value 1.23 is assigned to an integer, the resulting value will simply be

                            1. The 0.23 will have been truncated.


        If the size of the whole number component is too large to fit into the target integer type, then that value will be reduced modulo the target type’s range.

// demonstrate casts

class conversion

{

        public static void main (String args[])

        {

                byte b;

                int i = 257;

                double d = 323.142;

                System.out.println (“Conversion of int to byte: -”);

                b = (byte) i;

                System.out.println (“i and b: -“+i+” “+b);

                System.out.println (“\n Conversion of double to int: -”);

                i = (int) d;

                System.out.println (“d and i: -“+d+” “+i);

               System.out.println (“\n Conversion of double to byte: -”);

                b = (byte) d;

                System.out.println (“d and b: -“+d+” “+b);

        }

}

Summary: It is common to assign a value of one type to a variable of another type. If the two types are compatible then java will perform the conversion automatically. For example it is possible to assign an integer value to a long variable.if we want to assign an int value to a byte variable.This conversion will not be performed automatically, because a byte is smaller than int.This kind of conversion is sometimes called a narrowing conversion.

___________________________________________________________________________________

Decision Statement

        There are two types of decision making statements in Java. They are:

                - if statements

                - switch statements

The if Statement:

        An if statement consists of a Boolean expression followed by one or more statements.

    Syntax:

        The syntax of an if statement is:

        if(Boolean_expression)

        {

                //Statements will execute if the Boolean expression is true

        }

        If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Example:

class Test{

        public static void main(String args[])

        {

                int x =10;

                if( x <20)

                {

                        System.out.print("This is if statement");

                }

        }

}

This would produce the following result:

This is if statement

                                                                           __________

The if...else Statement:

        An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:

        The syntax of an if...else is:

        if(Boolean_expression){

                //Executes when the Boolean expression is true

        }else{

                //Executes when the Boolean expression is false

        }

Example:

publicclassTest

{

        publicstaticvoid main(String args[])

        {

                int x =30;

                if( x <20)

                {

                        System.out.print("This is if statement");

                }else{

                        System.out.print("This is else statement");

                }

        }

}

This would produce the following result:

This is else statement

                                                                           __________

The if...else if...else Statement:

        An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if , else if , else statements there are few points to keep in mind.

     An if can have zero or one else's and it must come after any else if's.

     An if can have zero to many else if's and they must come before the else.

     Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

        The syntax of an if...else is:

        if(Boolean_expression1){

                //Executes when the Boolean expression 1 is true

        }elseif(Boolean_expression2){

                //Executes when the Boolean expression 2 is true

        }elseif(Boolean_expression3){

                //Executes when the Boolean expression 3 is true

        }else{

                //Executes when the none of the above condition is true.

        }

Example:

public class Test{

        public static void main(String args[]){

                int x =30;\

                if( x ==10){

                        System.out.print("Value of X is 10");

                }elseif( x ==20){

                        System.out.print("Value of X is 20");

                }elseif( x ==30){

                        System.out.print("Value of X is 30");

                }else{

                        System.out.print("This is else statement");

                }

        }

}

This would produce the following result:

        Value of X is30

                                                                           __________

Nested if...else Statement:

        It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

Syntax:

        The syntax for a nested if...else is as follows:

        if(Boolean_expression1){

                //Executes when the Boolean expression 1 is true

        if(Boolean_expression2){

                //Executes when the Boolean expression 2 is true

        }

}

You can nest else if...else in the similar way as we have nested if statement.

Example:

public class Test{

        public static void main(String args[]){

                int x =30;

                int y =10;

                if( x ==30){

                        if( y ==10){

                                System.out.print("X = 30 and Y = 10");

                        }

                }

        }

}

This would produce the following result:

X =30and Y =10

                                                                           __________

The switch Statement:

        A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

    The syntax of enhanced for loop is:

switch(expression){

        case value :

                //Statements

                break;//optional

        case value :

                //Statements

                break;//optional

                //You can have any number of case statements.

        default://Optional

                //Statements

    }

The following rules apply to a switch statement:

     The variable used in a switch statement can only be a byte, short, int, or char.

     You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

     The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.

     When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

     When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

     Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

     A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.

    No break is needed in the default case.

Example:

public class Test{

        public static void main(String args[]){

                //char grade = args[0].charAt(0);

                char grade ='C';

                switch(grade)

                {

                        case'A':

                                System.out.println("Excellent!");

                                break;

                        case'B':

                        case'C':

                                System.out.println("Well done");

                                break;

                        case'D':

                                System.out.println("You passed");

                        case'F':

                                System.out.println("Better try again");

                                break;

                        default:

                                System.out.println("Invalid grade");

                }

                System.out.println("Your grade is "+ grade);

        }

}

        Compile and run above program using various command line arguments. This would produce the following result:

$ java Test

Welldone

Your grade is a C

$

Summary: Decision statement are used to make decision from the given number of statements. if satisfies the conditions It returns true else return false.

___________________________________________________________________________________

Looping Statement

        There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.

        Java has very flexible three looping mechanisms. You can use one of the following three loops:

             while Loop

             do...while Loop

             for Loop

        As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:

        A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

        The syntax of a while loop is:

while(Boolean_expression)

{

        //Statements

}

        When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

        Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

public class Test{

        public static void main(String args[]){

                int x =10;

                while( x <20){

                        System.out.print("value of x : "+ x );

                        x++;

                        System.out.print("\n");

                }

        }

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19


The do...while Loop:

        A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

        The syntax of a do...while loop is:

do

{

        //Statements

}while(Boolean_expression);

        Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

        If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test{

        public static void main(String args[]){

                int x =10;

                do{

                        System.out.print("value of x : "+ x );

                        x++;

                        System.out.print("\n");

                }while( x <20);

        }

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19


The for Loop:

        A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

        A for loop is useful when you know how many times a task is to be repeated.

Syntax:

        The syntax of a for loop is:

for(initialization;Boolean_expression; update)

{

        //Statements

}

Here is the flow of control in a for loop:

         The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

         Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

         After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

         The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:

public class Test{

        public static void main(String args[]){

                for(int x =10; x <20; x = x+1){

                        System.out.print("value of x : "+ x );

                        System.out.print("\n");

                }

        }

}

This would produce the following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19


Enhanced for loop in Java:

        As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:

        The syntax of enhanced for loop is:

for(declaration : expression)

{

        //Statements

}

Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class Test{

        public static void main(String args[]){

                int[] numbers ={10,20,30,40,50};

                for(int x : numbers ){

                        System.out.print( x );

                        System.out.print(",");

                }

                System.out.print("\n");

                String[] names ={"James","Larry","Tom","Lacy"};

                for(String name : names ){

                        System.out.print( name );

                        System.out.print(",");

                }

        }

}

This would produce the following result:

10,20,30,40,50,

James,Larry,Tom,Lacy,

Summary: Loop is usedto execute a block of code several number of times .A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.For loop is used to execute a block of code for N times.

___________________________________________________________________________________

JUMPING STATEMENT

        There are three jump statements in java:

            break

            continue

            return

        These statements transfer control to another part of your program. The break statements have three uses, they are:

- It determines a statement sequence in a switch statement.

- It can be used to exit a loop

- It is another form of goto.


The break Keyword:

        The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.

        The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

        The syntax of a break is a single statement inside any loop:

                break;

Example:

public class Test{

        public static void main(String args[]){

                int[] numbers ={10,20,30,40,50};

                for(int x : numbers ){

                        if( x ==30){

                                break;

                        }

                        System.out.print( x );

                        System.out.print("\n");

                }

        }

}

This would produce the following result:

10

20


The continue Keyword:

        The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

        In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

        In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:

        The syntax of a continue is a single statement inside any loop:

            continue;

Example:

public class Test{

        public static void main(String args[]){

                int[] numbers ={10,20,30,40,50};

                        for(int x : numbers ){

                                if( x ==30){

                                        continue;

                                }

                                System.out.print( x );

                                System.out.print("\n");

                        }

                }

        }

This would produce the following result:

10

20

40

50

The following example illustrates the use of break to exit a loop.

class BrDemoAppl

{

        public static void main(String args[])

                for (int count = 1; count <= 100; count++)

                {    

                        if (count == 10)

                                break;

                        System.out.println("The value of num is : " + count);

                }

                System.out.println("The loop is over");

        }

}

        The for loop is designed to run for 100 times but it determines when the value of count is equal to 10 by calling thebreak statement.

The output for the program is:

        When used inside a nested loop, the break statement will only break out of the innermost loop. It must be noted that the break statement should be used only to cancel a loop when some sort of special situation occurs. Sometimes a programmer might want to continue the loop, but stop processing the remainder of the code in its body for a particular iteration. The continue statementperforms such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.

The following code uses continue in the code:

class ContDemo

{

        public static void main(String args[])

        {

                for (int count = 1; count <= 10; count++)

                {

                        System.out.print(count + " ");

                                if (count % 2 ==0)

                                        continue;

                                System.out.println("");

                }

        }

}

The output of the above program is:

        The above example uses % operator to check if count is even or not depending on the value in remainder which should be 0. If it is, the loop continues without printing a new line. The return statement is used to explicitly return from a method. This causes the program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it is executed.

___________________________________________________________________________________

Arrays

         An array is a group of like-typed variables that are referred by a common name.

        Arrays of any type can be created and may have one or more dimensions.

    A specific element in an array is accessed by its index.

    Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays

        A one-dimensional array is a list of like typed variables.

        To create an array, you first must create an array variable of the desired type.

        The general form of a one-dimensional array declaration is:

        type var-name[ ];

        int month_days[ ];

        The value of month_days is set to null, which represents an array with no value. To link month_days with an actual, physical array of integers, you must first allocate one using new and assign it to month_days.

         new is special character which allocates memory.

        The general form of new as it applies to one-dimensional arrays appears as follows:

                    array-var=newtype[size];

        Following example allocates a 12-element array of integers and line them to month_days.

month_days=newint[12];

after this statement executes, month_days will refer to an array of 12 integers.

In short, obtaining an array is a two step process.

    1. you must declare a variable of the desired array type.

    2. you must allocate the memory that will hold the array, using new, and assign it to the array variable.

class Array

{

        public static void main(String args[])

        {

                int month_days[ ];

                month_days= new int[12];

                month_days[0]=31;

                month_days[1]=28;

                month_days[2]=31

                month_days[3]=30

                month_days[4]=31

                month_days[5]=30

                month_days[6]=31

                month_days[7]=31;

                month_days[8]=30;

                month_days[9]=31;

                month_days[10]=30;

                month_days[11]=31;

                System.out.println (“April has” + month_days[3] + “days.”);

        }

}

        it is possible to combine the declaration of the array variable with the allocation of the array itself, as shown here:

        o int month_days[ ]=new int[12];

    Arrays can be initialized when they are declared.

        An array initializer is a list of comma-separated expressions surrounded by curly braces. The comma separates the values of the array elements.

        The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new.

For example,

Class AutoArray

{

        public static void main (String args[ ])

        {

                int month_days[]={31,28,31,30,31,30,31,31,30,31,30,31};

                System.out.println(“April has” + month_days[3] + “days.”);

        }

}


Multidimensional Arrays

        Multidimensional arrays are actually arrays of arrays.

        To declare a multidimensional array variable, specify each additional index using another set of square brackets.

        For example, following declares two dimensional array:

                o int twoD[ ] [ ] = new int [4] [5];

        This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

Alternative Array Declaration

        There is a second form that may be used to declare an array:

                type[ ] var-name;

        The square brackets follow the type specifier, and not the name of the array variable.

        For example, the following two declarations are equivalent:

            int a1[ ] = new int[4];

            int [ ] a1= new int[4];

            char twod [ ] [ ] = new char [3] [4];

            char [ ] [ ] twod = new char [3] [4];


        This alternative declaration form offers convenience when declaring several arrays at the same time. For example,

         int [ ] nums1, nums2, nums3;

         This creates 3 array variables of int type.

Summary: An array is a group of like-typed variables that are referred by a common name.A specific element in an array is accessed by its index.Array can be of two type one dimentional and two dimentional .

In 1 Dimenntional array

    month_days=newint[12];

        after this statement executes, month_days will refer to an array of 12 integers. obtaining an array is a two step process.

        1. you must declare a variable of the desired array type.

        2. you must allocate the memory that will hold the array, using new, and assign it to the array variable.

o int twoD[ ] [ ] = new int [4] [5];

    This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

___________________________________________________________________________________

Command-Line Arguments

        A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter:

        java Sort friends.txt

        

        When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the commandline arguments passed to the Sort application in an array that contains a single String: "friends.txt".

Echoing Command-Line Arguments

        The Echo example displays each of its command-line arguments on a line by itself:

public class Echo {

        public static void main (String[] args) {

                for (String s: args) {

                        System.out.println(s);

                }

        }

}

        The following example shows how a user might run Echo. User input is in italics.

java Echo Drink Hot Java

Drink

Hot

Java


        Note that the application displays each word — Drink, Hot, and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink, Hot, and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

java Echo "Drink Hot Java"

Drink Hot Java


Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String

argument that represents a number, such as "34", to a numeric value. Here is a code snippet

that converts a command-line argument to an int:

int firstArg;

if (args.length > 0) {

        try {

                   firstArg = Integer.parseInt(args[0]);

        } catch (NumberFormatException e) {

        System.err.println("Argument" + " must be an integer");

        System.exit(1);

        }

}

        parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number classes

— Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type.

Summary: A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.Like java filename clr1 cla2 cla3

___________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

1 comment: