SlideShare ist ein Scribd-Unternehmen logo
1 von 175
JAVA FUNDAMENTALS ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
History of Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JDK & JRE ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Byte Code & JVM(Java Virtual Machine)  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Platform Independent ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Application and Applets ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java Compiler Java Program Java Interpreter Machine Code Virtual Machine Bytecode Source Code Bytecode Virtual Machine Real Machine Process of Compilation Process of Converting bytecode into machine code
Java Source Code Java Compiler Java Enabled Browser Java Interpreter Output Output Application Type Applet Type
Principal of OOPs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Inheritance :-  Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without 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 The class Shape defines a method called getArea() that returns the area of a shape. However, this method is not implemented by that class. Therefore, it is an abstract method and Shape is an abstract class. This means that no objects of class Shape can be created. However, the functionality of that class can be inheritated by its subclass. The various subclasses of Shape like Ellipse,Rectangle,Triangle do implement the getArea() method. Ellipse Rectangle Triangle
First Java Application ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Class Declaration The first line public class HelloWorld declares a class, which is an Object-Oriented construct. 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 a new class definition follows. Opening Bace Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”, appearing in the last line in the example. The main() method Every java application program must include the main() method. This is starting point for the interpreter to begin the execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate the execution. Public :  The Keyword public is an access specifier that declares the main method as unprotected and therefore making it to accessible to all other classes. Static :  The keyword static which declares this method as one that belongs to the entire Class and not a part of any Objects of the class.
The main must always be declared be declared as static since the interpreter uses  this 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 objects  Of the class type String. The Output Line The only executable Statement in the program is System.out.println("Hello World!!"); Since Java is a true Object Oriented Language, every method must be part of an  Object. The println method is a member of the out Object, which is static data  Member of the System class. This line prints Hello World!! to the screen. The method println always appends a newline character to the end  of the string.
Compile the Code To compile the program, you need to first install the JDK. Then, use the program  javac included with the JDK to convert the text in listing 7.1 to code which the  computer can run. To run javac, on a Macintosh drag the source file over the javac  icon. On any other computer, type the line: javac HelloWorld.java  at a command prompt. The javac program creates a file called HelloWorld.class  from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as  bytecodes  which can be run by the Java interpreter.  Run the Program Now that you have compiled the program, you can run it by typing at the command prompt: java HelloWorld   After you do this, the computer should print to the screen Hello World!! That may not seem very interesting, but then it's a simple program. If you don't see the Hello World!! on the screen, go back and make sure you have typed in the file exactly as shown in listing 7.1, and make sure that you called the file HelloWorld.java.
JAVA CONTROLS ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Variables and Constants ,[object Object],[object Object],Integer Constants : Refers to a sequence of digits. There are three types of Integers, namely, decimal,octal and hexadecimal integer. Decimal Integer consist of of a set of digits, 0 through 9, preceded by an optional minus sign. An octal integer constant consists of any combination of digits from the set 0 through 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. Java Constant Numeric Constant Character Constant Integer    Real  Character  String
Real Constants : Integer constant are inadequate to represent quantities that vary continuously, such as distance, heights, temperature, prices and so on. These quantities 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 exponential notation. e2 means multiply by 10 2 . 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.
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” ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Data Types Integer Types Java 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 : Data Types in Java Primitive (Intrinsic) Non-Primitive ( Derived) Numeric Non-Numeric Classes Arrays Integer Floating Point Character Boolean Interface
The Java integer primitive types. Integer literals can be specified in decimal, hexadecimal, or octal notation. To specify a decimal  value, simply use the number as normal. To indicate that a literal value is a long, you can append  either "L" or "l" to the end of the number. Hexadecimal values are given in base 16 and include  the 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. 9,223,372,036,854,775,807 -9,223,372,036,854,775,808 64 long 2,147,483,647  -2,147,483,648 32 int 32,767  -32,768 16 short 255 -256 8 byte Maximum Value   Minimum Value Bit Size   Type
Table 3.7. Examples of integer literals. Floating-Point Types Support for floating-point numbers in Java is provided through two primitive types-float and double, which are 32- and 64-bit values, respectively. Similar to integer literals are Java's 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  0x64 0144  100L 100 0x10 020  16L 16 0XF 017  15L 15 0xA 012  10L 10 0x1 01 1L  1 0x0 0 0L  0 Hexadecimal   Octal Long Integer
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.02e23d Boolean :-  Java supports two Boolean literals-true and false.  Character Literals :- A character literal is a single character or an escape sequence enclosed in single quotes, for example, 'b'. Escape sequences are used to indicate special characters or actions, such as line feed, form feed, or carriage return. The available escape sequences ar shown in Table 3.8.  String Literals Although there is no string primitive type in Java, you can include string literals in your programs. 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. As examples of string literals, consider the following: "A String“,"Column 1Column 2”
Table 3.8. Escape sequences. Unicode character xxxx Backslash  Single quote apos; Double quote amp;quot;  Carriage return  Form feed  Line feed  Horizontal tab  Backspace  Purpose   Sequence
Arithmetic Operators and Expressions An expression is a operators and operands. It follows the rules of algebra and should be familiar. Java allows several types of expressions. The arithmetic operators are given below : +   addition -  subtraction *  multiplication /   division %   modulus +=   addition assignment -=  subtraction assignment *=multiplication assignment /=division assignment %=  modulus assignment ++  increment,--  decrement
An expression may appear on the right side of an assignment statement. For example, Int answer; Answer=100*31; Java expression may contain Variables, constants or both. For example assuming that answer and count are variables, this expression is perfectly valid. Answer=count-100;
Increment/Decrement Operators The  increment  and  decrement operators  are used with one variable (they are known as  unary operators ): ++ increment operator  --  decrement operator  For instance, the increment operator (++) adds one to the operand, as shown in the next line of code: x++;  is the same as  x+=1; The increment and decrement operators behave slightly differently based on the side of the operand 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 code fragment, the result of y is 6: int x=5;int y=++x;  // y=6 x=6  If the operator appears after the operand, the addition occurs after the value is taken. So y is 5 as shown in the next code fragment. Notice that in both examples, x is 6 at the end of the fragment. int x=5;int y = x++;  //y=5 x=6  Similarly, the decrement operator (--) subtracts one from the operand, and the timing of this is in relation to the evaluation of the expression that it occurs in.
The Relational Operators The most intuitive comparative operators are those that fall into a category known as relational operators.  Relational operators  include those standard greater-than and 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, you know 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 to evaluating 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 to  The following two assignment statements produce identical results: result1 = a+b < c*d ; result2 = (a+b) < (c*d) ;  Logical Expressions The third set of evaluation operators fall into a category known as logical expressions.  Logical expressions  work a bit differently than the previous operators, and are probably not something you covered in your third grade math class.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],true true true true true false false true true false true false false false false false (A || B) (A && B) And when B is When A is
The Conditional Operator The conditional operator is the one ternary or triadic operator in Java, and operates as it does in C and C++. It takes the following form: expression1  ?  expression2  :  expression3 In 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. If  expression1  is false, then  expression3  is evaluated, and its result is the value of the conditional. Consider the following examples. The first is using the conditional operator to determine the maximum of two values; the second is determining the minimum of 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 convince yourself that none of the three examples requires any brackets in order to be evaluated correctly.
Type Conversion in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Conversions and the Cast Operator : Normally with implicit conversion, the conversion is so natural that you don't even notice. Sometimes though it is important to make sure a conversion occurs between two types. 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 operator with high precedence and comes before its operand, the result of which is a variable of the type specified by the cast, but which has the value of the original object. The following 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 in a 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 other type, and objects can only be converted to a parent class. Casting and Converting Integers The 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...).
Casting and Converting Characters Characters 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 lose some data. In fact, even if you convert between a character and a short you an loose some data. If you are using the Han character set (Chinese, Japanese, or Korean), you can lose data by casting a char into a short (16-bit integer), because the top bit will be lost. Casting and Converting Booleans There 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 on the current value of a Boolean, use an if-else statement, or imitate the following code: 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, and anything else equal to true as follows: int j;boolean tf;...tf = (j!=0);  // Boolean tf is true if j is not 0, false otherwise.
Comments in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Java comment delimiters are summarized in Table 3.1. Table 3.1. Java comment delimiters. The enclosed text is treated as a comment by the compiler but is used by JavaDoc to automatically generate documentation.  */ /** The rest of the line is treated as a comment.  (none) // The enclosed text is treated as a comment.  */ /* Purpose End Start
Java Control Statements if Selection Statement Iteration Statement Jump Statement If-else switch while do for break continue return Control Statement
Selection Statement :  These select one of several control flows. There are three 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 control the flow of execution of statements. It is a two-way decision statement and is used 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 on whether the value of the expression (relation or condition) is ‘true’ or ‘false’. It transfers the control to a particular statement. If the statement is true then the Statement block will be executed;otherwise the statement-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-block and statement-x are executed in sequence.
Example : Class Demo { public static void main(String args[]) { If(args.length==0) System.out.println(“You must have command line arguments”); }} If-else statement if(test expression) { True-Block Statement(s); } Else { False-Block statement(s); } Statement-x;
If the test expression is true, then the true-block statement(s) executed immediately following to the if statement, are executed; otherwise the false statement(s) will be executed, not both.In both the cases, the control is transferred subsequently to the statement-x. Nesting of If—else Statement If(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 it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated;otherwise statement-2 will be evaluated and then control is transferred to the statement-x.
Switch Statement:  The Java switch statement is ideal for testing a single expression against a series of possible values and executing the code associated 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;
Iteration Statement :  These specify how and when looping will take place. There are three types of Iteration statements: while, do and for The for Statement  The first line of a for loop enables you to specify a starting value for a loop counter, specify the test condition that will exit the loop, and indicate how the loop counter should be incremented after each pass through the loop. This is definitely a statement that offers a lot of bang for the buck. The syntax of a Java for statement is as follows:  for (initialization; testExpression; incremement)     statement  For example, a sample for loop may appear as follows:  int count; for (count=0; count<100; count++)     System.out.println(&quot;Count = &quot; + count);  In this example, the initialization statement of the for loop sets count to 0. The test expression, count < 100, indicates that the loop should continue as long as count is less than 100. Finally, the increment statement increments the value of count by one. As long as the test expression is true, the statement following the for loop setup will be executed, as follows:  System.out.println(&quot;Count = &quot; + count);  Of course, you probably need to do more than one thing inside the loop. This is as easy to do as using curly braces to indicate the scope of the for loop.
The while Statement Related to the for loop is the while loop. The syntax for a while loop is as follows:  while (booleanExpression)     statement  As you can tell from the simplicity of this, the Java while loop does not have the built-in support for initializing and incrementing variables that its for loop does. Because of this, you need to be careful to initialize loop counters prior to the loop and increment them within the body of the while loop. For example, the following code fragment will display a message five times:  int count = 0; while (count < 5) {     System.out.println(&quot;Count = &quot; + count);     count++; }  The do…while Statement  The final looping construct in Java is the do…while loop. The syntax for a do…while loop is as follows:  do {     statement } while (booleanExpression);
This is similar to a while loop except that a do…while loop is guaranteed to execute at least once. It is possible that a while loop may not execute at all depending on the test expression used in the loop. For example, consider the following method:  public void ShowYears(int year) {     while (year < 2000) {         System.out.println(&quot;Year is &quot; + year);         year++;     } }  This method is passed a year value, then loops over the year displaying a message as long as the year is less than 2000. If year starts at 1996, then messages will be displayed for the years 1996, 1997, 1998, and 1999. However, what happens if year starts at 2010? Because the initial test, year < 2000, will be false, the while loop 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 loop has executed for each pass, it will always be executed at least once. This is a very valid distinction between the two types of loop, but it can also be a source of potential errors. Whenever you use a do…while loop, you should be careful to consider the first pass through the body of the loop.
Jumping Of course, it is not always easy to write all of your for, while and do…while loops so that they are easy to read and yet the loops terminate on exactly the right pass through the loop. Java makes it easier to jump out of loops and to control other areas of program flow with its break and continue statements.  The break Statement Earlier in this chapter, you saw how the break statement is used to exit a switch statement. In a similar manner, break can be used to exit a loop  As an example of this, consider the following code:  int year = 1909; while (DidCubsWinTheWorldSeries(year) == false) {     System.out.println(&quot;Didn't win in &quot; + year);     if (year >= 3000) {         System.out.println(&quot;Time to give up. Go White Sox!&quot;);         break;     } } System.out.println(&quot;Loop exited on year &quot; + year);
This example shows a while loop that will continue to execute until it finds a year that the Chicago Cubs won the World Series. Because they haven't won since 1908 and the loop counter year starts with 1909, it has a lot of looping to do. For each year they didn't win, a message is displayed. However, even die-hard Cubs fans will eventually give up and change allegiances to the Chicago White Sox. In this example, if the year is 3000 or later, a message is displayed and then a break is encountered. The break statement will cause program control to move to the first statement after the end of the while loop. In this case, that will be the following line:  System.out.println(&quot;Loop exited on year &quot; + year);  The continue Statement  Just as a break statement can be used to move program control to immediately after the end of a loop, the continue statement can be used to force program control back to the top of a loop
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
varName=new type[size]; Here varName is name of the array, type is a valid Java type, and size specifies the number of elements in the array. You can see that the new operator is used to allocate memory for the array. These two steps combines like type 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 variable name that can hold 10 integer values. Multidimensional Array : In addition to one dimensional we can create arrays of two or more dimensions. In Java, Multidimensional array are implemented as arrays of arrays. You need to perform two steps to work with multidimensional arrays : 1. Declare the array and 2. allocate space for its elements.
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.
JAVA Classes and Methods ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The General Form of Class A class array contains three types of items : variable,methods, and constructors. Variable represent its state. Method provide the logic that constitutes the behavior defined by a class. The variable and methods can be both static and instance variable. Constructors initialize the state of a new instance of a class. The Simplified form of a class is : class clsName { //instance variable declarations type1 varName1=value1; type2 varName2=value2; … .. //constructor clsName(cparams1) { // body of constructor }
clsName(cparamsN) { //body of constructor } … //methods rtype1 mthName(mparams1) { //body of method } … .. } } The keyword class indicates that a class named clsName is being declared. This name must follow the Java naming convention for identifiers. The instance Variables named varName1 through varNameN included using the normal variable declaration syntax. Each variable must be assigned a type shown as
type1 through typeN and may be initialized to value shown as value1 through valueN. Constructors always have the same name as the class. They do not have return values. Method named mthName1 through mthNameN can be included. The return type of the methods are rType1 through rtypeN, and their Optional Parameter lists are mparams1 through mparamsN. Constructors Often an object will require some form of initialization when it is created. To accommodate this, Java allows you to define constructor for your classes. A Constructor is a special method that creates and initializes an object of a particular class. It has the same name as its class and may accept arguments. Constructor does not have a return type. Instead, a constructor returns a reference to the object that it creates.  Constructor Overloading A class may have several constructors. This feature is called constructor overloading. When constructors are overloaded each is still called by the name of its class. However it must have a different parameter list. i.e. Signature of each constructor must differ.
Method Overloading Like Constructor, method can also be overloaded. This occurs when two or more methods have the same name but different signature. Recall that the signature of a 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 that basically 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 a different type. Another advantage of method overloading is that it provides an easy way to handle default parameter values.  The New Operator Objects are created using the new operator. The new Operator creates an instance 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 to create an instance.) A reference to the new object is assigned to a variable named objRef. Notice the expression immediately to the right of the keyword new. This is known as constructor. A constructor creates an instance of the class. It has the same name as the class and may optionally have an argument list args.
Garbage Collection Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable. It prevents programming errors that could otherwise occur by incorrectly deleting or failing to delete objects. An object becomes eligible for garbage collection when it is no longer referenced by any Variable. However, the JVM determines exactly when this task is performed. finalize method : Constructor method used to initialize an object when it is declared. This process is known as initialization. Similarly, Java supports a concept called finalization, which is just opposite to Initialization. We know that java run-time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalizer method. This is similar to destructor of C++. The finalizer method is simply finalize() and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.
Command Line Arguments All java application contain a static method named main().This method takes one argument that is an array of String objects. These objects represent any arguments that may have been entered by the user on the command line. The number of command line arguments is obtained via the expression args.length. This is an int type. The individual arguments are accessed as arg[0],args[1],args[2], and so forth. The System Class The system class defines several attributes relate to the run-time environment. It has a static variable named out that contains a reference to a PrintStream object. The print() and println() methods of that object display their string arguments on the standard output. The static variable  err  also holds 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 current application.
Using Classes and Methods ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Instance Variables and Methods Each 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. Instance variable 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 Methods A static variable is shared by all objects of its class and thus relates to the class itself. A static variable may be declared by using the static keyword as a modifier as 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 the memory.
A static method may be declared by using the static keyword as a modifier. A static method acts relative to a class. It deos not act on specific objects of its class. 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 optional list of parameter types shown as mparams may be specified. String Class Strings 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 a variety of string manipulation tasks like compareTo()  method used to sort an array of strings in alphabetical order.
Math Class Mathematical functions such as cos,sqrt, log etc. are frequently used to analysis of real-life problems. Java supports these basic functions through Math class defined in the java.lang package.The math function used as follows  Math.function_name();  Like double y=Math.sqrt(x); Wrapper Class  There 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.The Benefit of using wrapper classes is that they provide methods to convert strings to simple types. This is a very useful because it gives us a mechanism by which to process user input.
Inheritance ,[object Object],[object Object],[object Object],[object Object],[object Object]
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 derived from is commonly referred to as a  superclass . The term  immediate superclass  is used to describe the class from which a subclass is directly derived. In Figure 3.5, for example, ClassicCar is a subclass of both Car and Object. Car and Object are both superclasses of ClassicCar, but only Car is the immediate superclass of ClassicCar.  Fig 3.5
Call By Value and Call By Reference (Argument Passing) All methods are passed by value. This means that copies of the arguments are provided to a method. Any changes to those copies are not visible outside method.  The situation when an array of objects are passed as an argument. In this case the entire array or object is not actually copied.Instead, only a copy of the reference is provided. Therefore any changes to the array or object are visible outside the method. However the reference itself is passed by value.
Overriding Member Methods  When 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 of this, 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    
  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);      } }
Because ClassicCar is derived from Car, it inherits all of the functionality of Car, including its member variables year and originalPrice. The function CalculateSalePrice appears in both class declarations. This means that the occurrence of this function in ClassicCar overrides the occurrence of it in Car for object instances of ClassicCar. As an example of how this works, consider the following:  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 class's constructor  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.
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;} }  The this Variable All Java classes contain a hidden member variable named this. The this member can be used at runtime to reference the object itself. One excellent use of this is in constructors. It is very common to have a set of instance variables in a class that must be set to values that are passed to a constructor. When you are doing this, it would 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 on the right could be the parameter passed to the constructor.
  Here, we've had to come up with two names for each concept: the best variable names (manufacturer, model, and so on) are used as the instance variables in the class declaration. The less satisfactory names are passed as parameters so as to distinguish them from the instance variables. The assignment statements are then very readable by Java but seem a little contrived to human readers. Java's this keyword provides a very effective solution to this problem in that 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;
In this case, the variables like this.year refer to the instance variables, whereas the unqualified variables like year refer to the constructor's parameters. this.year = year;          this.passengers = passengers;         this.cost = cost;   } }         
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Abstract Classes Sometimes you may want to declare a class and yet not know how to define all of the methods that belong to that class. For example, you may want to declare a class called Mammal and include in it a member method called MarkTerritory. However, you don't know how to write MarkTerritory because it is different for each type of Mammal. Of course, you plan to handle this by deriving subclasses of Mammal, such as Dog and Human. But what code do you put in the MarkTerritory function of Mammal itself?  In Java you can declare the MarkTerritory function of Mammal as an abstract method. Doing so allows you to declare the method without writing any code for it in that class. However, you can write code for the method in the subclass. If a method is declared abstract, then the class must also be declared as abstract. For Mammal 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     } }
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 for MarkTerritory. The Human class could contain code that would mark territory by building a fence around it, while the GangMember class could contain code that would mark territory by spray-painting graffiti. The Dog class would mark territory by raising the dog's leg and doing what dogs do to mark territory.
Final Variables, Methods and Class All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses from overriding the members of the super class, we can 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 will never be altered in any way. Similarly the value of a final variable can never be change.  Sometimes we may like to prevent a class being further subclassed for security reasons. A class that can not be subclassed is called a final class. This is achieved 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 not allow it.
STRINGS Strings represent a sequence of characters. The easiest way to represent a sequence of characters in Java is by using a character array. Example : char charArray[]=new char[4]; We can declare string using Characters but there is limitation that we can not use functions related with strings using array like copy of an array is difficult. For that Java provides String class using objects. for that two classes are used String and StringBuffer. A Java String is an instantiated object of the String class.  String stringName; stringName=new String (&quot;string&quot;); String Array : String itemArray[]=new String[3];//will create itemArray of size 3 to hold three string constants.
String Methods : The String Class defines a number of methods that allow us to accomplish a veriety of string manipulation tasks. s2=s1.toLowerCase; //converts the string s1 to all lowercase s2=s1.toUpperCase; //converts the string s1 to all Uppercase s2=s1.replace('x','y'); //Replace all occurance of x with y s2=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 s2 s1.equalsIgnoreCase(s2) //Returns true if s1=s2, ignoring the case of characters. s1.length() //Gives the Length of s1 s1.charAt(n) //Gives nth character of s1 s1.compareTo(s2) //Returns negative if s1<s2,positive if s1>s2, and zero if s1 is equal to s2 s1.concat(s2) //concatenates s1 and s2 s1.substring(n) //Gives substring starting from nth character
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 p s1.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, StringBuffer creates strings of flexible length that can be modified in terms of both length and content. We can insert 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 x s1.append(s2)//Appends the string s2 to s1 at the end s1.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.
Vectors : Java does not support the concept of variable arguments to a function. This feature can be achieved in Java through the use of the Vector class contained in the java.util package. This class can be used to 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. Vectors are created like arrays as follows : Vector intVect = new Vector();//declaring without size Vector intVect = new Vector(3);//declaring with size Vectors 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 done using the wrapper classes discussed in the next section.The vector class supports a number of methods that can be used to manipulate the vectors created.
list.addElement(item)//Adds the item specified to the list at the end list.elementAt(10)//Gives the name of the 10th object list.size()//Gives the number of objects present list.removeElement(item)//Removes the specified item from the list list.removeElementAt(n)//Removes the item stored in the nth position of the list. list.removeAllElements()//Removes all the element in the list list.copyInto(array)//Copies all items from list to array list.insertElementAt(item,n)//Inserts the item at nth position. Wrapper Classes Vectors not handled primitive data types like int,long,char and double. Primitive data types may  be converted object types by using the wrapper classes contained in the java.lang package. Wrapper class for convering primitive data types are given below
Simple type Wrapper Class boolean Boolean char Character double Double float Float int  Integer long Long The Wrapper classes have number of unique methods for handling primitive data types and objects. 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() method int i=IntVal.intValue();//Object to primitive integer Converting Numbers to Strings Using toString() method str=Integer.toString(i);//Primitive integer to string
Converting String Objects to Numeric Objects using the Static Method valueOf() IntVal=Integer.valueOf(str);//converts string to Integer objects Converting Numeric Strings  to Primitive Numbers using Parsing Method int i=Integer.parseInt(str);//converts string to primitive integer.
Input and Output in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Constructors for the File Class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Methods Of File Class: ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Understanding Streams ,[object Object],[object Object],[object Object],[object Object]
The Low-Level Streams ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Methods of FileInputStream ,[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object]
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
Multithreading Multitheading is specialized form of multitasking. like windows and other os uses multitasking technique i.e. they handled more than one process at a time, the same thing we can do in Java using multithreading technique. A thread is similar to a program that has  a single flow of control. It has a beginning, a body, and an end,and executes commands sequentially. Java enables us to use multiple flows of control in developing programs. Each flow of control is represented by thread that runs parallel to others. i.e. a program that contains multiple flows of control is known as multithreaded program.Threads in Java are subprograms of a main application program and share the same memory space, known as lightweight threads or lightweight process. Threds running in parallel does not mean that they actually run at the same time. Since all the threads 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 it appears they are running concurrently. Creating Threads : Threads are implemented in the form of objects that contain a method called run(). The  run() method is the heart and soul of any thread.
public void run() { .... (statements for implementing threads) } The run() method should be invoked by an object of the concerned thread. This can be achieved by creating 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() method with the code required by the thread. 2. By converting a class to a thread :Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.
Extending the Thread Class : We can make our class as runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. steps 1. Declare a class as extending the Thread class 2. implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate the thread execution. Stopping and Blocking a Thread Stopping a Thread  Whenever we want to stop a thread from running further, we may do so by calling its stop() method,like aThread.stop(); This statement causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches the end of its method.
Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently  running state by using either of the following thread methods: sleep();//blocked for a specified time suspend();//blocked until further orders wait();//blocked until certain condition occurs These methods causes the thread to go into the blocked (or non- runnable) state.the thread will return 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 Thread During the life time of a thread, there are many states it can enter. they include : 1. Newborn state 2. Runnabke state 3. Running state 4. Blocked state 5. Dead State
yield stop LIFE CYCLE OF A THREAD Newborn Running Runnable Active Thread Dead Killed Thread start stop stop resume notify suspend sleep wait Blocked Idle Thread (Not Runnable New Thread
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
However,if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so be using the yield() method. Running State  Running 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. A running 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 method sleep(time) where time is in milliseconds. This means that the thread is out of the queue during this time period. 3. It has been told to wait until some event occurs. This is done by using wait() method. The thread can be scheduled to run again using the notify() method. Blocked State A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended,sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered &quot;not runnable&quot; but not dead and therefore fully qualified to run again.
Dead State  Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it.  Thread Priority  In java each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads that we have discussed so far are of the same priority. The threads of the same priority are given equal treatment by the java schedular and,therefore,they share the processor on first-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 thread's priority is set. The Thread class defines  several priority constants : MIN_PRIORITY=1 NORM_PRIORITY=5 MAX_PRIORITY=10
intNumber may assume one of these constants or any value between 1 and 10.the default setting is NORM_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 are ready for execution, the java system chooses the highest priority thread and executes it. For a thread of 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 be preempted 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. Syncronization When multiple threads access shared data then sometimes Data corruption occurs if Multithreaded programs is not designed correctly that leads to system failure.Unfortunately, such problems can occur at unpredictable times and be very difficult to reproduce.
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 t0 t1 t2 t3 t4 t5 t6 Thread A Thread B Read Balance Context Switch Read Balance Add $10 to Balance Context Switch Add $10 to Balance Balance $0 $0 $0 $0 $10 $10 $10 Fig 1 Thread Scheduling Fig 1 depicts one possible scheduling of these threads. At time t0, the account balance is zero. Thread A is executing 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 of the 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.
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 done in two common ways. First a method can be synchronized by using the synchronized keyword as a modifier in the method declaration. When a thread begins executing a synchronized instance method, it automatically acquires a lock on that object. The lock is automatically relinquished. When the method completes. Only one method may have this lock at any time. Therefore, only one method may execute any of the synchronized instance method for that same object, the JVM automatically 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. The syntax is : Synchronize(obj) { //statement block } Here, obj is the object to be blocked. If you wish to protect the instance data, you should lock against that object. If you wish to protect against the class data, you should lock the appropriate Class 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.
Deadlock Deadlock is an error that can be encountered in multithreaded programs. It occurs when two or more thread wait indefinitely for each other to relinquish locks. Assume that thread 1 holds a lock on object 1 and waits for a lock on object 2. Thread 2 holds a lock object 2 and waits for a lock on object 1. Neither of these method may proceed. Each waits forever for the other to relinquish the lock it needs. Thread Communication   In deadlock you have seen that how thread acquires a lock and does not relinquish it. In Thread communication threads can communicate with each other. Thread can temporarily release a lock so other threads can have an opportunity to execute a synchronized method or statement block. That lock can be acquired again at a later time. A class objects defines three methods that allow threads to communicate with each other. The wait() method allows a thread that is executing a synchronized method or statement block on that object to release the lock and wait for a notification from another thread. It has these three forms : Void wait() throws InterruptedException Void wait(long msec) throws InterruptedException Void wait(long msec,int nsec) throws InterruptedException The first form causes the current thread to wait indefinitely. The second form causes the thread to wait for a msec milliseconds. The last form causes the current thread to wait for msec milliseconds plus nanoseconds.
notify() method allows a thread that is executing a synchronized method or statement block to notify another thread that is waiting for a lock on this object. If several threads are waiting, only one of these is selected. The selection criteria are determined by the implementer of the JVM. The signature is : void notify() It is important to understand that when a thread executes the notify() or notifyAll() method it does not relinquish its lock at that moment. This occurs only when it leaves the synchronized method or statement block.
APPLET An applet is a program that can be referenced by the html source code of web page. It is dynamically downloaded from a Web Server to a browser. The applet then executes within the environment provided by the browser. Alternatively you may use a tool such as the appletviewer to run it.  It is important to recognize that downloading code from the Internet and executing it on your computer is inherently dangerous. Therefore, applet do not have the same capabilities as Java applications. They are restricted to operating within the confines of a “sandbox”. In other words code 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 would obviously be risky because they could accidentally or maliciously destroy any data stored on that device.Applet can not execute any native code. An applet may open a socket connection back to the host from which it was downloaded, but not to any other host. The reason for this restriction can be understood if you imagine a configuration in which a firewall protects a corporate Intranet from computer hackers. Assume that an employee has downloaded an applet from internet to an PC or workstation. If that applet is allowed to open sockets to any machine, it would then have the potential to steal proprietary information and send back to the hacker’s machine. This must be prevented. Therefore, an applet is not allowed to contact any of those private machines.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Building Applet Code It is essential that our applet code uses the services of two classes, namely,  Applet  and  Graphics  from the Java Class Library. The  Applet  class which is contained in the  java.applet  package provides life and behavior to the applet through its methods such as  init(),start()  and  paint()  . Unlike with applications, where Java calls main() method directly to initiate the execution of the program, when an applet is loaded, Java automatically calls a series of  Applet  class methods for starting, running, and stopping the applet code. The  applet  class therefore maintains the lifecycle of an applet. The paint() method of the  Applet  class, when it is called, actually displays the result of the applet code on the screen. The output may be text, graphics, or sound. The paint() method, which requires a  Graphics  object as an argument, is defined as follows : public void paint(Graphics g) This requires that the applet code imports  java.awt  package that contains the Graphics class. All output operations of an applet are performed using the methods defined in the  Graphics  class.  import java,awt.*; import java.applet.*; public class appletclassname extends Applet { public void paint(Graphics g) { g.dreawString(“Hello Java”,10,100); } }
Here Applet class itself a subclass of the Panel class, which is again subclass of the Container class and so on given below : Chain of classes inherited by Applet class Applet Life Cycle Every Java applet inherits a set of default behaviors from the applet class. The applet state include : 1. Born or Initialization state 2. Idle State 3.
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides
Core Java Slides

Weitere ähnliche Inhalte

Was ist angesagt?

Core Java
Core JavaCore Java
Core JavaNA
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".SudhanshuVijay3
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Training on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaTraining on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaShravan Sanidhya
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecturesubnesh
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 

Was ist angesagt? (20)

Core Java
Core JavaCore Java
Core Java
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Junit
JunitJunit
Junit
 
Training on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaTraining on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan Sanidhya
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Core Java
Core JavaCore Java
Core Java
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Core java
Core javaCore java
Core java
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 

Ähnlich wie Core Java Slides

java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docxvikasbagra9887
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxDrPreethiD1
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01Jay Palit
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technologysshhzap
 
Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdfkumari36
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1RubaNagarajan
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to javajalinder123
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDrRajeshreeKhande
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1Qualys
 
Java Programming (M&M)
Java Programming (M&M)Java Programming (M&M)
Java Programming (M&M)mafffffe19
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdfDeepakChaudhriAmbali
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxVeerannaKotagi1
 

Ähnlich wie Core Java Slides (20)

Java presentation
Java presentationJava presentation
Java presentation
 
java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docx
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Java Intro
Java IntroJava Intro
Java Intro
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdf
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to java
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
 
Java Programming (M&M)
Java Programming (M&M)Java Programming (M&M)
Java Programming (M&M)
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
Java
JavaJava
Java
 
java concepts
java conceptsjava concepts
java concepts
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptx
 

Mehr von Vinit Vyas

Hiroshima and nagasaki
Hiroshima and nagasakiHiroshima and nagasaki
Hiroshima and nagasakiVinit Vyas
 
AVR Fundamentals
AVR FundamentalsAVR Fundamentals
AVR FundamentalsVinit Vyas
 
Hardware Memory
Hardware MemoryHardware Memory
Hardware MemoryVinit Vyas
 
Albert Einstein
Albert EinsteinAlbert Einstein
Albert EinsteinVinit Vyas
 
World’s Greatest Writers
World’s Greatest WritersWorld’s Greatest Writers
World’s Greatest WritersVinit Vyas
 
Why Do We Need God?
Why Do We Need God?Why Do We Need God?
Why Do We Need God?Vinit Vyas
 

Mehr von Vinit Vyas (6)

Hiroshima and nagasaki
Hiroshima and nagasakiHiroshima and nagasaki
Hiroshima and nagasaki
 
AVR Fundamentals
AVR FundamentalsAVR Fundamentals
AVR Fundamentals
 
Hardware Memory
Hardware MemoryHardware Memory
Hardware Memory
 
Albert Einstein
Albert EinsteinAlbert Einstein
Albert Einstein
 
World’s Greatest Writers
World’s Greatest WritersWorld’s Greatest Writers
World’s Greatest Writers
 
Why Do We Need God?
Why Do We Need God?Why Do We Need God?
Why Do We Need God?
 

Core Java Slides

  • 1.
  • 2.
  • 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.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. Java Compiler Java Program Java Interpreter Machine Code Virtual Machine Bytecode Source Code Bytecode Virtual Machine Real Machine Process of Compilation Process of Converting bytecode into machine code
  • 10. Java Source Code Java Compiler Java Enabled Browser Java Interpreter Output Output Application Type Applet Type
  • 11.
  • 12. Inheritance :- Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without 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 The class Shape defines a method called getArea() that returns the area of a shape. However, this method is not implemented by that class. Therefore, it is an abstract method and Shape is an abstract class. This means that no objects of class Shape can be created. However, the functionality of that class can be inheritated by its subclass. The various subclasses of Shape like Ellipse,Rectangle,Triangle do implement the getArea() method. Ellipse Rectangle Triangle
  • 13.
  • 14. Class Declaration The first line public class HelloWorld declares a class, which is an Object-Oriented construct. 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 a new class definition follows. Opening Bace Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”, appearing in the last line in the example. The main() method Every java application program must include the main() method. This is starting point for the interpreter to begin the execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate the execution. Public : The Keyword public is an access specifier that declares the main method as unprotected and therefore making it to accessible to all other classes. Static : The keyword static which declares this method as one that belongs to the entire Class and not a part of any Objects of the class.
  • 15. The main must always be declared be declared as static since the interpreter uses this 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 objects Of the class type String. The Output Line The only executable Statement in the program is System.out.println(&quot;Hello World!!&quot;); Since Java is a true Object Oriented Language, every method must be part of an Object. The println method is a member of the out Object, which is static data Member of the System class. This line prints Hello World!! to the screen. The method println always appends a newline character to the end of the string.
  • 16. Compile the Code To compile the program, you need to first install the JDK. Then, use the program javac included with the JDK to convert the text in listing 7.1 to code which the computer can run. To run javac, on a Macintosh drag the source file over the javac icon. On any other computer, type the line: javac HelloWorld.java at a command prompt. The javac program creates a file called HelloWorld.class from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as bytecodes which can be run by the Java interpreter. Run the Program Now that you have compiled the program, you can run it by typing at the command prompt: java HelloWorld After you do this, the computer should print to the screen Hello World!! That may not seem very interesting, but then it's a simple program. If you don't see the Hello World!! on the screen, go back and make sure you have typed in the file exactly as shown in listing 7.1, and make sure that you called the file HelloWorld.java.
  • 17.
  • 18.
  • 19. Real Constants : Integer constant are inadequate to represent quantities that vary continuously, such as distance, heights, temperature, prices and so on. These quantities 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 exponential notation. e2 means multiply by 10 2 . 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.
  • 21. Data Types Integer Types Java 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 : Data Types in Java Primitive (Intrinsic) Non-Primitive ( Derived) Numeric Non-Numeric Classes Arrays Integer Floating Point Character Boolean Interface
  • 22. The Java integer primitive types. Integer literals can be specified in decimal, hexadecimal, or octal notation. To specify a decimal value, simply use the number as normal. To indicate that a literal value is a long, you can append either &quot;L&quot; or &quot;l&quot; to the end of the number. Hexadecimal values are given in base 16 and include the 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. 9,223,372,036,854,775,807 -9,223,372,036,854,775,808 64 long 2,147,483,647 -2,147,483,648 32 int 32,767 -32,768 16 short 255 -256 8 byte Maximum Value Minimum Value Bit Size Type
  • 23. Table 3.7. Examples of integer literals. Floating-Point Types Support for floating-point numbers in Java is provided through two primitive types-float and double, which are 32- and 64-bit values, respectively. Similar to integer literals are Java's 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 &quot;f&quot; or &quot;F&quot;. To indicate that 0x64 0144 100L 100 0x10 020 16L 16 0XF 017 15L 15 0xA 012 10L 10 0x1 01 1L 1 0x0 0 0L 0 Hexadecimal Octal Long Integer
  • 24. it is to be treated as a double precision value, append either &quot;d&quot; or &quot;D&quot;. 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.02e23d Boolean :- Java supports two Boolean literals-true and false. Character Literals :- A character literal is a single character or an escape sequence enclosed in single quotes, for example, 'b'. Escape sequences are used to indicate special characters or actions, such as line feed, form feed, or carriage return. The available escape sequences ar shown in Table 3.8. String Literals Although there is no string primitive type in Java, you can include string literals in your programs. 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. As examples of string literals, consider the following: &quot;A String“,&quot;Column 1Column 2”
  • 25. Table 3.8. Escape sequences. Unicode character xxxx Backslash Single quote apos; Double quote amp;quot; Carriage return Form feed Line feed Horizontal tab Backspace Purpose Sequence
  • 26. Arithmetic Operators and Expressions An expression is a operators and operands. It follows the rules of algebra and should be familiar. Java allows several types of expressions. The arithmetic operators are given below : +  addition -  subtraction *  multiplication /  division %  modulus +=  addition assignment -=  subtraction assignment *=multiplication assignment /=division assignment %=  modulus assignment ++  increment,--  decrement
  • 27. An expression may appear on the right side of an assignment statement. For example, Int answer; Answer=100*31; Java expression may contain Variables, constants or both. For example assuming that answer and count are variables, this expression is perfectly valid. Answer=count-100;
  • 28. Increment/Decrement Operators The increment and decrement operators are used with one variable (they are known as unary operators ): ++ increment operator -- decrement operator For instance, the increment operator (++) adds one to the operand, as shown in the next line of code: x++; is the same as x+=1; The increment and decrement operators behave slightly differently based on the side of the operand 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 code fragment, the result of y is 6: int x=5;int y=++x; // y=6 x=6 If the operator appears after the operand, the addition occurs after the value is taken. So y is 5 as shown in the next code fragment. Notice that in both examples, x is 6 at the end of the fragment. int x=5;int y = x++; //y=5 x=6 Similarly, the decrement operator (--) subtracts one from the operand, and the timing of this is in relation to the evaluation of the expression that it occurs in.
  • 29. The Relational Operators The most intuitive comparative operators are those that fall into a category known as relational operators. Relational operators include those standard greater-than and 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, you know 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 to evaluating 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 to The following two assignment statements produce identical results: result1 = a+b < c*d ; result2 = (a+b) < (c*d) ; Logical Expressions The third set of evaluation operators fall into a category known as logical expressions. Logical expressions work a bit differently than the previous operators, and are probably not something you covered in your third grade math class.
  • 30.
  • 31. The Conditional Operator The conditional operator is the one ternary or triadic operator in Java, and operates as it does in C and C++. It takes the following form: expression1 ? expression2 : expression3 In 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. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. Consider the following examples. The first is using the conditional operator to determine the maximum of two values; the second is determining the minimum of 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 convince yourself that none of the three examples requires any brackets in order to be evaluated correctly.
  • 32.
  • 33. Conversions and the Cast Operator : Normally with implicit conversion, the conversion is so natural that you don't even notice. Sometimes though it is important to make sure a conversion occurs between two types. 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 operator with high precedence and comes before its operand, the result of which is a variable of the type specified by the cast, but which has the value of the original object. The following 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 in a 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 other type, and objects can only be converted to a parent class. Casting and Converting Integers The 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. Casting and Converting Characters Characters 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 lose some data. In fact, even if you convert between a character and a short you an loose some data. If you are using the Han character set (Chinese, Japanese, or Korean), you can lose data by casting a char into a short (16-bit integer), because the top bit will be lost. Casting and Converting Booleans There 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 on the current value of a Boolean, use an if-else statement, or imitate the following code: 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, and anything else equal to true as follows: int j;boolean tf;...tf = (j!=0); // Boolean tf is true if j is not 0, false otherwise.
  • 35.
  • 36. The Java comment delimiters are summarized in Table 3.1. Table 3.1. Java comment delimiters. The enclosed text is treated as a comment by the compiler but is used by JavaDoc to automatically generate documentation. */ /** The rest of the line is treated as a comment. (none) // The enclosed text is treated as a comment. */ /* Purpose End Start
  • 37. Java Control Statements if Selection Statement Iteration Statement Jump Statement If-else switch while do for break continue return Control Statement
  • 38. Selection Statement : These select one of several control flows. There are three 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 control the flow of execution of statements. It is a two-way decision statement and is used 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 on whether the value of the expression (relation or condition) is ‘true’ or ‘false’. It transfers the control to a particular statement. If the statement is true then the Statement block will be executed;otherwise the statement-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-block and statement-x are executed in sequence.
  • 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 statement if(test expression) { True-Block Statement(s); } Else { False-Block statement(s); } Statement-x;
  • 40. If the test expression is true, then the true-block statement(s) executed immediately following to the if statement, are executed; otherwise the false statement(s) will be executed, not both.In both the cases, the control is transferred subsequently to the statement-x. Nesting of If—else Statement If(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 it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated;otherwise statement-2 will be evaluated and then control is transferred to the statement-x.
  • 41. Switch Statement: The Java switch statement is ideal for testing a single expression against a series of possible values and executing the code associated 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. Iteration Statement : These specify how and when looping will take place. There are three types of Iteration statements: while, do and for The for Statement The first line of a for loop enables you to specify a starting value for a loop counter, specify the test condition that will exit the loop, and indicate how the loop counter should be incremented after each pass through the loop. This is definitely a statement that offers a lot of bang for the buck. The syntax of a Java for statement is as follows: for (initialization; testExpression; incremement)     statement For example, a sample for loop may appear as follows: int count; for (count=0; count<100; count++)     System.out.println(&quot;Count = &quot; + count); In this example, the initialization statement of the for loop sets count to 0. The test expression, count < 100, indicates that the loop should continue as long as count is less than 100. Finally, the increment statement increments the value of count by one. As long as the test expression is true, the statement following the for loop setup will be executed, as follows: System.out.println(&quot;Count = &quot; + count); Of course, you probably need to do more than one thing inside the loop. This is as easy to do as using curly braces to indicate the scope of the for loop.
  • 43. The while Statement Related to the for loop is the while loop. The syntax for a while loop is as follows: while (booleanExpression)     statement As you can tell from the simplicity of this, the Java while loop does not have the built-in support for initializing and incrementing variables that its for loop does. Because of this, you need to be careful to initialize loop counters prior to the loop and increment them within the body of the while loop. For example, the following code fragment will display a message five times: int count = 0; while (count < 5) {     System.out.println(&quot;Count = &quot; + count);     count++; } The do…while Statement The final looping construct in Java is the do…while loop. The syntax for a do…while loop is as follows: do {     statement } while (booleanExpression);
  • 44. This is similar to a while loop except that a do…while loop is guaranteed to execute at least once. It is possible that a while loop may not execute at all depending on the test expression used in the loop. For example, consider the following method: public void ShowYears(int year) {     while (year < 2000) {         System.out.println(&quot;Year is &quot; + year);         year++;     } } This method is passed a year value, then loops over the year displaying a message as long as the year is less than 2000. If year starts at 1996, then messages will be displayed for the years 1996, 1997, 1998, and 1999. However, what happens if year starts at 2010? Because the initial test, year < 2000, will be false, the while loop 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 loop has executed for each pass, it will always be executed at least once. This is a very valid distinction between the two types of loop, but it can also be a source of potential errors. Whenever you use a do…while loop, you should be careful to consider the first pass through the body of the loop.
  • 45. Jumping Of course, it is not always easy to write all of your for, while and do…while loops so that they are easy to read and yet the loops terminate on exactly the right pass through the loop. Java makes it easier to jump out of loops and to control other areas of program flow with its break and continue statements. The break Statement Earlier in this chapter, you saw how the break statement is used to exit a switch statement. In a similar manner, break can be used to exit a loop As an example of this, consider the following code: int year = 1909; while (DidCubsWinTheWorldSeries(year) == false) {     System.out.println(&quot;Didn't win in &quot; + year);     if (year >= 3000) {         System.out.println(&quot;Time to give up. Go White Sox!&quot;);         break;     } } System.out.println(&quot;Loop exited on year &quot; + year);
  • 46. This example shows a while loop that will continue to execute until it finds a year that the Chicago Cubs won the World Series. Because they haven't won since 1908 and the loop counter year starts with 1909, it has a lot of looping to do. For each year they didn't win, a message is displayed. However, even die-hard Cubs fans will eventually give up and change allegiances to the Chicago White Sox. In this example, if the year is 3000 or later, a message is displayed and then a break is encountered. The break statement will cause program control to move to the first statement after the end of the while loop. In this case, that will be the following line: System.out.println(&quot;Loop exited on year &quot; + year); The continue Statement Just as a break statement can be used to move program control to immediately after the end of a loop, the continue statement can be used to force program control back to the top of a loop
  • 47.
  • 48. varName=new type[size]; Here varName is name of the array, type is a valid Java type, and size specifies the number of elements in the array. You can see that the new operator is used to allocate memory for the array. These two steps combines like type 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 variable name that can hold 10 integer values. Multidimensional Array : In addition to one dimensional we can create arrays of two or more dimensions. In Java, Multidimensional array are implemented as arrays of arrays. You need to perform two steps to work with multidimensional arrays : 1. Declare the array and 2. allocate space for its elements.
  • 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.
  • 51. The General Form of Class A class array contains three types of items : variable,methods, and constructors. Variable represent its state. Method provide the logic that constitutes the behavior defined by a class. The variable and methods can be both static and instance variable. Constructors initialize the state of a new instance of a class. The Simplified form of a class is : class clsName { //instance variable declarations type1 varName1=value1; type2 varName2=value2; … .. //constructor clsName(cparams1) { // body of constructor }
  • 52. clsName(cparamsN) { //body of constructor } … //methods rtype1 mthName(mparams1) { //body of method } … .. } } The keyword class indicates that a class named clsName is being declared. This name must follow the Java naming convention for identifiers. The instance Variables named varName1 through varNameN included using the normal variable declaration syntax. Each variable must be assigned a type shown as
  • 53. type1 through typeN and may be initialized to value shown as value1 through valueN. Constructors always have the same name as the class. They do not have return values. Method named mthName1 through mthNameN can be included. The return type of the methods are rType1 through rtypeN, and their Optional Parameter lists are mparams1 through mparamsN. Constructors Often an object will require some form of initialization when it is created. To accommodate this, Java allows you to define constructor for your classes. A Constructor is a special method that creates and initializes an object of a particular class. It has the same name as its class and may accept arguments. Constructor does not have a return type. Instead, a constructor returns a reference to the object that it creates. Constructor Overloading A class may have several constructors. This feature is called constructor overloading. When constructors are overloaded each is still called by the name of its class. However it must have a different parameter list. i.e. Signature of each constructor must differ.
  • 54. Method Overloading Like Constructor, method can also be overloaded. This occurs when two or more methods have the same name but different signature. Recall that the signature of a 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 that basically 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 a different type. Another advantage of method overloading is that it provides an easy way to handle default parameter values. The New Operator Objects are created using the new operator. The new Operator creates an instance 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 to create an instance.) A reference to the new object is assigned to a variable named objRef. Notice the expression immediately to the right of the keyword new. This is known as constructor. A constructor creates an instance of the class. It has the same name as the class and may optionally have an argument list args.
  • 55. Garbage Collection Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable. It prevents programming errors that could otherwise occur by incorrectly deleting or failing to delete objects. An object becomes eligible for garbage collection when it is no longer referenced by any Variable. However, the JVM determines exactly when this task is performed. finalize method : Constructor method used to initialize an object when it is declared. This process is known as initialization. Similarly, Java supports a concept called finalization, which is just opposite to Initialization. We know that java run-time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalizer method. This is similar to destructor of C++. The finalizer method is simply finalize() and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.
  • 56. Command Line Arguments All java application contain a static method named main().This method takes one argument that is an array of String objects. These objects represent any arguments that may have been entered by the user on the command line. The number of command line arguments is obtained via the expression args.length. This is an int type. The individual arguments are accessed as arg[0],args[1],args[2], and so forth. The System Class The system class defines several attributes relate to the run-time environment. It has a static variable named out that contains a reference to a PrintStream object. The print() and println() methods of that object display their string arguments on the standard output. The static variable err also holds 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 current application.
  • 57.
  • 58. Instance Variables and Methods Each 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. Instance variable 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 Methods A static variable is shared by all objects of its class and thus relates to the class itself. A static variable may be declared by using the static keyword as a modifier as 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 the memory.
  • 59. A static method may be declared by using the static keyword as a modifier. A static method acts relative to a class. It deos not act on specific objects of its class. 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 optional list of parameter types shown as mparams may be specified. String Class Strings 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 a variety of string manipulation tasks like compareTo() method used to sort an array of strings in alphabetical order.
  • 60. Math Class Mathematical functions such as cos,sqrt, log etc. are frequently used to analysis of real-life problems. Java supports these basic functions through Math class defined in the java.lang package.The math function used as follows Math.function_name(); Like double y=Math.sqrt(x); Wrapper Class There 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.The Benefit of using wrapper classes is that they provide methods to convert strings to simple types. This is a very useful because it gives us a mechanism by which to process user input.
  • 61.
  • 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 derived from is commonly referred to as a superclass . The term immediate superclass is used to describe the class from which a subclass is directly derived. In Figure 3.5, for example, ClassicCar is a subclass of both Car and Object. Car and Object are both superclasses of ClassicCar, but only Car is the immediate superclass of ClassicCar. Fig 3.5
  • 63. Call By Value and Call By Reference (Argument Passing) All methods are passed by value. This means that copies of the arguments are provided to a method. Any changes to those copies are not visible outside method. The situation when an array of objects are passed as an argument. In this case the entire array or object is not actually copied.Instead, only a copy of the reference is provided. Therefore any changes to the array or object are visible outside the method. However the reference itself is passed by value.
  • 64. Overriding Member Methods When 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 of this, 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.   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. Because ClassicCar is derived from Car, it inherits all of the functionality of Car, including its member variables year and originalPrice. The function CalculateSalePrice appears in both class declarations. This means that the occurrence of this function in ClassicCar overrides the occurrence of it in Car for object instances of ClassicCar. As an example of how this works, consider the following: 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 class's constructor 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. 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;} } The this Variable All Java classes contain a hidden member variable named this. The this member can be used at runtime to reference the object itself. One excellent use of this is in constructors. It is very common to have a set of instance variables in a class that must be set to values that are passed to a constructor. When you are doing this, it would 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 on the right could be the parameter passed to the constructor.
  • 68.   Here, we've had to come up with two names for each concept: the best variable names (manufacturer, model, and so on) are used as the instance variables in the class declaration. The less satisfactory names are passed as parameters so as to distinguish them from the instance variables. The assignment statements are then very readable by Java but seem a little contrived to human readers. Java's this keyword provides a very effective solution to this problem in that 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. In this case, the variables like this.year refer to the instance variables, whereas the unqualified variables like year refer to the constructor's parameters. this.year = year;         this.passengers = passengers;         this.cost = cost;   } }        
  • 70.
  • 71. Abstract Classes Sometimes you may want to declare a class and yet not know how to define all of the methods that belong to that class. For example, you may want to declare a class called Mammal and include in it a member method called MarkTerritory. However, you don't know how to write MarkTerritory because it is different for each type of Mammal. Of course, you plan to handle this by deriving subclasses of Mammal, such as Dog and Human. But what code do you put in the MarkTerritory function of Mammal itself? In Java you can declare the MarkTerritory function of Mammal as an abstract method. Doing so allows you to declare the method without writing any code for it in that class. However, you can write code for the method in the subclass. If a method is declared abstract, then the class must also be declared as abstract. For Mammal 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. 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 for MarkTerritory. The Human class could contain code that would mark territory by building a fence around it, while the GangMember class could contain code that would mark territory by spray-painting graffiti. The Dog class would mark territory by raising the dog's leg and doing what dogs do to mark territory.
  • 73. Final Variables, Methods and Class All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclasses from overriding the members of the super class, we can 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 will never be altered in any way. Similarly the value of a final variable can never be change. Sometimes we may like to prevent a class being further subclassed for security reasons. A class that can not be subclassed is called a final class. This is achieved 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 not allow it.
  • 74. STRINGS Strings represent a sequence of characters. The easiest way to represent a sequence of characters in Java is by using a character array. Example : char charArray[]=new char[4]; We can declare string using Characters but there is limitation that we can not use functions related with strings using array like copy of an array is difficult. For that Java provides String class using objects. for that two classes are used String and StringBuffer. A Java String is an instantiated object of the String class. String stringName; stringName=new String (&quot;string&quot;); String Array : String itemArray[]=new String[3];//will create itemArray of size 3 to hold three string constants.
  • 75. String Methods : The String Class defines a number of methods that allow us to accomplish a veriety of string manipulation tasks. s2=s1.toLowerCase; //converts the string s1 to all lowercase s2=s1.toUpperCase; //converts the string s1 to all Uppercase s2=s1.replace('x','y'); //Replace all occurance of x with y s2=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 s2 s1.equalsIgnoreCase(s2) //Returns true if s1=s2, ignoring the case of characters. s1.length() //Gives the Length of s1 s1.charAt(n) //Gives nth character of s1 s1.compareTo(s2) //Returns negative if s1<s2,positive if s1>s2, and zero if s1 is equal to s2 s1.concat(s2) //concatenates s1 and s2 s1.substring(n) //Gives substring starting from nth character
  • 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 p s1.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, StringBuffer creates strings of flexible length that can be modified in terms of both length and content. We can insert 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 x s1.append(s2)//Appends the string s2 to s1 at the end s1.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. Vectors : Java does not support the concept of variable arguments to a function. This feature can be achieved in Java through the use of the Vector class contained in the java.util package. This class can be used to 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. Vectors are created like arrays as follows : Vector intVect = new Vector();//declaring without size Vector intVect = new Vector(3);//declaring with size Vectors 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 done using the wrapper classes discussed in the next section.The vector class supports a number of methods that can be used to manipulate the vectors created.
  • 78. list.addElement(item)//Adds the item specified to the list at the end list.elementAt(10)//Gives the name of the 10th object list.size()//Gives the number of objects present list.removeElement(item)//Removes the specified item from the list list.removeElementAt(n)//Removes the item stored in the nth position of the list. list.removeAllElements()//Removes all the element in the list list.copyInto(array)//Copies all items from list to array list.insertElementAt(item,n)//Inserts the item at nth position. Wrapper Classes Vectors not handled primitive data types like int,long,char and double. Primitive data types may be 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. Simple type Wrapper Class boolean Boolean char Character double Double float Float int Integer long Long The Wrapper classes have number of unique methods for handling primitive data types and objects. 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() method int i=IntVal.intValue();//Object to primitive integer Converting Numbers to Strings Using toString() method str=Integer.toString(i);//Primitive integer to string
  • 80. Converting String Objects to Numeric Objects using the Static Method valueOf() IntVal=Integer.valueOf(str);//converts string to Integer objects Converting Numeric Strings to Primitive Numbers using Parsing Method int i=Integer.parseInt(str);//converts string to primitive integer.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108. Multithreading Multitheading is specialized form of multitasking. like windows and other os uses multitasking technique i.e. they handled more than one process at a time, the same thing we can do in Java using multithreading technique. A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end,and executes commands sequentially. Java enables us to use multiple flows of control in developing programs. Each flow of control is represented by thread that runs parallel to others. i.e. a program that contains multiple flows of control is known as multithreaded program.Threads in Java are subprograms of a main application program and share the same memory space, known as lightweight threads or lightweight process. Threds running in parallel does not mean that they actually run at the same time. Since all the threads 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 it appears they are running concurrently. Creating Threads : Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread.
  • 109. public void run() { .... (statements for implementing threads) } The run() method should be invoked by an object of the concerned thread. This can be achieved by creating 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() method with the code required by the thread. 2. By converting a class to a thread :Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.
  • 110. Extending the Thread Class : We can make our class as runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. steps 1. Declare a class as extending the Thread class 2. implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate the thread execution. Stopping and Blocking a Thread Stopping a Thread Whenever we want to stop a thread from running further, we may do so by calling its stop() method,like aThread.stop(); This statement causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches the end of its method.
  • 111. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following thread methods: sleep();//blocked for a specified time suspend();//blocked until further orders wait();//blocked until certain condition occurs These methods causes the thread to go into the blocked (or non- runnable) state.the thread will return 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 Thread During the life time of a thread, there are many states it can enter. they include : 1. Newborn state 2. Runnabke state 3. Running state 4. Blocked state 5. Dead State
  • 112. yield stop LIFE CYCLE OF A THREAD Newborn Running Runnable Active Thread Dead Killed Thread start stop stop resume notify suspend sleep wait Blocked Idle Thread (Not Runnable New Thread
  • 113.
  • 114. However,if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so be using the yield() method. Running State Running 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. A running 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 method sleep(time) where time is in milliseconds. This means that the thread is out of the queue during this time period. 3. It has been told to wait until some event occurs. This is done by using wait() method. The thread can be scheduled to run again using the notify() method. Blocked State A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended,sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered &quot;not runnable&quot; but not dead and therefore fully qualified to run again.
  • 115. Dead State Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. Thread Priority In java each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads that we have discussed so far are of the same priority. The threads of the same priority are given equal treatment by the java schedular and,therefore,they share the processor on first-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 thread's priority is set. The Thread class defines several priority constants : MIN_PRIORITY=1 NORM_PRIORITY=5 MAX_PRIORITY=10
  • 116. intNumber may assume one of these constants or any value between 1 and 10.the default setting is NORM_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 are ready for execution, the java system chooses the highest priority thread and executes it. For a thread of 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 be preempted 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. Syncronization When multiple threads access shared data then sometimes Data corruption occurs if Multithreaded programs is not designed correctly that leads to system failure.Unfortunately, such problems can occur at unpredictable times and be very difficult to reproduce.
  • 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 t0 t1 t2 t3 t4 t5 t6 Thread A Thread B Read Balance Context Switch Read Balance Add $10 to Balance Context Switch Add $10 to Balance Balance $0 $0 $0 $0 $10 $10 $10 Fig 1 Thread Scheduling Fig 1 depicts one possible scheduling of these threads. At time t0, the account balance is zero. Thread A is executing 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 of the 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. 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 done in two common ways. First a method can be synchronized by using the synchronized keyword as a modifier in the method declaration. When a thread begins executing a synchronized instance method, it automatically acquires a lock on that object. The lock is automatically relinquished. When the method completes. Only one method may have this lock at any time. Therefore, only one method may execute any of the synchronized instance method for that same object, the JVM automatically 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. The syntax is : Synchronize(obj) { //statement block } Here, obj is the object to be blocked. If you wish to protect the instance data, you should lock against that object. If you wish to protect against the class data, you should lock the appropriate Class 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. Deadlock Deadlock is an error that can be encountered in multithreaded programs. It occurs when two or more thread wait indefinitely for each other to relinquish locks. Assume that thread 1 holds a lock on object 1 and waits for a lock on object 2. Thread 2 holds a lock object 2 and waits for a lock on object 1. Neither of these method may proceed. Each waits forever for the other to relinquish the lock it needs. Thread Communication In deadlock you have seen that how thread acquires a lock and does not relinquish it. In Thread communication threads can communicate with each other. Thread can temporarily release a lock so other threads can have an opportunity to execute a synchronized method or statement block. That lock can be acquired again at a later time. A class objects defines three methods that allow threads to communicate with each other. The wait() method allows a thread that is executing a synchronized method or statement block on that object to release the lock and wait for a notification from another thread. It has these three forms : Void wait() throws InterruptedException Void wait(long msec) throws InterruptedException Void wait(long msec,int nsec) throws InterruptedException The first form causes the current thread to wait indefinitely. The second form causes the thread to wait for a msec milliseconds. The last form causes the current thread to wait for msec milliseconds plus nanoseconds.
  • 120. notify() method allows a thread that is executing a synchronized method or statement block to notify another thread that is waiting for a lock on this object. If several threads are waiting, only one of these is selected. The selection criteria are determined by the implementer of the JVM. The signature is : void notify() It is important to understand that when a thread executes the notify() or notifyAll() method it does not relinquish its lock at that moment. This occurs only when it leaves the synchronized method or statement block.
  • 121. APPLET An applet is a program that can be referenced by the html source code of web page. It is dynamically downloaded from a Web Server to a browser. The applet then executes within the environment provided by the browser. Alternatively you may use a tool such as the appletviewer to run it. It is important to recognize that downloading code from the Internet and executing it on your computer is inherently dangerous. Therefore, applet do not have the same capabilities as Java applications. They are restricted to operating within the confines of a “sandbox”. In other words code 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 would obviously be risky because they could accidentally or maliciously destroy any data stored on that device.Applet can not execute any native code. An applet may open a socket connection back to the host from which it was downloaded, but not to any other host. The reason for this restriction can be understood if you imagine a configuration in which a firewall protects a corporate Intranet from computer hackers. Assume that an employee has downloaded an applet from internet to an PC or workstation. If that applet is allowed to open sockets to any machine, it would then have the potential to steal proprietary information and send back to the hacker’s machine. This must be prevented. Therefore, an applet is not allowed to contact any of those private machines.
  • 122.
  • 123. Building Applet Code It is essential that our applet code uses the services of two classes, namely, Applet and Graphics from the Java Class Library. The Applet class which is contained in the java.applet package provides life and behavior to the applet through its methods such as init(),start() and paint() . Unlike with applications, where Java calls main() method directly to initiate the execution of the program, when an applet is loaded, Java automatically calls a series of Applet class methods for starting, running, and stopping the applet code. The applet class therefore maintains the lifecycle of an applet. The paint() method of the Applet class, when it is called, actually displays the result of the applet code on the screen. The output may be text, graphics, or sound. The paint() method, which requires a Graphics object as an argument, is defined as follows : public void paint(Graphics g) This requires that the applet code imports java.awt package that contains the Graphics class. All output operations of an applet are performed using the methods defined in the Graphics class. import java,awt.*; import java.applet.*; public class appletclassname extends Applet { public void paint(Graphics g) { g.dreawString(“Hello Java”,10,100); } }
  • 124. Here Applet class itself a subclass of the Panel class, which is again subclass of the Container class and so on given below : Chain of classes inherited by Applet class Applet Life Cycle Every Java applet inherits a set of default behaviors from the applet class. The applet state include : 1. Born or Initialization state 2. Idle State 3.