Java and its features Major difference between C++ and Java Java Environment Data types Java Tokens Casting Control Flow Statements Object Oriented Concepts Thegeneral conceptsof OOP whichformtheheart of Java language Thevariousconceptsare: EncapsulationandDataAbstraction Inheritance Polymorphism Encapsulation and Data Abstraction Thewrappingupof dataandmethodsintoasingleunit(called class) isknownasencapsulation.. Abstractionrefersto theact of representingessential features of an entity. Theseencapsulateall theessential properties of theobjectsthat aretobecreated. Inheritance Thisistheprocessbywhichobjectsof oneclasscanacquire thepropertiesof objectsof another class. Theconcept of inheritanceprovidestheideaof code reusability. Polymorphism Polymorphism means the ability to take more than one form. Polymorphism is mainly of two types. 1. Run Time 2. Compile Time Run time polymorphism means function call is resolved at run time. Compile Time polymorphism means function call is resolved at Compiletime. The features of Java Simple Platform Independent Robust and Secure Multithreaded Compiled and Interpreted Distributed Simple Javaissimplelanguageif wearefamiliar withthebasic conceptsof object-orientedprogramming(OOP). JavainheritsC/ C++syntaxandmanyof the object-orientedfeaturesof C++. Platform Independent Javaensuresportabilityintwoways. First Javacompiler generatesbytecodeinstructionsthat canbeimplementedon anymachine. Secondlythesizeof theprimitivedatatypeismachine- independent. Themost significant contributionof Javaisitsportability. Javaprogramscanbeeasilymovedfromonecomputer system toanother. Robust and Secure Javaisarobust language. It providesmanysafeguardsto ensurereliablecode. It hasstrict compiletimeandruntimecheckingfor datatypes. Javaalsoincorporatestheconcept of exceptionhandling whichcapturesserieserrorsandeliminatesanyriskof crashingsystem. Multithreaded Multithreadedmeanshandlingmultipletaskssimultaneously. Javasupportsmultithreadedprograms. Thismeansthat weneed not wait for theapplicationtofinishonetaskbeforebeginning another. Compiled and Interpreted Java is both compiled and interpret language. Java compiler translates source code into bytecode instructions. Java interpreter generates machine code Distributed Java supports for creating distributed applications over network Java applications can open and access remote objects on internet as easily as they do in a local system. This enables multiple programmers at multiple remote locations to collaborate and work together on a single project. Major Differences Between C++ And Java Java does not support operator overloading Java does not have template classes as in C++ Java does not support multiple inheritances of classes. This is accomplished using a new feature called interface. Java does not support global variables. Every variable and method is declared within a class and forms part of that class. Java does not use pointers. Java has replaced the destructor function with a finalize() function. There are no header files in Java. The Java Environment Java environment includes a number of development tools and hundreds of classes and methods. The development tools are part of the system known as Java Development Kit (JDK). The classes and methods are part of Java Standard Library (JSL), also known as the Application Programming Interface (API). Java Development Kit TheJavaDevelopment Kit comeswithacollectionof tools that are used for developing and running Java programs. Theyinclude: appletviewer (for viewingapplets) javac(JavaCompiler) java(Javainterpreter) javap(javadisassembler) javah( for Cheader files) javadoc(for creatingHTML documents) jdb(Javadebugger) Application Programming Interface The Java standard library (or API) includes several packages. Most commonly used packages are Language Support Package Utilities Package Input / Output Package: Networking Package AWT Package Applet Package Java Language An Overview Javais ageneral-purpose, object-oriented programming language. Wecandeveloptwotypesof JavaPrograms Stand-aloneapplications Webapplets Stand-alone applications Stand-aloneapplications areprograms written in Javato carry out certaintasksonastandalonelocal computer. Example1.1 Data Types Datatypesdefinethe storagemethodsavailablefor representinginformation. Javadatatypescanbedividedintotwocategories. simple composite. Javas Primitive Data Types (Simple): Integer : This type includes byte, short, int and long. All these represent only whole numbers. Floating-point numbers : This type includes float and double. These numbers used to represent fractional numbers. Boolean : This type has Boolean. It is used to represent the true or false values. Characters : This type includes char. It is used to represent a character set or a symbol. Boolean : It represents true or false. It can hold only one value either true or false. These values cannot be changed from this type to any other type. These values are useful for comparison. These variables are declared by the keyword boolean. For example : boolean sign; Byte : The smallest integer type is byte. This type is useful for file handling and stream handling. These variables are declared by the keyword byte. For example : byte b; Char: It is used to represent characters. A char must be a single character of Unicode. Unicode is the superset of ASCII. It solves multi language problems. ASCII characters are 8 bit length. Unicode characters are 16 bit length For example : char ch; Short: It represents whole numbers of small length. These variables are declared by the keyword short. For example : short s; Int: It represents integer values or the whole numbers. These variables are declared by the keyword int. For example : int i; Long: It is usually used to represent values of higher range These variables are declared by the keyword long. For example : long al; Float: It represents floating point numerical values. These variables are very commonly used for decimal calculations. These variables are declared by the keyword float. For example : float fa; Double: It represents floating point numbers of larger orde. These variables are declared by the keyword double. For example : double currency; Java Tokens When a Java program is compiled, the Java compiler parses the text and extracts individual tokens These tokens define the structure of the Java language. All the tokens that comprise Java are known as the Java token set. Java tokens can be broken into five categories: Identifiers Keywords Literals Operators Seperators Identifiers: Identifiers are tokens that are used to represent user-defined names. These names can be assigned to variables, methods, and classes to uniquely identify them to the compiler. The following are valid identifiers: Keywords: Keywords are predefined identifiers reserved by Java. Data Declaration Keywords: Exp:boolean,byte,char,double Loop Keywords: Exp:while,break,for,do,continue Literals: Literals are the actual values stored by the variables (Identifiers). Literals can be numbers, characters, or strings. Numeric literals include integers, floating-point numbers, and booleans. There are many types of Literals: Integer literals Floating point literals Character literals Boolean literals String literals Example1.2 Operators The data items that operators act upon are called operands. Some operators require two operands, while others act upon only one operand. Most operators allow the individual operands to be expressions. A few operators permit only single variables as operands. Types of Operators Unary operators : Java supports a class of operators that act upon a single operand to produce a new value, Such operators are known as unary operators. For exp: -139 -A -( a + b) Relational Operators: There are six relational operators in Java. They are Less than(<) Less than or Equal to(<=) Greater than(>) Greater than or Equal to(>=) Equal to(==) Not Equal to(!=) Logical Operators Java supports three logical operators. They are AND (&&) OR(!!) NOT(!) Conditional Operator Simpleconditional operationscanbecarriedout withthe conditional operator(?:). Anexpressionthat makesuseof theconditional operator iscalleda conditional expression. Suchanexpressioncanbewritteninplaceof themoretraditional if-elsestatement. A conditional expressioniswrittenintheform expression1?expression2: expression3 For exp: max=(l >m) ?l : m; Assignment Operators There are different assignment operators in Java. All of them are used to form assignment expressions, which assign the value of an expression to an identifier. The most commonly used assignment operator is = Example : a = 10; b = 20; c = L; Arithmetic Assignment Operator There are arithmetic assignment operators corresponding to all the arithmetic operations: +=, -=, *=, / =, %= For Exp: The expression g += 5; Here 5 is added to the original value of the variable g, and the old value is replaced. Example 1.6 Bitwise Operators Javasupportscertainlowlevel featuresthat allowthe programmer tocarryout operationsnormallyavailableonlyin assemblylanguageor machinelanguage. Bitwiseoperationsoperatorscanbedividedintothreegeneral categories Theonescomplement operator Thelogical bitwiseoperators Theshift operators. The ones complement operator The ones complement operator (~) is a unary operator that causes the bits of its operand to be inverted For Ex: Binary equivalent of 8 = 0000 1000 Ones complement of 8 = 1111 0111 BitwiseComp The Shift Operators Theleft-shift, right-shift, andzero-fill-right-shift operators(<<, >>, and>>>) shift theindividual bitsof aninteger byaspecifiedinteger amount. Expression Value x = 7 x >> 2 1 x << 1 14 x >>> 1 3 The differences between the right-shift (>>) and zero-fill-right-shift (>>>) operators Theright-shift operator appearstoshift zerosintotheleftmost bits. Thereisnodifferencebetweenthetwooperatorswhiledealingwith positivenumbers, Theyboththeseoperatorsshift zerosintotheupper bitsof a number. Theright-shift operator preservesthehigh-order bit andeffectively shiftsthelower 31bitstotheright. Thisbehavior yieldsresultsfor negativenumberssimilar tothosefor positivenumbers. Thezero-fill-right-shiftoperator, ontheother hand, shiftszerosinto all theupper bits, includingthehigh-order bit Casting The process of converting one data type to another is called casting. Java allows automatic type conversions when it is manipulated with one or more operands. During arithmetic operations, numeric values of different types will be interoperable among themselves. casting Explicit casting To assign a value of higher bit data types to a lower one, it has to be explicitly said. It is called explicitcasting. expcast Control Flow Statements The Java language provides for three constructs for performing loop operations. They are: `The if statement `The for statement `The while statement `The do statement `The Switch statement if statement If statement is a conditional branch statement. It can be used to change the program execution thro different paths. The general form of if statement is If(condition) statement1; else Statement2; If the given condition is true then statement1 will be executed .If the condition is false statment2 will be executed. Example 1.6 The for statement This loop is an entry-controlled loop that provides a more concise loopcontrol structure The syntax of the For...next loop in Javais for ( n =1; n <100; n++) Example:1.13 The While Statement The while loop is used to repeat a block of code as long as a particular conditionistrue. Thesyntaxof thewhileloopinJavais while(condition) { blockof code } Example1.14 The do while statement The condition is placed at the end of the loop where it is used to specifywhentoexit theloop. The do while loop is very similar except that it executes a given statement until theconditionisfalse. Thisloopisexecutedatleast once. After thefirst iterationit checks for the condition, if it is true the loop is executed. The loop continuestill conditiongoes Example1.15 A break statement exits a loop before an entry condition fails. The most common use of break is in switch statements. Break Continue It is sometimes necessary to exit from the middle of a loop. Sometimes it may be necessary to go back to the top of the loop. Some other times it may be necessary to leave the loop completely. For these purposes Java provides the break and continue statements. Labeled Loops Normallyinsidenestedloopsbreakandcontinueexit theinnermost enclosingloop. For exampleconsider thefollowingloops. Example1.18 Switch statement Switch statements are shorthands for a certain kind of if statement. Example 1.20