Core java slides


Published on

  • More than 5000 IT Certified ( SAP,Oracle,Mainframe,Microsoft and IBM Technologies etc...)Consultants registered. Register for IT courses at Most of our companies will help you in processing H1B Visa, Work Permit and Job Placements
    Are you sure you want to  Yes  No
    Your message goes here
  • Turn into a Hadoop specialist. We offer a complete range of training classes that will give you the skills to get the most out of your product. Give power to your whole team. We have the right level of class to teach you the core comprehension you need to perform at your best. For more information send an email to For course Content and Recorded Demo Click Here:
    Are you sure you want to  Yes  No
    Your message goes here
  • Hi All, We are planning to start new devops online batch on this week... If any one interested to attend the demo please register in our website... For this batch we are also provide everyday recorded sessions with Materials. For more information feel free to contact us : For Course Content and Recorded Demo Click Here :
    Are you sure you want to  Yes  No
    Your message goes here
  • ios online training
    Are you sure you want to  Yes  No
    Your message goes here
  • Java: The Complete Reference, Ninth Edition ---
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Core java slides

  1. 1. JAVA FUNDAMENTALS History JDK and JRE Byte Code and JVM (Java Virtual Machine) Platform Independent Applications and Applets Principle of OOPs First Java Application
  2. 2. History of JavaJava is a General Purpose, Object Oriented Programming Languagedeveloped by Sun Microsystems of USA I 1991. Originally called Oak byGames Gosling, one of the invention of the language, java was designedfor the development of software for consumer electronic devices likeTVs, VCRs, toasters and such other electronic Machines.This goal had astrong impact on the development team to make the language simple,portable and highly reliable. The java team which included PatrickNaughton discovered that the existing languages like C and C++ hadlimitations in terms of both reliability and portability. However, theymodeled their new language Java on C and C++ but removed a numberof features of of C and C++ that were considered as source of problemsand thus made java really simple, reliable,portable and powerfullanguage.
  3. 3. Java Milestones :1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer electronic devices. A team of Sun Microsystems programmers headed by James Gosling was formed to undertake this task.1991 After exploring the possibility of most Object Oriented Programming Language C++, the team announced a new language named “Oak”.1992 The team, known as a Green Project team by Sun, demonstrated the application of their new language to control a list of home appliances using a hand-held device with a tiny touch sensitive screen.1993 The World Wide Web(WWW) appeared on the internet and transformed the text-based Internet into a Graphical-rich environment. The green Project team came up with the idea of developing Web Applets(tiny programs) using the new language that could run on all types of computers connected to Internet.1994 The team developed a web browser called “Hot Java” to locate and run applet programs on Internet. Hot Java demonstrated the power of the new language, thus making it instantly popular among the Internet users.1995 Oak was named “Java”, due to some legal snags. Java is just a name and is not an acronym. Many popular companies including Netscape and Microsoft announce to their support to Java.
  4. 4. 1996 Java established itself not only a leader for Internet Programming but also as a general-purpose, object oriented programming language. Java found its home.The most striking feature of the language is that it is a platform-neutral language.Java is a first programming language that is not tied to any particular hardware oroperating system.Features of Java :• Compiled and Interpreted.• Platform-Independent and Portable• Object-Oriented• Robust and Secure• Distributed• Familiar, Simple and Small• Multithreaded and Interactive• High Performance• Dynamic and Extensible
  5. 5. JDK & JREJava Environment includes a large number of development tools and hundreds of classes andmethods. The development tools are part of the system known as Java Development Kit (JDK)and the classes and methods are part of the Java Standard Library (JSL), also known as theApplication Programming Interface (API).JDK : Java Development Kit comes with a collection of tools that are used for developing and running Java Programs. They include :appletviewer-> Enables us to run Java Applets (Without using java compatible browser)Java Java Interpreter, which runs applets and applications by reading and interpreting bytecode files.Javac The Java compiler, which translates Java source code to byte code files that the interpreter understad.Javadoc Creates HTML-format documentation from Java source code files.Javah Produces header files for use with native methods.javap Java disassembler, which enables us to convert bytecode files into a program description.Jdb Java debugger, which helps us to find errors in our programs.
  6. 6. Byte Code & JVM(Java Virtual Machine)Since platform-independence is a defining characteristic of Java, it is important to understandhow it is achieved. Programs exist in two forms; source code and object code. Source Code isthe textual version of the program that you write using a text editor. The programs printed in abook are shown as source code. The executable form of a program is object code. The computercan execute object code. Typically, object code is specific to a particular CPU. Therefore, itcannot be executed on a different platform. Java removes this feature in a very elegant manner.Like all computer languages, a java program begins with its source code. The difference iswhat happens when a Java program is compiled. Instead of producing executable code, the JavaCompiler produces an object file that contains bytecode. Bytecodes are instructions that are notfor any specific CPU. Instead, they are designed to be interpreted by a Java Virtual Machine(JVM). The key to Java’s platform-independence comes from the fact that the same bytecodescan be executed by any JVM on any platform. As long as there is a JVM implemented for a agiven environment, it can run any Java program. For example, Java programs can execute underWindows 98,Solaris,IRIX, or any other platform for which a JVM can be implemented for thatplatform. This would then allow any Java program to execute in that new environment.
  7. 7. Platform IndependentCompilation is the process of converting the code that you type into a languagethat the computer understands-machine language. When you compile aprogram, the compiler checks for syntactical errors in code and lists all theerrors on the screen. You have to rectify the errors and recompile the programto get the machine language code. The Java compiler compiles the code tobytecode that is understood by the Java environment.The bytecode is the result of compiling a Java program. You can execute thiscode on any platform. In other words, due to the bytecode compilation processand interpretation by a browser, Java programs can be executed on a variety ofhardware and operating systems. The only requirement is that the systemshould have a java-enabled Internet browser.The java compiler is written inJava, and the interpreter is written in C. The Java Interpreter can execute JavaCode directly on any machine on which a Java interpreter has been installed.
  8. 8. Application and AppletsThere are two types of programs that can be built in Java Applications and applets.Applications can be directly executed by a JVM. In fact, Java can be used to developprograms for all kinds of applications, Hot Java itself is a Java Application program.Applets are small Java programs developed for Internet Applications. An applet locatedon distant computer (Server) can be downloaded via Internet and executed on a localcomputer (Client) using a Java enabled browser. We can develop applets for doingeverything from simple animated graphics to complex games and utilities. Since appletsare embedded in an HTML document and run inside a Web Page, creating and runningapplets are more complex than creating application. Stand alone program can read andwrite files and perform certain operations that applet can not do. An Applet can only runwithin a Web Browser. The Web browser includes a JVM that provides an executionenvironment for the applet. It is also possible to use a tool called the appletviewer torun an applet. This utility is included in the Java Development Kit(JDK) and is used totest applets. In this manner, an applet written by any developer in the world may bedynamically downloaded from the Web Server and executed on a client PC orworkstation.
  9. 9. Java Program Java Compiler Virtual Machine Source Code Bytecode Process of Compilation Bytecode Java Interpreter Machine CodeVirtual Machine Real Machine Process of Converting bytecode into machine code
  10. 10. Java Source Code Java Compiler Application TypeApplet Type Java Java Enabled Interpreter Browser Output Output
  11. 11. Principal of OOPsObject Oriented Programming (OOP) attempts to emulate the real world in software systems.The real world consists of objects, categorized in classes. In Object Oriented Programming,classes have attributes, represented by data member. The attributes distinguish an object ofthe class. Classes have behaviors, which are represented by methods. The methods definehow an object acts or reacts.Feature of Object Oriented Programming :Information Encapsulation(Hiding) :- Objects provide the benefit of information hiding.Electrical writing in a television should not be tempered with, and therefore should be hiddenfrom the user. Object Oriented programming allows you to encapsulate data that you do notwant users of the object to access. Typically, attributes of a class are encapsulated.Abstraction :- Abstraction allows us to focus on only those parts of an object that concernus. Person operating the television does not need to know the intricacies of how it works. Theperson just needs to know how to switch it on, change channels, and adjust the volume.Allthe details that are unnecessary to users are encapsulated, leaving only a simple interface tointeract with. Providing users with only what they need to know is known as abstraction. i.e.Abstraction lets us ignore the irrelevant details and concentrate on the essentials.
  12. 12. Inheritance :- Inheritance is the process by which objects of one class acquire theproperties of objects of another class. Inheritance supports the concept ofhierarchical classification. In OOP, the concept of inheritance provides the idea ofreusability. This means that we can add additional features to an existing classwithout modifying it. This is possible by deriving a new class from the existing one.The new class will have the combined features of both the classes.Polymorphism :- Polymorphism means “One Interface, multiple implementations.” Shape Ellipse Rectangle TriangleThe class Shape defines a method called getArea() that returns the area of ashape. However, this method is not implemented by that class. Therefore, it is anabstract method and Shape is an abstract class.This means that no objects of class Shape can be created. However, thefunctionality of that class can be inheritated by its subclass. The varioussubclasses of Shape like Ellipse,Rectangle,Triangle do implement the getArea()method.
  13. 13. First Java Application Create the File The first step to create the HelloWorld application is to copy the text from listing 7.1 into a file called using your favorite text editor (by choosing Windows, NotePad, or SimpleText on the Macintosh). It is very important to call the file, because the compiler expects the file name to match the class identifierListing 7.1 The HelloWorld application.public class HelloWorld { public static void main(String args[]){System.out.println("Hello World!!");}}
  14. 14. Class DeclarationThe first line public class HelloWorld declares a class, which is an Object-Orientedconstruct. As stated earlier Java is true Object-Oriented language and therefore,everything must be placed inside a class. Class is a keyword and declares that anew class definition follows.Opening BaceEvery class definition in Java begins with an opening brace “{“ and ends with amatching closing brace “}”, appearing in the last line in the example.The main() methodEvery java application program must include the main() method. This is startingpoint for the interpreter to begin the execution of the program. A Java applicationcan have any number of classes but only one of them must include a main methodto initiate the execution.Public : The Keyword public is an access specifier that declares the main methodas unprotected and therefore making it to accessible to all other classes.Static : The keyword static which declares this method as one that belongs to theentire Class and not a part of any Objects of the class.
  15. 15. The main must always be declared be declared as static since the interpreter usesthis method before any objects are created.Void : The type modifier void states that the main method does not return any value.All parameters to a method are declared inside a pair of parentheses. Here,String args[] declares a parameter named args, which contains an array of objectsOf the class type String.The Output LineThe only executable Statement in the program isSystem.out.println("Hello World!!");Since Java is a true Object Oriented Language, every method must be part of anObject. The println method is a member of the out Object, which is static dataMember of the System class. This line printsHello World!!to the screen. The method println always appends a newline character to the endof the string.
  16. 16. Compile the CodeTo compile the program, you need to first install the JDK. Then, use the programjavac included with the JDK to convert the text in listing 7.1 to code which thecomputer can run. To run javac, on a Macintosh drag the source file over the javacicon. On any other computer, type the line:javac HelloWorld.javaat a command prompt. The javac program creates a file called HelloWorld.classfrom the file. Inside this file (HelloWorld.class) is text known asbytecodes which can be run by the Java interpreter.Run the ProgramNow that you have compiled the program, you can run it by typing at the commandprompt:java HelloWorldAfter you do this, the computer should print to the screenHello World!!That may not seem very interesting, but then its a simple program. If you dont seethe Hello World!! on the screen, go back and make sure you have typed in the fileexactly as shown in listing 7.1, and make sure that you called the
  17. 17. JAVA CONTROLS Variables and Constants Arithmetic Operator and Expressions Type Conversion in Java Comments in Java(3 Types) Java’s Control Statements o If o If-else o Do-while o While o for o Increment and Decrement Operators o Escape Sequences Characters o Relational and Logical Operators o Ternary Operators o Switch case o Break o Bitwise Operators o Arrays-Single and Multidimensional
  18. 18. Variables and ConstantsConstants : Constants in Java refer to fixed values that do not change during theexecution of a program. Java supports several types of constants given in figure below : Java Constant Numeric Constant Character Constant Integer Real Character StringInteger Constants : Refers to a sequence of digits. There are three types ofIntegers, namely, decimal,octal and hexadecimal integer.Decimal Integer consist of of a set of digits, 0 through 9, preceded by an optionalminus sign.An octal integer constant consists of any combination of digits from the set 0through 7, with a leading 0.A sequence of digits preceded by ox or OX is considered as hexadecimal integer.They may also include alphabets A through F.
  19. 19. Real Constants : Integer constant are inadequate to represent quantities that varycontinuously, such as distance, heights, temperature, prices and so on. Thesequantities are represented by numbers containing fractional parts like 17.546.Such numbers are called real.The real number may also be expressed in exponential (or scientific ) notation.For example, the value 215.65 may be written as 2.1565e2 in exponentialnotation. e2 means multiply by 102. The general form is : mantissa e exponent mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase. Since the exponent causes the decimal point to “float”, this notation is said to represent a real number in floating point form.
  20. 20. Single Character Constants : A single character constant (or simply character constant ) contains a single character enclosed within a pair of single quote marks. Examples of character constants are : ‘5’ ‘X’ ‘;’ String Constant : A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets,digits,special characters and blank spaces. Example are : “Hello Java” “1997”Variable : A variable is an Identifier that denotes a storage location used to store adata value. Unlike constants that remain unchanged during the execution of program.Examples of variables : average,height,total_height.Variable name may consist of alphabets,digits,the underscore(_) and dollorcharacters.Rules to write Variable/Identifier in Java :• They must not begin with digit• Upper and lowecase are distinct. This means that the variable Total is not the samas total or TOTAL.• It should not be a keyword.• White space is not allowed.• Variable names can be of any length.
  21. 21. Data Types Data Types in Java Primitive (Intrinsic) Non-Primitive ( Derived)Numeric Non-Numeric Classes Arrays Floating InterfaceInteger Character Boolean PointInteger TypesJava consists of four integer types: byte, short, int, and long, which are defined as 8-,16-, 32-, and 64-bit signed values as summarized in Table below :
  22. 22. The Java integer primitive types. Type Bit Size Minimum Value Maximum Value byte 8 -128 +127 short 16 -32,768 32,767 int 32 -2,147,483,648 2,147,483,647 long 64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807Integer literals can be specified in decimal, hexadecimal, or octal notation. To specify a decimalvalue, simply use the number as normal. To indicate that a literal value is a long, you can appendeither "L" or "l" to the end of the number. Hexadecimal values are given in base 16 and includethe digits 0-9 and the letters A-F. To specify a hexadecimal value, use 0x followed by the digits and letters that comprise the value. Similarly, an octal value is identified by a leading 0 symbol.For examples of specifying integer literals, see Table 3.7.
  23. 23. Table 3.7. Examples of integer literals. Integer Long Octal Hexadecimal 0 0L 0 0x0 1 1L 01 0x1 10 10L 012 0xA 15 15L 017 0XF 16 16L 020 0x10 100 100L 0144 0x64Floating-Point TypesSupport for floating-point numbers in Java is provided through two primitive types-floatand double, which are 32- and 64-bit values, respectively. Similar to integer literals are Javas floating-point literals. Floating-point literals can be specified in either the familiar decimal notation (for example, 3.1415) or exponential notation (for example, 6.02e23). To indicate that a literal is to be treated as a single precision float, append either "f" or "F". To indicate that
  24. 24. it is to be treated as a double precision value, append either "d" or "D". Java includes predefined constants, POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN, to represent the infinity and not-a-number values. The following list shows some valid floating-point literals: 43.3F,3.1415d,-12.123f,6.02e+23f,6.02e23d,6.02e-23f,6.02e23dBoolean :- Java supports two Boolean literals-true and false.Character Literals :-A character literal is a single character or an escape sequence enclosed insingle quotes, for example, b. Escape sequences are used to indicate special characters oractions, such as line feed, form feed, or carriage return. The available escape sequences ar shownin Table 3.8.String LiteralsAlthough there is no string primitive type in Java, you can include string literals in yourprograms. Most applications and applets will make use of some form of string literal,probably at least for error messages. A string literal consists of zero or more characters(including the escape sequences shown in Table 3.8) enclosed in double quotes. Asexamples of string literals, consider the following: "A String“,"Column 1tColumn 2”
  25. 25. Table 3.8. Escape sequences.Sequence Purposeb Backspacet Horizontal tabn Line feedf Form feedr Carriage return" Double quote Single quote Backslashuxxxx Unicode character
  26. 26. Arithmetic Operators and ExpressionsAn expression is a operators and operands. It follows the rules of algebra and shouldbe familiar. Java allows several types of expressions. The arithmetic operators aregiven below :+ addition-subtraction*multiplication/ division% modulus+= addition assignment-=subtraction assignment*=multiplication assignment/=division assignment%=modulus assignment++increment,--decrement
  27. 27. An expression may appear on the right side of an assignment statement. Forexample,Int answer;Answer=100*31;Java expression may contain Variables, constants or both. For example assumingthat answer and count are variables, this expression is perfectly valid.Answer=count-100;
  28. 28. Increment/Decrement OperatorsThe increment and decrement operators are used with one variable (they are known asunary operators):++ increment operator-- decrement operatorFor instance, the increment operator (++) adds one to the operand, as shown in the next lineof code:x++;is the same asx+=1;The increment and decrement operators behave slightly differently based on the side of theoperand they are placed on. If the operand is placed before the operator (for example, ++x),the increment occurs before the value is taken for the expression. So, in the following codefragment, the result of y is 6:int x=5;int y=++x; // y=6 x=6If the operator appears after the operand, the addition occurs after the value is taken. So y is5 as shown in the next code fragment. Notice that in both examples, x is 6 at the end of x=5;int y = x++; //y=5 x=6Similarly, the decrement operator (--) subtracts one from the operand, and the timing of thisis in relation to the evaluation of the expression that it occurs in.
  29. 29. The Relational OperatorsThe most intuitive comparative operators are those that fall into a category knownas relational operators. Relational operators include those standard greater-thanand less-than symbols you learned about back in third grade. Conveniently enough,they work the same way as they did back in third grade, too. For instance, youknow that if you write (3>4), you wrote something wrong (false). On the other hand(3<4) is correct (true). In Java and most other languages, you are not limited toevaluating constants; you are free to use variables, so the statement (Democrats>Republicans) is also valid. The complete list of relational operators is shown here:Operator Boolean Result< Less than<= Less than or equal to> Greater than>= Greater than or equal toThe following two assignment statements produce identical results:result1 = a+b < c*d ;result2 = (a+b) < (c*d) ;Logical ExpressionsThe third set of evaluation operators fall into a category known as logicalexpressions. Logical expressions work a bit differently than the previous operators,and are probably not something you covered in your third grade math class.
  30. 30. Logical expressions operate either on a pair of booleans, or on the individual bits of anobject. There are two types of logical operators which are divided roughly along theselines:•Boolean operators. Only operate on Boolean values.•Bitwise operators. Operate on each bit in a pair of integral operands.The Conditional-And and Conditional-Or OperatorsThere are two primary Boolean operators:•Logical-AND: &&•Logical-OR: ||Oddly, in most computer languages, including Java, there is no Conditional-XORoperator. And when B is (A && B) (A || B) When A is false false false false false true false true true false false true true true true true
  31. 31. The Conditional OperatorThe conditional operator is the one ternary or triadic operator in Java, andoperates as it does in C and C++. It takes the following form:expression1 ? expression2 : expression3In this syntax, expression1 must produce a Boolean value. If this value is true,then expression2 is evaluated, and its result is the value of the conditional. Ifexpression1 is false, then expression3 is evaluated, and its result is the value ofthe conditional.Consider the following examples. The first is using the conditional operator todetermine the maximum of two values; the second is determining the minimumof two values; the third is determining the absolute value of a quantity:BestReturn = Stocks > Bonds ? Stocks : Bonds ;LowSales = JuneSales < JulySales ? JuneSales : JulySales ;Distance = Site1-Site2 > 0 ? Site1-Site2 : Site2 - Site1 ;In reviewing these examples, think about the precedence rules, and convinceyourself that none of the three examples requires any brackets in order to beevaluated correctly.
  32. 32. Type Conversion in JavaImplicit Type ConversionsJava performs a number of implicit type conversions when evaluating expressions.For unary operators (such as ++ or --), the situation is very simple: operands of typebyte or short are converted to int, and all other types are left as-is.For binary operators, the situation is only slightly more complex. For operations involving onlyinteger operands, if either of the operands is long, then the other is also converted to long;otherwise, both operands are converted to int. The result of the expression is an int, unless thevalue produced is so large that a long is required. For operations involving at least one floatingpoint operand, if either of the operands is double, then the other is also converted to double andthe result of the expression is also a double; otherwise, both operands are converted to float, andthe result of the expression is also a float.Fortunately, implicit conversions take place almost always without your wanting or needing toknow. The compiler handles all the details of adding bytes and ints together so you dont have to.short Width;long Length, Area;Area = Length * Width;// In the division below, Area will be converted to a double,// and theresult of the calculation will be a double.
  33. 33. Conversions and the Cast Operator :Normally with implicit conversion, the conversion is so natural that you dont evennotice. Sometimes though it is important to make sure a conversion occurs between twotypes. Doing this type of conversion requires an explicit cast, by using the cast operator.The cast operator consists of a type name within round brackets. It is a unary operatorwith high precedence and comes before its operand, the result of which is a variable ofthe type specified by the cast, but which has the value of the original object. Thefollowing example shows an example of an explicit cast:float x = 2.0;float y = 1.7;x - ( (int)(x/y) * y)When x is divided by y in this example, the type of the result is a floating-point number.However, value of x/y is explicitly converted to type int by the cast operator, resulting ina 1, not 1.2. So the end result of this equation is that x equals 1.7.Not all conversions are legal. For instance, boolean values cannot be cast to any othertype, and objects can only be converted to a parent class.Casting and Converting IntegersThe four integer types can be cast to any other type except boolean. However,casting into a smaller type can result in a loss of data, and a cast to a floating-point number (float or double) will probably result in the loss of some precision,unless the integer is a whole power of two (for example, 1, 2, 4, 8...).
  34. 34. Casting and Converting CharactersCharacters can be cast in the same way 16-bit (short) integers are cast; that is,you can cast it to be anything. But, if you cast into a smaller type (byte), you losesome data. In fact, even if you convert between a character and a short you anloose some data.If you are using the Han character set (Chinese, Japanese, or Korean), you canlose data by casting a char into a short (16-bit integer), because the top bit willbe lost.Casting and Converting BooleansThere are not any direct ways to cast or convert a Boolean to any other type.However, if you are intent on getting an integer to have a 0 or 1 value based onthe current value of a Boolean, use an if-else statement, or imitate the followingcode:int j;boolean tf;...j = tf?1:0; // integer j gets 1 if tf is true, and 0 otherwise.Conversion the other way can be done with zero to be equal to false, andanything else equal to true as follows:int j;boolean tf; = (j!=0); // Boolean tf is true if j is not 0, false otherwise.
  35. 35. Comments in JavaJava supports three types of comment delimiters-the traditional /*and */ of C, the // of C++, and a new variant that starts with /** andends with */.The /* and */ delimiters are used to enclose text that is to be treated as acomment by the compiler. These delimiters are useful when you want todesignate a lengthy piece of code as a comment, as shown in thefollowing:/* This is a comment that will span multiple source code lines. */The // comment delimiter is borrowed from C++ and is used to indicate thatthe rest of the line is to be treated as a comment by the Java compiler.This type of comment delimiter is particularly useful for adding commentsadjacent to lines of code, as shown in the following:Date today = new Date(); // create an object with todays dateSystem.out.println(today); // display the dateFinally, the /** and */ delimiters are new to Java and are used to indicate that the enclosed textis to be treated as a comment by the compiler, but that the text is also part of the automaticclass documentation that can be generated using JavaDoc
  36. 36. The Java comment delimiters are summarized in Table 3.1.Table 3.1. Java comment delimiters. Start End Purpose/* */ The enclosed text is treated as a comment.// (none The rest of the line is treated as a comment. )/** */ The enclosed text is treated as a comment by the compiler but is used by JavaDoc to automatically generate documentation.
  37. 37. Java Control Statements Control Statement Selection Statement Iteration Statement Jump Statement conti returnif If-else switch break nue while do for
  38. 38. Selection Statement : These select one of several control flows. There arethree types of selection statement in Java : if,if-else, and switch.If statement :The if statement is a powerful decision making statement and is used to controlthe flow of execution of statements. It is a two-way decision statement and isused in conjunction with an expression. The general form is :If(test expression){Statement-block;}Statement-x;It allows the computer to evaluate the expression first and then, depending onwhether the value of the expression (relation or condition) is ‘true’ or ‘false’. Ittransfers the control to a particular statement.If the statement is true then the Statement block will be executed;otherwise thestatement-block will be skipped and the execution will jump to the statement-x.It should be remember that when the condition is true both the statement-blockand statement-x are executed in sequence.
  39. 39. Example :Class Demo {public static void main(String args[]) {If(args.length==0)System.out.println(“You must have command line arguments”); }}If-else statementif(test expression){True-Block Statement(s);}Else{False-Block statement(s);}Statement-x;
  40. 40. If the test expression is true, then the true-block statement(s) executedimmediately following to the if statement, are executed; otherwise the falsestatement(s) will be executed, not both.In both the cases, the control istransferred subsequently to the statement-x.Nesting of If—else StatementIf(test condition1){ if(test condition2) { Statement-1; } else { Statement-2; }}else {Statement-3; }Statement-x;If the condition-1 is false, the statement-3 will be executed; otherwise itcontinues to perform the second test. If the condition-2 is true, the statement-1will be evaluated;otherwise statement-2 will be evaluated and then control istransferred to the statement-x.
  41. 41. Switch Statement: The Java switch statement is ideal for testing a singleexpression against a series of possible values and executing the codeassociated with the matching case statement.Switch(expression) {Case value-1: block-1; break;Case value-2: block-2; break;…………default: default-block; break; }Statement-x;
  42. 42. Iteration Statement : These specify how and when looping will take place. Thereare three types of Iteration statements: while, do and forThe for StatementThe first line of a for loop enables you to specify a starting value for a loopcounter, specify the test condition that will exit the loop, and indicate how the loopcounter should be incremented after each pass through the loop. This is definitelya statement that offers a lot of bang for the buck. The syntax of a Java forstatement is as follows:for (initialization; testExpression; incremement) statementFor example, a sample for loop may appear as follows:int count;for (count=0; count<100; count++) System.out.println("Count = " + count);In this example, the initialization statement of the for loop sets count to 0. The testexpression, count < 100, indicates that the loop should continue as long as countis less than 100. Finally, the increment statement increments the value of countby one. As long as the test expression is true, the statement following the for loopsetup will be executed, as follows:System.out.println("Count = " + count);Of course, you probably need to do more than one thing inside the loop. This isas easy to do as using curly braces to indicate the scope of the for loop.
  43. 43. The while StatementRelated to the for loop is the while loop. The syntax for a while loop is asfollows:while (booleanExpression) statementAs you can tell from the simplicity of this, the Java while loop does not havethe built-in support for initializing and incrementing variables that its for loopdoes. Because of this, you need to be careful to initialize loop counters priorto the loop and increment them within the body of the while loop. Forexample, the following code fragment will display a message five times:int count = 0;while (count < 5) { System.out.println("Count = " + count); count++;}The do…while StatementThe final looping construct in Java is the do…while loop. The syntax for ado…while loop is as follows:do { statement} while (booleanExpression);
  44. 44. This is similar to a while loop except that a do…while loop is guaranteed to executeat least once. It is possible that a while loop may not execute at all depending onthe test expression used in the loop. For example, consider the following method:public void ShowYears(int year) { while (year < 2000) { System.out.println("Year is " + year); year++; }}This method is passed a year value, then loops over the year displaying a messageas long as the year is less than 2000. If year starts at 1996, then messages will bedisplayed for the years 1996, 1997, 1998, and 1999. However, what happens ifyear starts at 2010? Because the initial test, year < 2000, will be false, the whileloop will never be entered. Fortunately, a do…while loop can solve this problem.Because a do…while loop performs its expression testing after the body of the loophas executed for each pass, it will always be executed at least once. This is a veryvalid distinction between the two types of loop, but it can also be a source ofpotential errors. Whenever you use a do…while loop, you should be careful toconsider the first pass through the body of the loop.
  45. 45. JumpingOf course, it is not always easy to write all of your for, while and do…while loops sothat they are easy to read and yet the loops terminate on exactly the right passthrough the loop. Java makes it easier to jump out of loops and to control otherareas of program flow with its break and continue statements.The break StatementEarlier in this chapter, you saw how the break statement is used to exit a switchstatement. In a similar manner, break can be used to exit a loopAs an example of this, consider the following code:int year = 1909;while (DidCubsWinTheWorldSeries(year) == false) { System.out.println("Didnt win in " + year); if (year >= 3000) { System.out.println("Time to give up. Go White Sox!"); break; }}System.out.println("Loop exited on year " + year);
  46. 46. This example shows a while loop that will continue to execute until it finds a yearthat the Chicago Cubs won the World Series. Because they havent won since1908 and the loop counter year starts with 1909, it has a lot of looping to do. Foreach year they didnt win, a message is displayed. However, even die-hardCubs fans will eventually give up and change allegiances to the Chicago WhiteSox. In this example, if the year is 3000 or later, a message is displayed andthen a break is encountered. The break statement will cause program control tomove to the first statement after the end of the while loop. In this case, that willbe the following line:System.out.println("Loop exited on year " + year);The continue StatementJust as a break statement can be used to move program control to immediatelyafter the end of a loop, the continue statement can be used to force programcontrol back to the top of a loop
  47. 47. ARRAYSOne Dimensional Array : is a list of variables of the same type that are accessed through a common name. An Individual variable in the array is called an array element. Arrays from a convenient way to handle groups of related data.To create an array, you need to perform two steps :4. Declare Array2. Allocate space for its elements.General Form for declaring one dimensional array given below :type varName[];Here, type is a valid Java data type and varName is the name of the array. Like int a[];This creates a variable named a that refers to an integer array. But it does not actually create storage for the array.Second approach to allocate space for One Dimensional Array is
  48. 48. varName=new type[size];Here varName is name of the array, type is a valid Java type, and sizespecifies the number of elements in the array. You can see that the newoperator is used to allocate memory for the array.These two steps combines liketype varName=new type[size];For example consider this declaration and allocation :Int ia=new int[10];Represents the structure of a one-dimensional array,here ia is array variablename that can hold 10 integer values.Multidimensional Array :In addition to one dimensional we can create arrays of two or moredimensions. In Java, Multidimensional array are implemented as arrays ofarrays. You need to perform two steps to work with multidimensional arrays :1. Declare the array and 2. allocate space for its elements.
  49. 49. The General form is given below :Type varname = new type[size1][size2];float a[][]=new float[2][2];Here a is two dimensional array having 2 rows and 2 columns. i.e. size is 4,we can store 4 elements in that array.
  50. 50. JAVA Classes and Methods The General Form of a class Constructor and Method Overloading The new Operator Garbage Collection Finalize method Command Line Arguments The System Class
  51. 51. The General Form of ClassA class array contains three types of items : variable,methods, and constructors.Variable represent its state. Method provide the logic that constitutes thebehavior defined by a class. The variable and methods can be both static andinstance variable. Constructors initialize the state of a new instance of a class.The Simplified form of a class is :class clsName {//instance variable declarationstype1 varName1=value1;type2 varName2=value2;…..//constructorclsName(cparams1) {// body of constructor}
  52. 52. clsName(cparamsN) {//body of constructor}…//methodsrtype1 mthName(mparams1) {//body of method}…..}}The keyword class indicates that a class named clsName is being declared. Thisname must follow the Java naming convention for identifiers. The instanceVariables named varName1 through varNameN included using the normalvariable declaration syntax. Each variable must be assigned a type shown as
  53. 53. type1 through typeN and may be initialized to value shown as value1 throughvalueN.Constructors always have the same name as the class. They do not have returnvalues.Method named mthName1 through mthNameN can be included. The return type ofthe methods are rType1 through rtypeN, and their Optional Parameter lists aremparams1 through mparamsN.ConstructorsOften an object will require some form of initialization when it is created. Toaccommodate this, Java allows you to define constructor for your classes. AConstructor is a special method that creates and initializes an object of a particularclass. It has the same name as its class and may accept arguments. Constructordoes not have a return type. Instead, a constructor returns a reference to theobject that it creates.Constructor OverloadingA class may have several constructors. This feature is called constructoroverloading. When constructors are overloaded each is still called by the name ofits class. However it must have a different parameter list. i.e. Signature of eachconstructor must differ.
  54. 54. Method OverloadingLike Constructor, method can also be overloaded. This occurs when two or moremethods have the same name but different signature. Recall that the signature ofa method is a combination of its name and the sequence of the parameter types.Method Overloading allows you to use the same name for a group of methods thatbasically have the same purpose. The println() is an good example of this concept.It has so many Overloaded forms.Each of these accepts one argument of adifferent type. Another advantage of method overloading is that it provides an easyway to handle default parameter values.The New OperatorObjects are created using the new operator. The new Operator creates aninstance of a class. It is invoked as follows :clsName obhRef=new clsName(args);Here, clsName is the name of the class to instantiated. (Instantiated means tocreate an instance.) A reference to the new object is assigned to a variable namedobjRef. Notice the expression immediately to the right of the keyword new. This isknown as constructor. A constructor creates an instance of the class. It has thesame name as the class and may optionally have an argument list args.
  55. 55. Garbage CollectionGarbage collection is the mechanism that reclaims the memory resources of anobject when it is no longer referenced by a variable. It prevents programmingerrors that could otherwise occur by incorrectly deleting or failing to deleteobjects. An object becomes eligible for garbage collection when it is no longerreferenced by any Variable. However, the JVM determines exactly when thistask is performed.finalize method :Constructor method used to initialize an object when it is declared. This processis known as initialization. Similarly, Java supports a concept called finalization,which is just opposite to Initialization. We know that java run-time is anautomatic garbage collecting system. It automatically frees up the memoryresources used by the objects. But objects may hold other non-object resourcessuch as file descriptors or window system fonts. The garbage collector cannotfree these resources. In order to free these resources we must use a finalizermethod. This is similar to destructor of C++.The finalizer method is simply finalize() and can be added to any class. Javacalls that method whenever it is about to reclaim the space for that object. Thefinalize method should explicitly define the tasks to be performed.
  56. 56. Command Line ArgumentsAll java application contain a static method named main().This method takesone argument that is an array of String objects. These objects represent anyarguments that may have been entered by the user on the command line.The number of command line arguments is obtained via the expressionargs.length. This is an int type. The individual arguments are accessed asarg[0],args[1],args[2], and so forth.The System ClassThe system class defines several attributes relate to the run-timeenvironment. It has a static variable named out that contains a reference to aPrintStream object. The print() and println() methods of that object displaytheir string arguments on the standard output. The static variable err alsoholds a reference to PrintStream object. This is the standard error stream.The static variable in contains a reference to an InputStream object.PrintStream and InputStream are classes that provide support for I/O.Another static method of the system class is exit(). It determines the currentapplication.
  57. 57. Using Classes and Methods Instance Methods and Variables Static keyword Inner Class/Nested Classes String Class Math Class Wrapper Class
  58. 58. Instance Variables and MethodsEach object has its own copy of all the instance variables defined by its class.Thus an Instance variable relates to an instance (object) of its class. Instancevariable may be declared by using the following form :type varName1;Here, the name of the variable is varName1 and the required type is type.Instance variables are initialized to default values during the creation of an object.A Instance Method acts upon an object and can be declared, as follows:rtype mthname(mparams) {//body of method}Here mthName is the name of the method and type is its return type.Static Variables and MethodsA static variable is shared by all objects of its class and thus relates to the classitself. A static variable may be declared by using the static keyword as a modifieras follows:static type varName1;Here the name of the variable ios varName1 and its type is type.Static variables are initialized to default values when the class loaded into thememory.
  59. 59. A static method may be declared by using the static keyword as a modifier. Astatic method acts relative to a class. It deos not act on specific objects of itsclass. To declare a static method as :static rtype mthName(mparams) {//body of method}}Here mthName is the name of the method and rtype is its return type an optionallist of parameter types shown as mparams may be specified.String ClassStrings are class instantiated object and implemented using String Class.String class expressed as :String stringName=new String(“string”);A string class defines a number of methods that allows you to accomplish avariety of string manipulation tasks like compareTo() method used to sort anarray of strings in alphabetical order.
  60. 60. Math ClassMathematical functions such as cos,sqrt, log etc. are frequently used toanalysis of real-life problems. Java supports these basic functions throughMath class defined in the java.lang package.The math function used as followsMath.function_name();Like double y=Math.sqrt(x);Wrapper ClassThere are wrapper classes for each of the eight simple types defined by Java.These are Boolean, Character, Byte,Integer,Float,Long,Short and Double.They encapsulate boolean,char,byte,int,float,long,short and double values.TheBenefit of using wrapper classes is that they provide methods to convertstrings to simple types. This is a very useful because it gives us a mechanismby which to process user input.
  61. 61. Inheritance Single and Multilevel Call by value and Call by reference Method Overriding this and super keyword Abstract and Final Classes
  62. 62. Class Inheritance In Java, every class you declare will be derived from another class. You can specify the class to derive from by using the extends keyword as follows: public class ClassicCar extends Car { // member methods and variables }A derived class is commonly referred to as a subclass, while the class it is derivedfrom is commonly referred to as a superclass. The term immediate superclass isused to describe the class from which a subclass is directly derived. In Figure 3.5, forexample, ClassicCar is a subclass of both Car and Object. Car and Object are bothsuperclasses of ClassicCar, but only Car is the immediate superclass of ClassicCar. Fig 3.5
  63. 63. Call By Value and Call By Reference (Argument Passing)All methods are passed by value. This means that copies of the arguments areprovided to a method. Any changes to those copies are not visible outsidemethod.The situation when an array of objects are passed as an argument. In this casethe entire array or object is not actually copied.Instead, only a copy of thereference is provided. Therefore any changes to the array or object are visibleoutside the method. However the reference itself is passed by value.
  64. 64. Overriding Member MethodsWhen you create a subclass, you inherit all of the functionality of its superclass,and then you can add or change this functionality as desired. As an example ofthis, consider the altered declaration of a Car class in the following code: public class Car { private int year; private float originalPrice; // calculate the sale price of a car based on its cost public double CalculateSalePrice() { double salePrice; if (year > 1994) salePrice = originalPrice * 0.75; else if (year > 1990) salePrice = originalPrice * 0.50; else salePrice = originalPrice * 0.25; return salePrice; } // a public constructor
  65. 65. public Car(int year, float originalPrice) { this.year = year; this.originalPrice = originalPrice; } }ClassicCar is derived from Car, as follows: public class ClassicCar extends Car { // calculate the sale price of a car based on its cost public double CalculateSalePrice() { return 10000; } // a public constructor public ClassicCar(int year, float originalPrice) { super(year, originalPrice); } }
  66. 66. Because ClassicCar is derived from Car, it inherits all of the functionality of Car,including its member variables year and originalPrice. The functionCalculateSalePrice appears in both class declarations. This means that theoccurrence of this function in ClassicCar overrides the occurrence of it in Car forobject instances of ClassicCar. As an example of how this works, consider thefollowing: ClassicCar myClassic = new ClassicCar(1920, 1400); double classicPrice = myClassic.CalculateSalePrice(); Car myCar = new Car(1990, 12000); double price = myCar.CalculateSalePrice();The variable myClassic is of type ClassicCar and is constructed using that classsconstructor Class Modifiers Classes that are created in Java can be modified by any of three class modifiers. The Java class modifiers are public, final, and abstract. If no class modifier is used, then the class may only be used within the package in which it is declared. A public class is a class that can be accessed from other packages. A class that is declared as final cannot be derived from, meaning it cannot have subclasses.
  67. 67. The this VariableAll Java classes contain a hidden member variable named this. The this membercan be used at runtime to reference the object itself. One excellent use of this is inconstructors. It is very common to have a set of instance variables in a class thatmust be set to values that are passed to a constructor. When you are doing this, itwould be nice to have code that was similar to the following:year = year;Ideally the variable on the left could be the instance variable, and the variable onthe right could be the parameter passed to the constructor. public class Car { String manufacturer; String model; int year; int passengers; // a public constructor public Car(String madeBy, String name, int yr, int pass,float cst) { manufacturer = madeBy; model = name; year = yr; passengers = pass; cost = cst;} }
  68. 68. Here, weve had to come up with two names for each concept: the best variablenames (manufacturer, model, and so on) are used as the instance variables inthe class declaration. The less satisfactory names are passed as parametersso as to distinguish them from the instance variables. The assignmentstatements are then very readable by Java but seem a little contrived to humanreaders. Javas this keyword provides a very effective solution to this problem inthat the constructor can be written as follows:public class Car { String manufacturer; String model; int year; int passengers; float cost; // calculate the sale price of a car based on its cost public double CalculateSalePrice() { return cost * 1.5; } // a public constructor public Car(String manufacturer, String model, int year,int passengers,float cost) { this.manufacturer = manufacturer; this.model = model;
  69. 69. this.year = year; this.passengers = passengers; this.cost = cost; } }In this case, the variables like this.year refer to the instance variables, whereasthe unqualified variables like year refer to the constructors parameters.
  70. 70. The super VariableIn the preceding declaration for ClassicCar, you may have noticed that theconstructor made use of a variable named super. Just as each object has a thisvariable that references itself, each object (other than those of type Object itself)has a super variable that represents the parent class. In this case, super(year,originalPrice) invokes the constructor of the superclass Car.Use of Super• Super is used to invoke the constructor method of the superclass.• Super may be only used within a subclass constructor method.• The call to superclass constructor must appear as the first statement within the subclass constructor.• The parameters in the super call must match the order and type of the inheritance variable declared in the subclass.
  71. 71. Abstract ClassesSometimes you may want to declare a class and yet not know how to define all ofthe methods that belong to that class. For example, you may want to declare aclass called Mammal and include in it a member method called MarkTerritory.However, you dont know how to write MarkTerritory because it is different for eachtype of Mammal. Of course, you plan to handle this by deriving subclasses ofMammal, such as Dog and Human. But what code do you put in the MarkTerritoryfunction of Mammal itself?In Java you can declare the MarkTerritory function of Mammal as an abstractmethod. Doing so allows you to declare the method without writing any code for itin that class. However, you can write code for the method in the subclass. If amethod is declared abstract, then the class must also be declared as abstract. ForMammal and its subclasses, this means they would appear as follows: abstract class Mammal { abstract void MarkTerritory(); } public class Human extends Mammal { public void MarkTerritory() { // mark territory by building a fence } }
  72. 72. public class GangMember extends Mammal { public void MarkTerritory() { // mark territory with graffiti } } public class Dog extends Mammal { public void MarkTerritory() { // mark territory by doing what dogs do } }With the preceding declarations, the Mammal class contains no code forMarkTerritory. The Human class could contain code that would mark territory bybuilding a fence around it, while the GangMember class could contain code thatwould mark territory by spray-painting graffiti. The Dog class would mark territoryby raising the dogs leg and doing what dogs do to mark territory.
  73. 73. Final Variables, Methods and ClassAll methods and variables can be overridden by default in subclasses. If we wishto prevent the subclasses from overriding the members of the super class, wecan declare them as final using the keyword final as a modifier. For example :final int SIZE=100;final void showStatus(…)Making a method final ensures that the functionality defined in this method willnever be altered in any way. Similarly the value of a final variable can never bechange.Sometimes we may like to prevent a class being further subclassed for securityreasons. A class that can not be subclassed is called a final class. This isachieved in Java using the keyword final as follows:Final class AClass ( ………….)Any attempt to inherit these classes will cause an error and the compiler will notallow it.
  74. 74. STRINGSStrings represent a sequence of characters. The easiest way to represent a sequenceof characters in Java is by using a character array. Example : charcharArray[]=new char[4];We can declare string using Characters but there is limitation that we can not usefunctions related with strings using array like copy of an array is difficult. For thatJava provides String class using objects.for that two classes are used String and StringBuffer. A Java String is aninstantiated object of the String class.String stringName;stringName=new String ("string");String Array :String itemArray[]=new String[3];//will create itemArray of size 3 to hold threestring constants.
  75. 75. String Methods :The String Class defines a number of methods that allow us to accomplish a veriety of stringmanipulation tasks.s2=s1.toLowerCase; //converts the string s1 to all lowercases2=s1.toUpperCase; //converts the string s1 to all Uppercases2=s1.replace(x,y); //Replace all occurance of x with ys2=s1.trim() //Removes the white spaces at the beginning and end of the String s1.s1.equals(s2) //Returns true if s1 is equal to s2s1.equalsIgnoreCase(s2) //Returns true if s1=s2, ignoring the case of characters.s1.length() //Gives the Length of s1s1.charAt(n) //Gives nth character of s1s1.compareTo(s2) //Returns negative if s1<s2,positive if s1>s2, and zero if s1 is equal to s2s1.concat(s2) //concatenates s1 and s2s1.substring(n) //Gives substring starting from nth character
  76. 76. s1.subsctring(n,m) //Gives substring starting from nth charater upto mth (not including mth)String.ValueOf(p) //Creates a string object of the parameter p (simple type or object)p.toString(); //creates a string representation of the object ps1.indexOf(x) //Gives the position of the first occurence of x in the string s1.s1.indexOf(x,n) // Gives the position of the x that occurs after nth position in the string s1.String.valueOf(variable) //Converts the parameter value to string representation.String Buffer Class :StringBuffer is a peer class of String. While String creates strings of fixed length, StringBuffercreates strings of flexible length that can be modified in terms of both length and content. We caninsert characters and substrings in the middle of a string, or append another string to the end.s1.setCharAt(n,x)//Modifies the nth character to xs1.append(s2)//Appends the string s2 to s1 at the ends1.insert(n,s2)//Inserts the string s2 at the position n of the string s1.s1.setLength(n)//Sets the length of the string s1 to n. If n<s1.length() s1 is truncated. If n>s1.length()zeros are added to s1.
  77. 77. Vectors :Java does not support the concept of variable arguments to a function. This feature can be achievedin Java through the use of the Vector class contained in the java.util package. This class can be usedto create a generic dynamic array known as vector that can hold objects of any type and any number.The objects do not have to be homogenious . Arrays can be eaisly implemented as vectors. Vectorsare created like arrays as follows :Vector intVect = new Vector();//declaring without sizeVector intVect = new Vector(3);//declaring with sizeVectors possess a number of advantages over arrays :1. It is convenient to use vectors to store objects.2. A vector can be used to stroe a list of objects that may vary in size.3. We can add and delete objects from the list as the list as and when required.A major constraints in using vectors is that we can not directly store simple data types in a vector.we can only store objects. Therefore, we need to convert simple types to objects. This can be doneusing the wrapper classes discussed in the next section.The vector class supports a number ofmethods that can be used to manipulate the vectors created.
  78. 78. list.addElement(item)//Adds the item specified to the list at the endlist.elementAt(10)//Gives the name of the 10th objectlist.size()//Gives the number of objects presentlist.removeElement(item)//Removes the specified item from the listlist.removeElementAt(n)//Removes the item stored in the nth position of the list.list.removeAllElements()//Removes all the element in the listlist.copyInto(array)//Copies all items from list to arraylist.insertElementAt(item,n)//Inserts the item at nth position.Wrapper ClassesVectors not handled primitive data types like int,long,char and double. Primitive data types maybe converted object types by using the wrapper classes contained in the java.lang package.Wrapper class for convering primitive data types are given below
  79. 79. Simple type Wrapper Classboolean Booleanchar Characterdouble Doublefloat Floatint Integerlong LongThe Wrapper classes have number of unique methods for handling primitive data types andobjects.Converting Primitive Numbers to Object Numbers Using Constructor Methods :Integer IntVal=new Integer(i);//Primitive integer to Integer Objects here i as primitive data values.Converting Object Numbers to primitive Numbers using typeValue() methodint i=IntVal.intValue();//Object to primitive integerConverting Numbers to Strings Using toString() methodstr=Integer.toString(i);//Primitive integer to string
  80. 80. Converting String Objects to Numeric Objects using the Static Method valueOf()IntVal=Integer.valueOf(str);//converts string to Integer objectsConverting Numeric Strings to Primitive Numbers using Parsing Methodint i=Integer.parseInt(str);//converts string to primitive integer.
  81. 81. Input and Output in JavaFiles in JavaThe Path Name While dealing with the files, a source of confusion for a beginner in Java programming is the path name. For example, consider the following path name on a Unix/Linux machine: /java/scjp/temp The first forward slash represents the root directory. This path name in Windows machines may be written as C:javascjptemp
  82. 82. Constructors for the File ClassFile(String pathname) Creates an instance of the File class by converting the path name String to an abstract path name.File(String parent, String child) Creates an instance of the File class by concatenating the child String to the parent String, and converting the combined String to an abstract path name.File(File parent, String child) Creates an instance of the File class by constructing an abstract path name from the abstract path name of the parent File, and the String path name of child.
  83. 83. Example:File f1 = new File("java/scjp");File f2 = new File("java/scjp", "temp/");File f3 = new File(f1, "temp/"); An instance of the File class is immutable. This means that once you have created a File object by providing a path name, the abstract path name represented by this object will never change. When you create an instance of the File class, no real file is created in the file system.
  84. 84. Methods Of File Class:boolean canRead():boolean canWrite():boolean createNewFile():boolean delete():boolean exists():String getAbsolutePath():String getCanonicalPath():String getName():String getParent():boolean isAbsolute():boolean isDirectory():boolean isFile():String[] list():String[] listFiles():boolean mkDir():boolean mkDirs():
  85. 85. Understanding StreamsWhether the source or destination is a file or a socket, any read orwrite is performed in three simple steps: 1. Open the stream. 2. Until there is more data, keep reading in a read, or writing in a write. 3. Close the stream.
  86. 86. The Low-Level StreamsA low-level input stream reads data and returns it in bytes, and alow-level output stream accepts data as bytes and writes the outputin bytes. Two examples of low-level streams are represented by theclasses FileInputStream and FileOutputStream, which aresubclasses of InputStream and OutputStream, respectively. The FileInputStream ClassThe FileInputStream class is designed for reading image files as itreads a stream of raw bytes.Constructors: FileInputStream(File file) FileInputStream (String name)
  87. 87. Methods of FileInputStreamint read() throws IOException: Returns the next byte of data, or -1if the end of the file is reachedint read(byte[] bytes) throws IOException: Reads bytes.lengthnumber of bytes from the stream into an array, and returns thenumber of bytes read, or -1 if the end of the file is reachedint read(byte[] bytes, int offset, int len) throws IOException:Reads up to a total of len bytes (starting from offset) into an array,and returns the number of bytes read, or –1 if the end of the file isreachedvoid close(): Closes the input stream and releases any systemresources assigned to the stream
  88. 88. The FileOutputStream ClassThe FileOutputStream class is meant for writing streams of rawbytes into files, such as image files.Constructors: FileOutputStream(File file) FileOutputStream (String name) Methods of FileOutputStreamvoid write(int b) throws IOException: Writes the passed-in byte tothe streamvoid write(byte[] bytes) throws IOException: Writes bytes.lengthnumber of bytes from the passed-in array to the streamvoid write(byte[] bytes, int offset, int len) throws IOException:Writes up to a total of len bytes (starting from offset) from thepassed-in array to the streamvoid close(): Closes the output stream and releases any systemresources assigned to the stream
  89. 89. Example code: 1. import*; 2. public class FileByteCopier { 3. public static void main(String[] args) throws IOException { 4. File inputFile = new File("scjp.txt"); 5. File outputFile = new File("scjpcopy.txt"); 6. FileInputStream in = new FileInputStream(inputFile); 7. FileOutputStream out = new FileOutputStream(outputFile); 8. int c; 9. while ((c = != -1)out.write(c); 10. in.close(); 11. out.close(); 12. } 13.}
  90. 90. The High-Level StreamsWhen the unit of information you are interested in is a high-level datatype such as a float, an int, or a String, and you don’t want to deal withbytes directly, you can work with high-level streams.Two examples of high-level streams are DataInputStream andDataOutputStream.
  91. 91. DataInputStream classconstructor for the DataInputStream class is: public DataInputStream(InputStream in)Methods of DataInputStream class boolean readBoolean() throws IOException byte readByte() throws IOException char readChar()throws IOException double readDouble() throws IOException float readFloat() throws IOException int readInt() throws IOException long readLong() throws IOException short readShort() throws IOException
  92. 92. The DataOutputStream ClassThe constructor for the DataOutputStream class is public DataOutputStream(OutputStream out)Methods of DataOutputStream class void writeBoolean(boolean b) throws IOException void writeByte(byte b) throws IOException void writeBytes(String s) throws IOException void writeChar(int c) throws IOException void writeChars(String s) throws IOException void writeDouble(double d) throws IOException void writeFloat(float f) throws IOException void writeInt(int i) throws IOException void writeLong(long l) throws IOException void writeShort(short s) throws IOException
  93. 93. Readers and WritersTo read data in text format,Java offers so-called reader and writerstreams. Note that some authors do not refer to readers and writersas streams. All the classes corresponding to reader and writerstreams are subclasses of the Reader and Writer classes and areused to read character streams. Low-Level Readers and WritersThe low-level reader streams read data and return it in characters,and low-level output streams accept data as characters and writethe output in characters. Two examples of low-level reader andwriter streams are FileReader and FileReader.
  94. 94. The FileReader ClassConstructors for the FileReader Class FileReader(File file) FileReader(String name)Methods of the FileReader Class int read() throws IOException: Returns the next character of data, or -1 if the end of the file is reached int read(char[] cbuf) throws IOException: Reads characters from the stream into the array cbuf, and returns the number of characters read, or -1 if the end of the file is reached int read(char[] cbuf, int offset, int len) throws IOException: Reads up to a total of len characters (starting from offset) into the array cbuf, and returns the number of chars read, or –1 if the end of file is reached void close(): Closes the input stream and releases any system resources assigned to the stream
  95. 95. The FileWriter ClassConstructors for the FileWriter Class FileWriter(File file) FileWriter(String name)Methods of the FileWriter Class void write(int c) throws IOException: Writes the passed-in single character to the stream void write(char[] ch) throws IOException: Writes ch.length number of characters from the passed-in array to the stream void write(String str) throws IOException: Writes the passed- in string to the stream void write(char[] cbuf, int offset, int len) throws IOException: Writes up to a total of len characters (starting from offset) from the passed in array to the stream
  96. 96. void write(String str, int offset, int len) throws IOException:Writes up to a total of len characters (starting from offset) from thepassed-in string to the streamvoid flush() throws IOException: Flushes the stream, whichmeans the remaining(buffered) data that you have written to thestream is sent out to the file before closingvoid close(): Closes the output stream and releases any systemresources assigned to the stream
  97. 97. Example Code: 1. import*; 2. public class FileByteCopier { 3. public static void main(String[] args) throws IOException { 4. File inputFile = new File("scjp.txt"); 5. File outputFile = new File("scjpcopy.txt"); 6. FileReader in = new FileReader(inputFile); 7. FileWriter out = new FileWriter(outputFile); 8. int c; 9. while ((c = != -1)out.write(c); 10. in.close(); 11. out.flush(); 12. out.close(); 13. } 14.}
  98. 98. High-Level Readers and WritersAs you know, you can use DataInputStream and DataOutputStreamto read and write the primitive types in binary format. Similarly, youcan read and write characters in character streams in big chunks(buffers) and in text format by using the BufferedReader andBufferedWriter classes, respectively. BufferedReader and BufferedWriter Classesconstructors: BufferedReader(Reader in); BufferedReader(Reader in, int size); BufferedWriter(Writer out); BufferedWriter(Writer out, int size);
  99. 99. Example Code: 1. import*; 2. public class FileBufferCopier { 3. public static void main(String[] args) throws IOException { 4. File inputFile = new File("scjp.txt"); 5. File outputFile = new File("scjpcopy.txt"); 6. BufferedReader in = new BufferedReader(new FileReader(inputFile)); 7. BufferedWriter out = new BufferedWriter(new FileWriter(outputFile)); 8. String line; 9. while ((line = in.readLine()) != null){ 10. out.write(line); 11. out.newLine(); 12. } 13. in.close(); 14. out.close(); 15. } 16.}
  100. 100. The PrintWriter ClassThe PrintWriter class, a subclass of the Writer class.Constructor for the PrintWriter class: PrintWriter (Writer out, true)The most commonly used methods of the PrintWriter class arepublic void print(…) and public void println(…)
  101. 101. Exceptions During I/O Operations
  102. 102. Object Streams and SerializationJava offers high-level streams ObjectInputStream andObjectOutputStream, which, when chained to low-level streamssuch as FileInputStream and FileOutputStream, can be used byprograms to read and write objects. The process of writing an objectto somewhere is called object serialization, and the process ofreading a serialized object back into the program is calleddeserialization.The goal here is to save the state of an object.
  103. 103. To make the objects of a class serializable, the class mustimplement the interface Serializable:class MySerialClass implements Serializable{// body of the class}The Serializable interface is an empty interface (i.e. no methods aredeclared inside it) and is used to just tag a class for possibleserialization.
  104. 104. Writing with ObjectOutputStream To write an object to a file, you use the ObjectOutputStream to write it to a low-level stream, which in turn will write it to the file. For example, consider the following code fragment: FileOutputStream out = new FileOutputStream("objectStore.ser"); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject("serialOut"); os.writeObject(new MySerialClass()); os.writeObject("End of storage!"); os.flush();
  105. 105. following are saved in serialization:The values of the instance variables of the serialized object.The class description of the object, which includes the class name,the serial version unique ID, a set of flags describing theserialization method, and a description of the data fields.All the objects that a serialized object refers to through objectreference variables. That means those objects must be serializable;otherwise, you will get a compiler error.
  106. 106. Reading with ObjectInputStream The objects can be read back in the same order in which they were stored. Here is a code fragment that reads inthe String and the Date objects that were written to the file named objectStore.ser in the previous example: FileInputStream in = new FileInputStream("objectStore.ser"); ObjectInputStream is = new ObjectInputStream(in); String note = (String)is.readObject(); MySerialClass serialIn1 = (MyClassSerial)is.readObject(); MySerialClass serialIn2 = (MyClassSerial)is.readObject();
  107. 107. Note the following points about serialization:If a class is serializable, then all the subclasses of this superclassare implicitly serializable even if they don’t explicitly implement theSerializable interface.If you want to serialize an array (or some other collection), each ofits elements must be serializable.Static variables are not saved as part of serialization. Recall that thepurpose of serialization is to save the state of an object, and a staticvariable belongs to the class and not to an object of the class.
  108. 108. MultithreadingMultitheading is specialized form of multitasking. like windows and other os uses multitaskingtechnique i.e. they handled more than one process at a time, the same thing we can do in Javausing multithreading technique.A thread is similar to a program that has a single flow of control. It has a beginning, a body, andan end,and executes commands sequentially. Java enables us to use multiple flows of control indeveloping programs.Each flow of control is represented by thread that runs parallel to others. i.e. a program thatcontains multiple flows of control is known as multithreaded program.Threads in Java aresubprograms of a main application program and share the same memory space, known aslightweight threads or lightweight process.Threds running in parallel does not mean that they actually run at the same time. Since all thethreads are running on the same processor, the flow of execution is shared between the threads.The Java interpreter handles the switching of control between the threads in such a way that itappears they are running concurrently.Creating Threads :Threads are implemented in the form of objects that contain a method called run(). The run()methodis the heart and soul of any thread.
  109. 109. public void run(){....(statements for implementing threads)}The run() method should be invoked by an object of the concerned thread. This can be achievedbycreating the thread and initiating it with the help of another thread method called start().A new thread can be created in two ways.1. By creating a thread class : Define a class that extends Thread class and override its run()methodwith the code required by the thread.2. By converting a class to a thread :Define a class that implements Runnable interface. TheRunnableinterface has only one method, run(), that is to be defined in the method with the code to beexecuted by the thread.
  110. 110. Extending the Thread Class :We can make our class as runnable as a thread by extending the class java.lang.Thread. Thisgives us accessto all the thread methods directly. steps1. Declare a class as extending the Thread class2. implement the run() method that is responsible for executing the sequence of code that thethread will execute.3. Create a thread object and call the start() method to initiate the thread execution.Stopping and Blocking a ThreadStopping a ThreadWhenever we want to stop a thread from running further, we may do so by calling its stop()method,likeaThread.stop();This statement causes the thread to move to the dead state. A thread will also move to the deadstate automatically when it reaches the end of its method.
  111. 111. Blocking a ThreadA thread can also be temporarily suspended or blocked from entering into the runnable andsubsequentlyrunning state by using either of the following thread methods:sleep();//blocked for a specified timesuspend();//blocked until further orderswait();//blocked until certain condition occursThese methods causes the thread to go into the blocked (or non- runnable) state.the thread willreturn to the runnable state when the specified time is elapsed in the case of sleep(), the resume()method is invoked in the case of suspend(), and the notify() method is called in the case of wait().Life Cycle of a ThreadDuring the life time of a thread, there are many states it can enter. they include :1. Newborn state2. Runnabke state3. Running state4. Blocked state5. Dead State
  112. 112. LIFE CYCLE OF A THREAD New Thread Newborn stop start stopActive Running Runnable Dead yieldThread Killed Thread suspend resume sleep notify stop wait Idle Thread Blocked (Not Runnable
  113. 113. Newborn StateWhen we create a thread object, the thread is in born and is said to be in newborn state. The thread isnot yet scheduled for running. At this state we can do only one of the following things with it:•Schedule it for running using start()•Kill it using stop()If scheduled it moves to the runnable state. If we attempt to use any other method at this stage,an exception will be thrown.Runnable StateThe runnable state means thread are ready for execution and is waiting for thethe availabilty of the processor. i.e. the thread has joined the queue of threads that are waitngfor execution. If all threads have equal priority, then they are given time slots for execution in roundrobin fashion,i.e.,first-come,fisrt-server manner. The thread that relinquishes control joins the queue at the end againwaits for its turn.This process of assigning time to threads is known as time-slicing.
  114. 114. However,if we want a thread to relinquish control to another thread of equal priority before its turncomes, we can do so be using the yield() method.Running StateRunning means that the processor has given its time to the thread for its execution.The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. Arunning thread may relinquish its control in one of the following situations.1. It has been suspended using suspend() method. Suspend() can be revived by using the resume()method.2. It has made to sleep. We can put a thread a sleep for a specified time period using the methodsleep(time) where time is in milliseconds. This means that the thread is out of the queue during this timeperiod.3. It has been told to wait until some event occurs. This is done by using wait() method. The thread canbe scheduled to run again using the notify() method.Blocked StateA thread is said to be blocked when it is prevented from entering into the runnable state andsubsequently the running state. This happens when the thread is suspended,sleeping, or waiting in orderto satisfy certain requirements. A blocked thread is considered "not runnable" but not dead and thereforefully qualified to run again.
  115. 115. Dead StateEvery thread has a life cycle. A running thread ends its life when it has completed executing itsrun() method. It is natural death. However, we can kill it by sending the stop message to it at anystate thus causing a premature death to it.Thread PriorityIn java each thread is assigned a priority, which affects the order in which it is scheduled forrunning. The threads that we have discussed so far are of the same priority. The threads of the samepriority are given equal treatment by the java schedular and,therefore,they share the processor onfirst-come,fist-serve basis.JAva permits us to set the priority of a thread using the setPriority() method as follows:ThreadName.setPriority(intNumber);the intNumber is an integer value to which the threads priority is set. The Thread class definesseveral priority constants :MIN_PRIORITY=1NORM_PRIORITY=5MAX_PRIORITY=10
  116. 116. intNumber may assume one of these constants or any value between 1 and 10.the default setting isNORM_PRIORITY.By assigning priorities to threads, we can ensure that they are given the attention they deserve.For example, we may need to answer an input as quickly as possible. Whenever multiple threads areready for execution, the java system chooses the highest priority thread and executes it. For a threadof lower priority to gain control, one of the following thing should happen :1. It stops the running of the run()2. It is made to sleep using sleep()3. It is told to wait using wait()However, If another thread of higher priority comes along, the currently running thread will bepreempted by the incomming thread thus forcing the current thread to move to the runnable state.Rememberthat the highest priority thread always preempts any lower priority threads. SyncronizationWhen multiple threads access shared data then sometimes Data corruption occurs if Multithreadedprograms is not designed correctly that leads to system failure.Unfortunately, such problems canoccur at unpredictable times and be very difficult to reproduce.
  117. 117. As an example, consider A bank account that is shared by multiple customers. Each of these customers can make deposits to or withdrawals from this account. That application might have a separate thread to process the actions of each user. Time Thread A Thread B Balance t0 Read Balance $0 t1 Context Switch $0 t2 Read Balance $0 t3 $0 t4 Add $10 to Balance $10 t5 Context Switch $10 t6 Add $10 to Balance $10 Fig 1 Thread SchedulingFig 1 depicts one possible scheduling of these threads. At time t0, the account balance is zero. Thread A isexecuting and wants to deposit $10 to the account. The current value of the account is read at time t1.However, a context switch from thread A to thread B then occurs at time t2. Thread B then reads the value ofthe account at time t3. It increments this value by $10 at time t4. Another context switch occurs at time t5.This returns control to Thread A. At time t6, it sets account balance to $10.
  118. 118. The net effect of this sequencing is that the final account balance is only $10. It should be $20.Data corruption has resulted.The solution to this problem is to synchronize the access to this common data. This can be donein two common ways. First a method can be synchronized by using the synchronized keyword asa modifier in the method declaration.When a thread begins executing a synchronized instance method, it automatically acquires a lockon that object. The lock is automatically relinquished.When the method completes. Only one method may have this lock at any time. Therefore, onlyone method may execute any of the synchronized instance method for that same object, the JVMautomatically causes the second thread to wait until the first thread relinquishes the lock.Another way to synchronize access to common data is via a syncronized statement block. Thesyntax is :Synchronize(obj) {//statement block}Here, obj is the object to be blocked. If you wish to protect the instance data, you should lockagainst that object. If you wish to protect against the class data, you should lock the appropriateClass object. One important benefit of Java class libraries is that they are designed to be thread-safe. In other words, multiple threads may access their methods.
  119. 119. DeadlockDeadlock is an error that can be encountered in multithreaded programs. It occurs when two ormore thread wait indefinitely for each other to relinquish locks. Assume that thread 1 holds a lockon object 1 and waits for a lock on object 2. Thread 2 holds a lock object 2 and waits for a lock onobject 1. Neither of these method may proceed. Each waits forever for the other to relinquish thelock it needs. Thread CommunicationIn deadlock you have seen that how thread acquires a lock and does not relinquish it. In Threadcommunication threads can communicate with each other. Thread can temporarily release a lock soother threads can have an opportunity to execute a synchronized method or statement block. Thatlock can be acquired again at a later time.A class objects defines three methods that allow threads to communicate with each other. Thewait() method allows a thread that is executing a synchronized method or statement block on thatobject to release the lock and wait for a notification from another thread. It has these three forms :Void wait() throws InterruptedExceptionVoid wait(long msec) throws InterruptedExceptionVoid wait(long msec,int nsec) throws InterruptedExceptionThe first form causes the current thread to wait indefinitely. The second form causes the thread towait for a msec milliseconds. The last form causes the current thread to wait for msec millisecondsplus nanoseconds.
  120. 120. notify() method allows a thread that is executing a synchronized method or statement block tonotify another thread that is waiting for a lock on this object. If several threads are waiting, onlyone of these is selected. The selection criteria are determined by the implementer of the JVM. Thesignature is : void notify()It is important to understand that when a thread executes the notify() or notifyAll() method it doesnot relinquish its lock at that moment. This occurs only when it leaves the synchronized method orstatement block.
  121. 121. APPLETAn applet is a program that can be referenced by the html source code of web page. It isdynamically downloaded from a Web Server to a browser. The applet then executes within theenvironment provided by the browser. Alternatively you may use a tool such as the appletviewerto run it.It is important to recognize that downloading code from the Internet and executing it on yourcomputer is inherently dangerous. Therefore, applet do not have the same capabilities as Javaapplications. They are restricted to operating within the confines of a “sandbox”. In other wordscode that is “untrusted” is not allowed to operate outside certain boundaries.For Example, applets are normally not allowed to read or write to your local disk. This wouldobviously be risky because they could accidentally or maliciously destroy any data stored on thatdevice.Applet can not execute any native code.An applet may open a socket connection back to the host from which it was downloaded, but notto any other host. The reason for this restriction can be understood if you imagine a configurationin which a firewall protects a corporate Intranet from computer hackers. Assume that anemployee has downloaded an applet from internet to an PC or workstation. If that applet isallowed to open sockets to any machine, it would then have the potential to steal proprietaryinformation and send back to the hacker’s machine. This must be prevented. Therefore, an appletis not allowed to contact any of those private machines.
  122. 122. Difference between Applet and Application Applet are not full-featured application programs. They are usually written to accomplish a small task or a component of a task. Since they are usually designed for use on the Internet, they impose certain limitations and restrictions in their design.• Applet do not use main() method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code.• Unlike stand-alone applications, applet can not be run independently. They are run from inside a web page using a special feature known as HTML tag.• Applets cannot red from or write to the files in the local computer.• Applets cannot run any program the local computer.Writing Applet Program9. Building an applet code (.java file).10. Creating an executable applet(.class file).11. Designing a Web Page using HTML tags.12. Preparing <Applet> tag, Incorporating <applet> tag into the Web Page.5. Creating HTML file. Testing the applet code