Example program for FORM VALIDATION

Size: px
Start display at page:

Download "Example program for FORM VALIDATION"

Transcription

1 Example program for FORM VALIDATION <html> <head> <script> function validate() var name = document.forms["regform"]["name"]; var = document.forms["regform"][" "]; var phone = document.forms["regform"]["telephone"]; var what = document.forms["regform"]["subject"]; var password = document.forms["regform"]["password"]; var address = document.forms["regform"]["address"]; if (name.value == "") window.alert("please enter your name."); name.focus(); return false; if (address.value == "") window.alert("please enter your address."); name.focus(); return false; if ( .value == "") window.alert("please enter a valid address."); .focus(); return false; if ( .value.indexof("@", 0) < 0) window.alert("please enter a valid address."); .focus(); return false; if ( .value.indexof(".", 0) < 0) window.alert("please enter a valid address."); .focus(); return false;

2 if (phone.value == "") window.alert("please enter your telephone number."); phone.focus(); return false; if (password.value == "") window.alert("please enter your password"); password.focus(); return flase; if (what.selectedindex < 1) alert("please enter your course."); what.focus(); return false; return true; </script> </head> <body> <h1 style="text-align: center"> REGISTRATION FORM </h1> <form name="regform" onsubmit="return validate()" method="post"> <p>name: <input type="text" name="name"> </p><br> <p> Address: <input type="text" name="address"> </p><br> <p> Address: <input type="text" name=" "> </p><br> <p>password: <input type="text" name="password"> </p><br> <p>telephone: <input type="text" name="telephone"> </p><br> <p>select YOUR COURSE <select type="text" value="" name="subject"> <option>btech</option> <option>bba</option> <option>bca</option> <option>b.com</option> <option>geekforgeeks</option> </select></p><br><br>

3 <p>comments: <textarea cols="55" name="comment"> </textarea></p> <p><input type="submit" value="send" name="submit"> <input type="reset" value="reset" name="reset"> </p> </form> </body> </html>

4 UNITII JAVA Introduction to object oriented programming-features of Java Data types, variables and arrays Operators Control statements Classes and Methods Inheritance. Packages and Interfaces Exception Handling Multithreaded Programming Input/Output Files Utility Classes String Handling. Introduction to Object oriented programming OOP is an approach to program organization and development, which attempts to eliminate some of the drawbacks of conventional programming methods by incorporating the best of structured programming features with several new concepts. OOP allows us to decompose a problem into number of entities called objects and then build data and methods (functions) around these entities. The data of an object can be accessed only by the methods associated with the object. Some of the Object-Oriented Paradigm (concepts) are: Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation 1. Emphasis is on data rather than procedure. 2. Programs are divided into objects. 3. Data Structures are designed such that they characterize the objects. 4 Methods that operate on the data of an object are tied together in the data structure. 5 Data is hidden and cannot be accessed by external functions. 6 Objects may communicate with each other through methods. CLASSES Class is blue print or an idea of an Object From one class any number of Instances can be created It is an encapsulation of attributes and methods

5 FIGURE class Ob1 Ob3 CIRCLE Ob2 RECTANGLE SQUARE syntax of CLASS class <ClassName> attributes/variables; Constructors(); methods(); Creating an Instance (How to create an object of the class) Instance is an Object of a class which is an entity with its own attribute values and methods. ClassName refvariable; refvariable = new Constructor (or) classname(); or ClassName refvariable = new Constructor (or) classname(); Inheritance Methods allows to reuse a sequence of statements Inheritance allows to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. The child class inherits characteristics of the parent class(i.e the child class inherits the methods and data defined for the parent class Method Binding Objects are used to call methods.

6 Method Binding is an object that can be used to call an arbitrary public method, on an instance that is acquired by evaluating the leading portion of a method binding expression via a value binding. It is legal for a class to have two or more methods with the same name. Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. Therefore the same-named methods must be distinguished: by the number of arguments, or by the types of arguments Overloading and inheritance are two ways to implement polymorphism. Method Overriding There may be some occasions when we want an object to respond to the same method but have different behavior when that method is called. That means, we should override the method defined in the superclass. This is possible by defining a method in a sub class that has the same name, same arguments and same return type as a method in the superclass. Then when that method is called, the method defined in the sub class is invoked and executed instead of the one in the superclass. This is known as overriding. Java History In 1990, Sun Microsystems started a project called Green. Many Java features are inherited from the earlier languages: B C C++ Java In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava. In 1995, Oak was renamed Java. A common story is that the name Java relates to the place from where the development team got its coffee. The name Java survived the trade mark search. Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystems in The original motivation is not Internet: platform-independent software embedded in consumer electronics devices. With Internet, the urgent need appeared to break the fortified positions of Intel, Macintosh and Unix programmer communities. Java as an Internet version of C++? No. Java was not designed to replace C++, but to solve a different set of problems. The Java Buzzwords(Features or advantages) The key considerations were summed up by the Java team in the following list of buzzwords: simple Java is designed to be easy for the professional programmer to learn and use. object-oriented: a clean, usable, pragmatic approach to objects, not restricted by the need for compatibility with other languages.

7 Robust: restricts the programmer to find the mistakes early, performs compile-time (strong typing) and run-time (exception-handling) checks, and manages memory automatically. Multithreaded: supports multi-threaded programming for writing program that perform concurrent computations Architecture-neutral: Java Virtual Machine provides a platform independent environment for the execution of Java byte code Interpreted and high-performance: Java programs are compiled into an intermediate representation byte code: a) can be later interpreted by any JVM b) can be also translated into the native machine code for efficiency. Distributed: Java handles TCP/IP protocols, accessing a resource through its URL much like accessing a local file. Dynamic: substantial amounts of run-time type information to verify and resolve access to objects at run-time. Secure: programs are confined to the Java execution environment and cannot access other parts of the computer. Portability: Many types of computers and operating systems are in use throughout the world and many are connected to the Internet Structure of Java Programs [Package statement section] [Import statement section] [class definition] //main method class definition class class-name public static void main(string args[]) statement1; statement2; Steps required to Execute the java program (1) Create the source file: open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java) file and class name are case sensitive and must be matched exactly (except the.java part) Example Program: HelloWorldApp.java class HelloWorldApp public static void main(string args[]) System.out.println( Hello World );

8 2)Compiling & Running the Program Compiling: is the process of translating source code written in a particular programming language into computer-readable machine code that can be executed. D:\>javac HelloWorldApp.java This command will produce a file HelloWorldApp.class, which is used for running the program with the command java. Running: is the process of executing program on a computer. D:\> java HelloWorldApp The Java Virtual Machine (JVM) is the runtime engine of the Java Platform, which allows any program written in Java or other language compiled into Java bytecode to run on any computer that has a native JVM. The JVM includes a just-in-time (JIT) compiler that converts the bytecode into machine language so that it runs as fast as a native executable Java Runtime Environment (JRE) The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language Java Development Kit (JDK) The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications. Byte Code Java bytecode is the result of the compilation of a Java program, an intermediate representation of that program which is machine independent. This bytecode can be run in any platform which has a Java installation in it. The Java bytecode is not completely compiled, but rather just an intermediate code sitting in the middle because it still has to be interpreted and executed by the JVM installed on the specific platform such as Windows, Mac or Linux. Upon compile, the Java source code is converted into the.class bytecode. Why Java is not 100% object oriented language? Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects. Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects. Data Types Java defines eight simple(primitive) types: 1)byte 8-bit integer type 2)short 16-bit integer type

9 3)int 32-bit integer type 4)long 64-bit integer type 5)float 32-bit floating-point type 6)double 64-bit floating-point type 7)char symbols in a character set 8)boolean logical values true and false byte: 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams or reading/writing in a file. short: 16-bit integer type. Range: to Example: short c = 1000; Usage: probably the least used simple type. int: 32-bit integer type. Range: to Example: int b = ; Usage: 1) Most common integer type. 2) Typically used to control loops and to index arrays. 3) Expressions involving the byte, short and int values are promoted to int before calculation. long: 64-bit integer type. Range: to Example: long lg = ; Usage: 1) useful when int type is not large enough to hold the desired value float: 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038. Example: float f = 1.5; Usage: 1) fractional part is needed 2) large degree of precision is not required double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308. Example: double pi = ; Usage: 1) accuracy over many iterative calculations 2) manipulation of large-valued numbers char: 16-bit data type used to store characters. Range: 0 to Example: char c = a ;

10 Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages. 2) Not the same as in C/C++ where char is 8-bit and represents ASCII only. boolean: Two-valued type of logical values. Range: values true and false. Example: boolean b = (1<2); Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for Variables Java uses variables to store data. To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) to associate an identifier with the variable 3) optionally, the variable may be assigned an initial value All done as part of variable declaration. Basic Variable Declaration datatype identifier [=value]; datatype must be A simple datatype User defined datatype (class type) Identifier is a recognizable name confirm to identifier rules Value is an optional initial value Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = ; char ch = 'x'; Variable Scope Scope determines the visibility of program elements with respect to other program elements. In Java, scope is defined separately for classes and methods: 1) variables defined by a class have a global scope 2) variables defined by a method have a local scope A scope is defined by a block: A variable declared inside the scope is not visible outside:

11 int n; n = 1;// this is illegal Arrays An array is a group of liked-typed variables referred to by a common name, with individual variables accessed by their index. Arrays are: 1) declared 2) created 3) initialized 4) used Also, arrays can have one or several dimensions. Array Declaration Array declaration involves: 1) declaring an array identifier 2) declaring the number of dimensions 3) declaring the data type of the array elements Two styles of array declaration: type array-variable[]; or type [] array-variable; Array Creation After declaration, no array actually exists. In order to create an array, we use the new operator: type array-variable[]; array-variable = new type[size]; This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable. Later we can refer to the elements of this array through their indexes: array-variable[index] The array index always starts with zero! The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error. Array Initialization Arrays can be initialized when they are declared: int monthdays[] = 31,28,31,30,31,30,31,31,30,31,30,31; Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements

12 Example: // Average an array of values. class Average public static void main(string args[]) double nums[] = 10.1, 11.2, 12.3, 13.4, 14.5; double result = 0; int i; for(i=0; i<5; i++) result = result + nums[i]; System.out.println("Average is " + result / 5); Multidimensional Arrays Multidimensional arrays are arrays of arrays: 1) declaration: int array[][]; 2) creation: int array = new int[2][3]; 3) initialization int array[][] = 1, 2, 3, 4, 5, 6 ; Allocating memory for two dimensional array dynamically When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For example, this following code allocates memory for the first dimension of twod when it is declared. It allocates the second dimension manually. // Manually allocate differing size second dimensions. class TwoDAgain public static void main(string args[]) int twod[][] = new int[4][]; twod[0] = new int[1]; twod[1] = new int[2]; twod[2] = new int[3]; twod[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) twod[i][j] = k; k++; for(i=0; i<4; i++) for(j=0; j<i+1; j++)

13 System.out.print(twoD[i][j] + " "); System.out.println(); Operators Java operators are used to build value expressions. Java provides a rich set of operators: 1) assignment 2) arithmetic 3) relational 4) logical 5) bitwise Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Examples: +,-,*,/,%,++,-- The Relational Operators: Example: ==,!=, >, <, >=,<= The Bitwise Operators: Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows: a = b = a&b = a b = a^b = ~a = ~ ~op Inverts all bits & op1 & op2 Produces 1 bit if both operands are 1 op1 op2 Produces 1 bit if either operand is 1 ^ op1 ^ op2 Produces 1 bit if exactly one operand is 1

14 >> op1 >> op2 << op1 << op2 Shifts all bits in op1 right by the value of op2 Shifts all bits in op1 left by the value of op2 Conditional Operator (? : ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x =(expression)?valueiftrue: valueiffalse Increment and Decrement The ++ and the are Java s increment and decrement operators instanceof Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is wriiten as: (Object reference variable )instanceof(class/interface type) public class Test public static void main(string args[]) String name = "James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); This would produce the following result: true Control Statements Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program. Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion

15 Selection Statements Java selection statements allow to control the flow of program s execution based upon conditions known only during run-time. Java provides four selection statements: 1) if Here is the general form of the if statement: if (condition) statement1; 2) if-else if (condition) statement1; else statement2; Nested ifs A nested if is an if statement that is the target of another if or else if(i == 10) if(j < 20) a = b; if(k > 100) c = d; // this if is else a = c; // associated with this else else a = d; // this else refers to if(i == 10) 3) if-else-if The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if(condition) statement; else if(condition) statement; else if(condition) statement;... else statement; 4) switch The switch statement is Java s multi way branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. switch (expression) case value1: // statement sequence break; case value2: // statement sequence break;... case valuen: // statement sequence break; default: // default statement sequence

16 Iteration Statements Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. Java provides three iteration statements: 1) while It repeats a statement or block while its controlling expression is true. Here is its general form: while(condition) // body of loop The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop // Demonstrate the while loop. class While public static void main(string args[]) int n = 10; while(n > 0) System.out.println("tick " + n); n--; 2) do-while The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is do // body of loop while (condition); Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise,the loop terminates. class DoWhile public static void main(string args[]) int n = 10; do System.out.println("tick " + n); n--;

17 while(n > 0); 3) for A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax: The syntax of a for loop is: for(initialization;boolean_expression; update) //Statements class ForTick public static void main(string args[]) int n; for(n=10; n>0; n--) System.out.println("tick " + n); The For-Each Version of the for Loop(Enhanced for loop) The general form of the for-each version of the for is shown here: for(type itr-var : collection) statement-block Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. The collection being cycled through is specified by collection. There are various types of collections that can be used with the for, but the only type used here is the array int nums[] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ; int sum = 0; for(int x: nums) sum += x; With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus, on the first iteration, x contains1;on the second iteration, x contains2;andsoon. Not only is the syntax streamlined, but it also prevents boundary errors.

18 Jump Statements Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. 2) continue The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. 3) return The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. In addition, Java supports exception handling that can also alter the control flow of a program. Type Conversion Size Direction of Data Type Widening Type Conversion (Casting down) Smaller Data Type Larger Data Type Narrowing Type Conversion (Casting up) Larger Data Type Smaller Data Type Conversion done in two ways Implicit type conversion (Widening Type Conversion) Carried out by compiler automatically Explicit type conversion Carried out by programmer using casting

19 byte -> short, int, long, float, doubl e short -> int, long, float, double char -> int, long, float, double int -> long, float, double Narrowing Type Conversion Programmer should describe the conversion explicitly byte and short are always promoted to int if one operand is long, the whole expression is promoted to long if one operand is float, the entire expression is promoted to float if any operand is double, the result is double Type Casting byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long - General form: (targettype) value Examples: 1) integer value will be reduced module bytes range: int i; byte b = (byte) i;

20 2) floating-point value will be truncated to integer value: float f; int i = (int) f; Classes in Java The class is at the core of Java. It is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. A class is declared by use of the class keyword A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. General form of a class: class classname type instance-variable-1; type instance-variable-n; type method-name-1(parameter-list) type method-name-2(parameter-list) type method-name-m(parameter-list) Creating Method(Introducing Methods) This is the general form of a method: type name(parameter-list) // body of method Methods that have a return type other than void. The syntax of return statement is return value; Ex: public static int f1(int a,int b) Example: Class Usage class Box //instance variable double width; double height; double depth; class BoxDemo public static void main(string args[]) Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20;

21 mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println ("Volume is " + vol); Example: To setting the dimensions of a box is to create a method that takes the dimensions of a box in its parameters and sets each instance variable appropriately. class Box double width; double height; double depth; // A method which computes and return volume double volume() return width * height * depth; // A method which sets dimensions of box (initialize the members of a class) void setdim(double w, double h, double d) width = w; height = h; depth = d; class BoxDemo5 public static void main(string args[]) Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize the dimension of each box mybox1.setdim(10, 20, 15); mybox2.setdim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

22 Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword. Declaring Objects Creating objects of a class is a two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. (or) Box mybox = new Box(); Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Boxobject will contain its own copies of the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement: mybox.width = 100; Constructors A constructor initializes the instance variables of an object. It is called immediately after the object is created but before the new operator completes. 1) it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default return type of a class When the class has no constructor, the default constructor automatically initializes all its instance variables with zero.

23 Example: Constructor class Box double width; double height; double depth; //Default constructor(without any argument) Box() System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; double volume() return width * height * depth; class BoxDemo public static void main(string args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); Output: Constructing Box Constructing Box Volume is Volume is Parameterized Constructors Parameterized constructors are accepting argument while creating an instance of the class.

24 Overloaded constructor: More than one constructor are defined in the class, depends on the number of arguments the constructors are executed. The following class Box defines a parameterized constructor and overloaded constructor that sets the dimensions of a box as specified by those parameters. class Box double width; double height; double depth; Box() //no argument constructor Width=height=depth=0.0d; Box(double w, double h, double d) //2 argument constructor width = w; height = h; depth = d; Box(double l) //one argument constructor width = height = depth = l; Box(Box ob) //copy constructor (accept the object as argument) width=ob.width; height=ob.height; depth=ob.depth; double volume() return width * height * depth; class BoxDemo public static void main(string args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(10,12,15); Box mybox2 = new Box(3); Box mybox3=new Box(mybox1); double vol; // get volume of first box

25 vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); The this Keyword this is always a reference to the object on which the method was invoked. Sometimes a method will need to refer to the object that invoked it. when a local variable has the same name as an instance variable, the local variable hides the instance variable. // Use this to resolve name-space collisions. Box(double width, double height, double depth) this.width = width; this.height = height; this.depth = depth; Garbage Collection Garbage collection is a mechanism to remove objects from memory when they are no longer needed. Garbage collection is carried out by the garbage collector: 1) The garbage collector keeps track of how many references an object has. 2) It removes an object from memory when it has no longer any references. 3) Thereafter, the memory occupied by the object can be allocated again. 4) The garbage collector invokes the finalize method. The finalize( ) Method A constructor helps to initialize an object just after it has been created. In contrast, the finalize method is invoked just before the object is destroyed: 1) implemented inside a class as: protected void finalize() 2) implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out Method overloading

26 Two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java supports polymorphism. When the methods are invoked, depends on the datatype or number of arguments the correct version of the method is identified. The return type alone is insufficient to distinguish two versions of a method. Example program for method overloading // Demonstrate method overloading. class OverloadDemo void test() System.out.println("No parameters"); // Overload test for one integer parameter. void test(int a) System.out.println("a: " + a); // Overload test for two integer parameters. void test(int a, int b) System.out.println("a and b: " + a + " " + b); // overload test for a double parameter double test(double a) System.out.println("double a: " + a); return a*a; class Overload public static void main(string args[]) OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25);

27 System.out.println("Result of ob.test(123.25): " + result); Note: When test ( ) is called with an integer argument inside Overload (ie) test(10), if no matching method is found, then it will invoke test(double a). Since, Java can automatically convert an integer into a double, and this conversion can be used to resolve the call. Access Control Encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. Java s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. When a member of a class is modified by the public specifier, then that member can be accessed by any other code. When a member of a class is specified as private, then that member can only be accessed by other members of its class. class Test int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) // set c's value c = i; int getc() // get c's value return c; class AccessTest public static void main(string args[]) Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! (private member cannot be accessed by outside of the class) // You must access c through its methods ob.setc(100); // OK

28 System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); Static Methods Class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions: They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. Example: // Demonstrate static variables, methods, and blocks. class UseStatic static int a = 3; static int b; static void meth(int x) System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); static System.out.println("Static block initialized."); b = a * 4; public static void main(string args[]) meth(42); As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a * 4 or 12. Then main( ) is called, which calls meth( ), passing 42 to x. Here is the output of the program: Static block initialized.

29 x = 42 a = 3 b = 12 static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For example, if you wish to call a static method from outside its class, you can do so using the following general form: classname.method( ) Here, classname is the name of the class in which the static method is declared. class StaticDemo static int a = 42; static int b = 99; static void callme() System.out.println("a = " + a); class StaticByName public static void main(string args[]) StaticDemo.callme(); //static method //static method invoked by using class name System.out.println("b = " + StaticDemo.b); Here is the output of this program: a = 42 b = 99 final keyword A variable can be declared as final. Doing so prevents its contents from being modified. Thus, a final variable is essentially a constant. This means that you must initialize a final variable when it is declared. For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; INHERITANCE:

30 Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.(or) In simple way, Inheritance can be defined as the process where one object acquires the properties of another. We can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. A new class is derived from an existing class: 1) existing class is called super-class 2) derived class is called sub-class A sub-class is a specialized version of its super-class: 1) has all non-private members of its super-class 2) may provide its own implementation of super-class methods Objects of a sub-class are a special kind of objects of a super-class. Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private.(private members never inherited. Still remains as private) Advantage or use of inheritance: Facilitates code reuse and avoids duplication of data. Software Reusability (among projects) Increased Reliability (resulting from reuse and sharing of well-tested code) Code Sharing (within a project) Consistency of Interface (among related objects) Software Components Rapid Prototyping (quickly assemble from pre-existing components) Polymorphism and Frameworks (high-level reusable components) Information Hiding Inheritance Basics To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The general form (syntax) class subclass-name extends superclass-name // body of class Member Access and Inheritance

31 Class A //Base class private int i; int k; Class B extends A //Derived(sub) class int j; public static void main(string args[]) B obj = new B(); //creating an instance of sub class obj.i=10 //error (private member never inherited) oj.k=23; //access to public member of a super calss obj.j=10 //correct A Superclass Variable Can Reference a Subclass Object A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. class A int i=10; public void disp() System.out.println( The iv al is +i); class B extends A int j; public static void main(string a[]) B bob=new B(); //object of derived class A aob; //object reference of base class aob=bob; //base class reference object is pointing to derived class object aob.disp(); //calls the superclass disp method aob.j=15; //error; since j is a member of sub class B

32 Note: That is, when a reference to a subclass object is assigned to a superclass reference variable, you will have access only to those parts of the object defined by the superclass. Types of inheritance Acquiring the properties of an existing Object into newly creating Object to overcome the re declaration of properties in deferent classes. Class A Class B extends implements Class C 4)Multiple inheritance Single inheritance: When a class extends by another one class only then we call it a single inheritance. class A int i; void showi() System.out.println("i: " + i); class B extends A int j; void showj() System.out.println( j: " + j); void sum() System.out.println("i+j: " + (i+j)); class SimpleInheritance public static void main(string args[])

33 A a = new A(); B b = new B(); a.i = 10; System.out.println("Contents of a: "); a.showi(); /* The subclass has access to all public members of its superclass. */ b.i = 7; b.j = 8; System.out.println("Contents of b: "); subob.showi(); subob.showj(); System.out.println("Sum of I and j in b:"); b.sum(); 2. Multi-level inheritance: one can inherit from a derived class (derived from another class), thereby making this derived class as the base class for the new class. class Box //Base class private double width, height, depth; Box(double w, double h, double d) //constructor which initialize the members width = w; height = h; depth = d; double volume() return width * height * depth; class BoxWeight extends Box //Derived from Box class //Adding the weight variable to the Box class double weight; BoxWeight(double w, double h, double d, double m) super(w, h, d); //Invokes the base class constructor weight = m; class Ship extends BoxWeight //Derived from BoxWeight calss (derived class) //Adding the cost variable to the BoxWeight class double cost; Ship(double w, double h, double d, double m, double c) super(w, h, d, m); //Invokes the base class constructor cost = c;

34 class DemoShip public static void main(string args[]) Ship ship1 = new Ship(10, 20, 15, 10, 3.41); double vol; vol = ship1.volume(); System.out.println("Volume of ship1 is " + vol); System.out.print("Weight of ship1 is ); System.out.println(ship1.weight); System.out.print("Shipping cost: $"); System.out.println(ship1.cost); Note: Multiple inheritance (java does not support this directly but indirectly achieve this by implementing interfaces) Use of super keyword: calls the superclass constructor. used to access a member of the superclass that has been hidden by a member of a subclass. super.a=a; When a sub-class declares the variables or methods with the same names and types as its super-class.the re-declared variables/methods hide those of the super-class. Example: (To access base class member when both base and derived class having same variable name) class A int i; class B extends A int i; B(int a, int b) super.i = a; //initialize the base class member i i = b; //initialize its own member i void show() System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i);

35 It is used to call a constructor of super class from constructor of sub class which should be first statement in a derived class constructor. super(a,b); Example(To invoke the base class constructor) class A int i; A(int i) this.i=i; Class B extends A int j; B(int k,l) Super(k); //Invoke the base class constructor j=l; //initialize its member Public static void main(string a[]) B bobj=new B(2,5); It is used to call a super class method from sub class method to avoid redundancy of code super.addnumbers(a, b); Example(To invoke the base class method when both base and derived class having same method name) class A int i=5; void dis() System.out.println(The value of i is +i); Class B extends A

36 int j=7; void dis() System.out.println(The value of j is +j); Public static void main(string a[]) B bobj=new B(); bobj.dis(); //invoke the dis() method in class B not in A super.dis(); //invoke the dis() method in class A not in B Polymorphism Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Example: function overloading, function overriding Static polymorphism: During compilation time, achieved with help of Method Overloading. Dynamic(run time) polymorphism: During runtime, achieved with help of Method Overriding (by assigning the object of the derived class to the base class object reference). Applying Method Overriding When a method of a sub-class has the same name and type as a method of the super-class, we say that this method is overridden. When an overridden method is called from within the sub-class: 1) it will always refer to the sub-class method 2) super-class method is hidden Example b(method overriding) // Using run-time polymorphism. class Figure double dim1; double dim2; Figure(double a, double b) dim1 = a; dim2 = b; double area() System.out.println("Area for Figure is undefined."); return 0;

37 class Rectangle extends Figure Rectangle(double a, double b) super(a, b); // override area for rectangle double area() System.out.println("Inside Area for Rectangle."); return dim1 * dim2; class Triangle extends Figure Triangle(double a, double b) super(a, b); // override area for right triangle double area() System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; class FindAreas public static void main(string args[]) Figure f = new Figure(10, 10); // f is a base class(figure) object Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; //base class (Figure) reference not object figref = r; //figref holds the address of Rectanle object System.out.println("Area is " + figref.area()); figref = t; //figref holds the address of Triangle object System.out.println("Area is " + figref.area()); figref = f; //figref holds the address of Figure object System.out.println("Area is " + figref.area()); The output from the program is shown here:

38 Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0 Overloading vs. Overriding Overloading Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Overriding Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overriding lets you define a similar operation in different ways for different object types Abstract Classes There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. use the modifier abstract on a class header to declare an abstract class abstract class Vehicle An abstract class often contains abstract methods, though it doesn t have to o Abstract methods consist of only methods declarations, without any method body public abstract class Vehicle String name; public String getname() return name; \\ method body abstract public void move(); \\ no body! Note: The non-abstract child of an abstract class must override the abstract methods of the parent

39 An abstract class cannot be instantiated Abstract Method Syntax: abstract type name(parameter-list); Two kinds of methods: 1) concrete may be overridden by sub-classes 2) abstract must be overridden by sub-classes It is illegal to define abstract constructors or static methods. Using final with inheritance final keyword is used declare constants which can not change its value of definition. final Variables can not change its value. final Methods can not be Overridden or Over Loaded final Classes can not be extended or inherited Preventing Overriding with final A method declared final cannot be overridden in any sub-class: class A final void meth() System.out.println("This is a final method."); class B extends A void meth() // ERROR! Can't override. System.out.println("Illegal!"); Using final to Prevent Inheritance final class A //... // The following class is illegal. class B extends A // ERROR! Can't subclass A //... As the comments imply, it is illegal for B to inherit A since A is declared as final. Packages

40 Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and name space management. A package is both a naming and a visibility control mechanism: 1) divides the name space into disjoint subsets. It is possible to define classes within a package that are not accessible by code outside the package. 2) controls the visibility of classes and their members It is possible to define class members that are only exposed to other members of the same package. Types: 1.Built-in(predefined) packages: eg: java.lang - bundles the fundamental classes java.io - classes for input, output functions are bundled in this package, etc. 2.User defined packages Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related. Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes. Creating a package: To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. This is the general form of the package statement: package pkgname; Ex: package mypackage; class MyClass1 class MyClass2 means that all classes in this file belong to the mypackage package. The package statement creates a name space where such classes are stored. You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The syntax is package pkg1[.pkg2[.pkg3]]; ex:package java.awt.image; Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Example:

41 package MyPack; class Balance String name; double bal; Balance(String n, double b) name = n; bal = b; void show() if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); class AccountBalance public static void main(string args[]) Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", ); current[1] = new Balance("Will Tell", ); current[2] = new Balance("Tom Jackson", ); for (int i=0; i<3; i++) current[i].show(); Save, compile and execute: 1) call the file AccountBalance.java 2) save the file in the directory MyPack 3) compile; AccountBalance.class should be also in MyPack 4) set access to MyPack in CLASSPATH variable, or make the parent of MyPack your current directory 5) run: java MyPack.AccountBalance Make sure to use the package-qualified class name. Importing of Packages Since classes within packages must be fully-qualified with their package names, it would be tedious to always type long dot-separated names. The import statement allows to use classes or whole packages directly. This is the general form of the import statement: import pkg1[.pkg2].(classname *); Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot (.). Ex: import java.util.date; //built in package import java.io.*; //built in package Importing of a concrete class: import mypackage1.mypackage2.myclass;

42 Importing of all classes within a package: import mypackage1.mypackage2.*; Example:(To create package and how to import or use that package in some other class) A package MyPack with one public class Balance. The class has two same-package variables: public constructor and a public show method. /* Now, the Balance class, its constructor, and its show() method are public. This means that they can be used by non-subclass code outside their package.*/ //Example program for creating a package package MyPack; //package declaration public class Balance String name; double bal; public Balance(String n, double b) //constructor to initialize the members name = n; bal = b; public void show() if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); The importing code has access to the public class Balance of the MyPack package and its two public members: //Example program for accessing a package import MyPack.*; // import the package which created in the above example class TestBalance public static void main(string args[]) /* Because Balance is public, you may use Balance class and call its constructor. */ Balance test = new Balance("J. J. Jaspers", 99.88); //class available in MyPack package test.show(); Note: A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration. Interfaces An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Using interface, we specify what a class must do, but not how it does this.

43 An interface is syntactically similar to a class, but it lacks instance variables and its methods are declared without any body. An interface is defined with an interface keyword. An interface is defined much like a class. This is the general form of an interface: access interface name return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; //... return-type method-namen(parameter-list); type final-varnamen = value; The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends Example interface Callback void callback(int param); Interface methods have no bodies they end with the semicolon after the parameter list. They are essentially abstract methods. An interface may include variables, but they must be final, static and initialized with a constant value. In a public interface, all members are implicitly public. Differences between classes and interfaces Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. One class can implement any number of interfaces. Interfaces are designed to support dynamic method resolution at run time. Interface is little bit like a class... but interface is lack in instance variables...that's u can't create object for it...

44 Interfaces are developed to support multiple inheritance... The methods present in interfaces are pure abstract.. The access specifiers public,private,protected are possible with classes, but the interface uses only one spcifier public... Interfaces contain only the method declarations... no definitions... A interface defines, which method a class has to implement. This is way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface. You cannot instantiate an interface. An interface does not contain any constructors. Another important point about interfaces is that a class can implement multiple interfaces Implementing an interface Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. General format of a class that includes the implements clause: access class name [extends super-class] implements interface1, interface2,, interfacen Access is public or default. If a class implements several interfaces, they are separated with a comma. If a class implements two interfaces that declare the same method, the same method will be used by the clients of either interface. The methods that implement an interface must be declared public. The type signature of the implementing method must match exactly the type signature specified in the interface definition. Two types of access: 1) public interface may be used anywhere in a program 2) default interface may be used in the current package only class Client implements Callback // Implement Callback's interface defined earlier public void callback(int p) System.out.println("callback called with " + p); It is both permissible and common for classes that implement interfaces to define additional members of their own. For example, the following version of Client implements callback( ) and adds the method nonifacemeth( ):

45 class Client implements Callback // Implement Callback's interface public void callback(int p) System.out.println("callback called with " + p); void nonifacemeth() System.out.println("Classes that implement interfaces " + "may also define other members, too."); Accessing Implementations Through Interface References You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be referred to by such a variable. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. class TestIface public static void main(string args[]) Callback c = new Client(); c.callback(42); The output of this program is shown here: callback called with 42 Example for interface //Interface declaration interface Drawable void draw(); //Implementation //c is the reference of the interface callback and holding the //address of Client class object class Rectangle implements Drawable public void draw()system.out.println("drawing rectangle"); class Circle implements Drawable public void draw()system.out.println("drawing circle"); //Using interface class TestInterface1 public static void main(string args[]) Drawable d=new Circle();

46 d.draw(); Output: drawing circle Multiple inheritance in Java by interface interface Printable void print(); interface Showable void show(); class A7 implements Printable,Showable public void print()system.out.println("hello"); public void show()system.out.println("welcome"); public static void main(string args[]) A7 obj = new A7(); obj.print(); obj.show(); Output:Hello Welcome variables in interface Variables declared in an interface must be constants. A technique to import shared constants into multiple classes: 1) declare an interface with variables initialized to the desired values 2) include that interface in a class through implementation As no methods are included in the interface, the class does not implement anything except importing the variables as constants An interface with constant values: interface SharedConstants int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5;

47 AskMe class includes all shared constants in the same way, using them to display the result, depending on the value received: class AskMe implements SharedConstants static void answer(int result) switch(result) case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later"); break; case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break; Extending interfaces One interface may inherit another interface. The inheritance syntax is the same for classes and interfaces. interface MyInterface1 void mymethod1( ) ; interface MyInterface2 extends MyInterface1 void mymethod2( ) ; When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. Example: Consider interfaces A and B. interface A void meth1(); void meth2(); interface B extends A void meth3(); MyClass must implement all of A and B methods: class MyClass implements B public void meth1() System.out.println("Implement meth1()."); public void meth2() System.out.println("Implement meth2().");

48 public void meth3() System.out.println("Implement meth3()."); Create a new MyClass object, then invoke all interface methods on it: class IFExtend public static void main(string arg[]) MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); EXCEPTION HANDLING: Definition: An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory. Fundamentals(concept) Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. 1) try a block surrounding program statements to monitor for exceptions 2) catch together with try, catches specific kinds of exceptions and handles them in some way 3) finally specifies any code that absolutely must be executed whether or not an exception occurs 4) throw used to throw a specific exception from the program 5) throws specifies which exceptions a given method can throw This is the general form of an exception-handling block: try // block of code to monitor for errors

49 catch (ExceptionType1 exob) // exception handler for ExceptionType1 catch (ExceptionType2 exob) // exception handler for ExceptionType2 //... finally // block of code to be executed after try block ends Here, ExceptionType is the type of exception that has occurred. Benefits of exception handling Separating Error-Handling code from regular business logic code Propagating errors up the call stack Grouping and differentiating error types Exception Types All exceptions are sub-classes of the build-in class Throwable. Throwable contains two immediate sub-classes: 1) Exception exceptional conditions that programs should catch The class includes: a) Runtime Exception defined automatically for user programs to include: division by zero, invalid array indexing, etc. b) user-defined exception classes 2) Error exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them Uncaught Exceptions If an exception is thrown and not caught (operationally, an exception is thrown when there is no applicable handler specified), the uncaught exception is handled by the runtime; the routine that does this is called the uncaught exception handler. The most common default behaviour is to terminate the program and print an error message to the console. These usually indicate programming bugs, such as logic errors or improper use of an API. Example: NullPointerException.Divisionby Zero,ArrayIdexOutOfBound Ecception etc class Exc0 public static void main(string args[]) int d = 0; int a = 42 / d; When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception.

50 Here is the exception generated when this example is executed: java.lang.arithmeticexception: / by zero at Exc0.main(Exc0.java:4) Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line number, 4, are all included in the simple stack trace. Also, notice that the type of exception thrown is a subclass of Exception called ArithmeticException, which more specifically describes what type of error happened. Using try and catch Although the default exception handler provided by the Java run-time system is useful for debugging, we have to handle the exception by writing our own code using try-catch block. try block-place the code(statement)that generate exception catch block- handle the exception by specifying its type Example: class Exc2 public static void main(string args[]) int d, a; try // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); // control never return back to try after catch catch (ArithmeticException e) // catch divide-by-zero error System.out.println("Division by zero."); a=0; System.out.println("After catch statement."); This program generates the following output: Division by zero. After catch A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. Displaying a Description of an Exception Throwable overrides the tostring( ) method (defined by Object) so that it returns a string containing a description of the exception. You can display this description in a println( )

51 statement by simply passing the exception as an argument. For example, the catch block in the preceding program can be rewritten like this: catch (ArithmeticException e) System.out.println("Exception: " + e); a = 0; // set a to zero and continue When this version is substituted in the program, and the program is run, each divide-by zero error displays the following message: Exception: java.lang.arithmeticexception: / by zero Multiple catch Clauses To handle more than one exception could be raised by a single piece of code; we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. // Demonstrate multiple catch statements. class MultiCatch public static void main(string args[]) try int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = 1 ; c[42] = 99; catch(arithmeticexception e) System.out.println("Divide by 0: " + e); catch(arrayindexoutofboundsexception e) System.out.println("Array index oob: " + e); System.out.println("After try/catch blocks."); Here is the output generated by running it both ways: C:\>java MultiCatch a = 0 Divide by 0: java.lang.arithmeticexception: / by zero After try/catch blocks.

52 C:\>java MultiCatch TestArg a = 1 Array index oob: java.lang.arrayindexoutofboundsexception:42 After try/catch blocks. When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Ex: /* This program contains an error.a subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. */ class SuperSubCatch public static void main(string args[]) try int a = 0; int b = 42 / a; catch(exception e) System.out.println("Generic Exception catch."); /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(arithmeticexception e) // ERROR - unreachable System.out.println("This is never reached."); The second catch statement is unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try. // An example of nested try statements. class NestTry public static void main(string args[]) try int a = args.length; /* If no command-line args are present,the following statement will generate a divide-by-zero exception. */ int b = 42 / a;

53 System.out.println("a = " + a); try // nested try block /* If one command-line arg is used,then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) int c[] = 1 ; c[42] = 99; // generate an out-of-bounds exception catch(arrayindexoutofboundsexception e) System.out.println("Array index out-of-bounds: " + e); catch(arithmeticexception e) System.out.println("Divide by 0: " + e); Output: C:\>java NestTry Divide by 0: java.lang.arithmeticexception: / by zero C:\>java NestTry One a = 1 Divide by 0: java.lang.arithmeticexception: / by zero C:\>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.arrayindexoutofboundsexception:42 throw using the throw statement we can throw an exception explicitly. The general form of throw is shown here: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-throwable classes, such as String andobject, cannot be used as exceptions. There are two ways you can obtain a Throwable object:using a parameter in a catch clause, or creating one with the new operator. // Demonstrate throw. class ThrowDemo static void demoproc() try throw new NullPointerException("demo"); catch(nullpointerexception e) System.out.println("Caught inside demoproc.");

54 Throws throw e; // rethrow the exception public static void main(string args[]) try demoproc(); catch(nullpointerexception e) System.out.println("Recaught: " + e); Here is the resulting output: Caught inside demoproc. Recaught: java.lang.nullpointerexception: demo A throws clause lists the types of exceptions that a method might throw. except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause Syntax: type method-name(parameter-list) throws exception-list // body of method Example: class ThrowsDemo static void throwone() throws IllegalAccessException System.out.println("Inside throwone."); throw new IllegalAccessException("demo"); public static void main(string args[]) try throwone(); catch (IllegalAccessException e) System.out.println("Caught " + e); finally finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.

55 The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. // Demonstrate finally. class FinallyDemo // Through an exception out of the method. static void proca() try System.out.println("inside proca"); throw new RuntimeException("demo"); finally System.out.println("procA's finally"); // Return from within a try block. static void procb() try System.out.println("inside procb"); return; finally System.out.println("procB's finally"); // Execute a try block normally. static void procc() try System.out.println("inside procc"); finally System.out.println("procC's finally"); public static void main(string args[]) try proca(); catch (Exception e) System.out.println("Exception caught"); procb(); procc(); Here is the output generated by the preceding program: inside proca

56 proca s finally Exception caught inside procb procb s finally inside procc procc s finally Creating Your Own Exception Subclasses Although Java s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. The following example declares a new subclass of Exception and then uses that subclass to signal an error condition in a method. It overrides the tostring( ) method, allowing a carefully tailored description of the exception to be displayed. // This program creates a custom exception type. class MyException extends Exception private int detail; MyException(int a) detail = a; public String tostring() return "MyException[" + detail + "]"; class ExceptionDemo static void compute(int a) throws MyException System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); public static void main(string args[]) try compute(1); compute(20); catch (MyException e) System.out.println("Caught " + e); Here is the result: Called compute(1) Normal exit Called compute(20) Caught MyException[20]

57 Java s Built-in Exceptions Inside the standard package java.lang, Java defines several exception classes. The unchecked exceptions defined in java.lang are listed in Table Table 10-2 lists those exceptions defined by java.lang that must be included in a method s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. Multithreaded Programming

58 Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. What is Multithreading? In multithreading, the thread is the smallest unit of code that can be dispatched by the thread scheduler A single program can perform two tasks using two threads Only one thread will be executing at any given point of time given single-processor architecture Ex: a text editor can format text at the same time that it is printing, Difference between thread based multitasking and process based multitasking Thread based multitasking It require less overhead It is a lightweight task Share their address spaces inter-thread communication is inexpensive context-switching from one thread to another is low-cost Process based multitasking It requires more overhead It is a heavyweight task It require their own separate address spaces inter-process communication is expensive context-switching from one process to another is high-cost Advantages: Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. Enhanced performance by decreased development time Simplified and streamlined program coding The Java Thread Model Java has completely done away with the event loop/polling mechanism (Event loop/polling means- Executing one process after another which results in CPU time wastage) Life cycle of a Thread Threads exist in several states. Running- ready to run as soon as it gets CPU time. Suspended- temporarily suspends its activity. Blocked - blocked when waiting for a resource Dead when it is terminated A suspended thread can then be resumed, allowing it to pick up where it left off.

59 The Thread class Java s multithreading feature is built into the Thread class The main Thread When a Java program starts executing: the main thread begins running the main thread is immediately created when main() commences execution Information about the main or any thread can be accessed by obtaining a reference to the thread using a public, static method in the Thread class called currentthread( ) Creating Threads To create a new thread a program will: 1) extend the Thread class, or 2) implement the Runnable interface Thread class encapsulates a thread of execution. The whole Java multithreading environment is based on the Thread class. 1.Using Runnable Interface To create a new thread by implementing the Runnable interface: 1) create a class that implements the run method (inside this method, we define the code that constitutes the new thread):

60 public void run() 2) instantiate a Thread object within that class, a possible constructor is: Thread(Runnable threadob, String threadname) 3) call the start method on this object (start calls run): void start() Ex: public class ThreadDemo implements Runnable public void run() for(int counter=1;counter<=100;counter++) System.out.println("thread is running..."+counter); public static void main(string args[]) ThreadDemo threaddemo = new ThreadDemo(); Thread t1 = new Thread(threadDemo); t1.start(); Output: thread is running...1 thread is running...2 thread is running...99 thread is running Creating Multiple Threads public class ThreadDemo implements Runnable public void run() for(int counter=1;counter<=100;counter++) System.out.println( Thread.currentThread().getName()+ thread is running..."+counter ); public static void main(string args[]) ThreadDemo threaddemo = new ThreadDemo(); Thread t1 = new Thread(threadDemo, First ); Thread t2 = new Thread(threadDemo, Second ); t1.start();

61 t2.start(); Output: Firstthread is running...1 Secondthread is running...1 Firstthread is running...2 Secondthread is running...2 Secondthread is running By Extending Thread class The second way to create a new thread: 1) create a new class that extends Thread 2) create an instance of that class Thread provides both run and start methods: 1) the extending class must override run 2) it must also call the start method 3) start( ) in turn calls the thread s run( ) method Example public class ThreadDemo1 extends Thread public void run() System.out.println("thread is running..."); public static void main(string args[]) ThreadDemo1 threaddemo=new ThreadDemo1(); threaddemo.start(); Thread Methods Start: a thread by calling start its run method Sleep: suspend a thread for a period of time Run: entry-point for a thread Join: wait for a thread to terminate isalive: determine if a thread is still running getpriority: obtain a thread s priority getname: obtain a thread s name

62 Control Thread Execution Two ways exist by which you can determine whether a thread has finished: The isalive( ) method will return true if the thread upon which it is called is still running; else it will return false The join( ) method waits until the thread on which it is called terminates. Syntax: final boolean isalive() final void join() throws InterruptedException class DemoThread implements Runnable String name; Thread thread; DemoThread(String threadname) name = threadname; thread = new Thread(this, name); System.out.println("New Thread: " + thread); thread.start(); public void run() try for (int i = 5; i > 0; i--) System.out.println("Child Thread: " + i); Thread.sleep(1000); catch (InterruptedException e) System.out.println(name + "Interrupted"); System.out.println(name + "Exiting"); public class MultiThreadImpl public static void main(string args[]) DemoThread t1 = new DemoThread("A"); DemoThread t2 = new DemoThread("B"); DemoThread t3 = new DemoThread("C"); System.out.println("Thread A is alive: " + t1.thread.isalive()); System.out.println("Thread B is alive: " + t2.thread.isalive()); System.out.println("Thread C is alive: " + t1.thread.isalive()); try System.out.println("Waiting for child threads to finish");

63 t1.thread.join(); t2.thread.join(); t3.thread.join(); catch (InterruptedException e) System.out.println("Main thread interrupted"); System.out.println("Thread A is alive: " + t1.thread.isalive()); System.out.println("Thread A is alive: " + t1.thread.isalive()); System.out.println("Thread A is alive: " + t1.thread.isalive()); System.out.println("Main thread exiting"); Output: New Thread: Thread[A,5,main] New Thread: Thread[B,5,main] Child Thread: 5 New Thread: Thread[C,5,main] Thread A is alive: true Thread B is alive: true Thread C is alive: true Waiting for child threads to finish Child Thread: 5 Child Thread: 5 Child Thread: 4 Child Thread: 4 Child Thread: 4 Child Thread: 3 Child Thread: 3 Child Thread: 3 Child Thread: 2 Child Thread: 2 Child Thread: 2 Child Thread: 1 Child Thread: 1 Child Thread: 1 BExiting CExiting AExiting Thread A is alive: false Thread A is alive: false Thread A is alive: false Main thread exiting Thread Priorities When there are multiple threads running at the same time, how the CPU decides which thread should be given more time to execute and complete first? A thread priority decides: The importance of a particular thread, as compared to the other threads when to switch from one running thread to another The term that is used for switching from one thread to another is context switch Threads which have higher priority are usually executed in preference to threads that have lower priority When the thread scheduler has to pick up from several threads that are runnable, it will check the thread priority and will decide when a particular has to run The threads that have higher-priority usually get more CPU time as compared to lower-priority threads.

64 A thread can voluntarily relinquish control by explicitly yielding, sleeping, or blocking on pending Input/ Output All threads are examined and the highest-priority thread that is ready to run is given the CPU A thread can be preempted by a higher priority thread A lower-priority thread that does not yield the processor is superseded, or preempted by a higher-priority thread Pre -emptive multitasking. When two threads with the same priority are competing for CPU time, threads are time-sliced in round-robin fashion in case of Windows like OS. Thread Preemption A higher priority thread can also preempt a lower priority thread Actually, threads of equal priority should evenly split the CPU time Every thread has a priority When a thread is created it inherits the priority of the thread that created it The methods for accessing and setting priority are as follows: public final int getpriority( ); public final void setpriority (int level); The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. Example: public class ThreadDemo implements Runnable public void run() for(int counter=1;counter<=100;counter++) System.out.println(Thread.currentThread().getName()+"thread is running..."+counter); public static void main(string args[]) ThreadDemo threaddemo = new ThreadDemo(); Thread t1 = new Thread(threadDemo,"First"); t1.setpriority(thread.max_priority); Thread t2 = new Thread(threadDemo,"Second"); t2.setpriority(thread.min_priority); t1.start(); t2.start(); Thread Synchronization Threads often need to share data. Different threads shouldn t try to access and change the same data at the same time Threads must therefore be synchronized Key to synchronization is the concept of the monitor (also called a semaphore).

65 For example, imagine a Java application where one thread (which let us assume as producer) writes data to a data structure, while a second thread (consider this as Consumer) reads data from the data structure. The consumer thread should wait till the producer thread has finished writing into the data structure, i.e., till the producer thread returns from method M1. The moment the producer thread returns from method M1, the consumer thread should be allowed to access the data structure through method M2. Using Synchronized Methods If a thread wants to enter an object s monitor, it has to just call the synchronized method of that object While a thread is executing a synchronized method, all other threads that are trying to invoke that particular synchronized method or any other synchronized methodof the same object, will have to wait. Every object in Java has a lock Using synchronization enables the lock and allows only one thread to access that part of code Synchronization can be applied to: A method public synchronized withdraw() A block of code synchronized (objectreference) Synchronized methods in subclasses use same locks as their super classes. The Synchronized Statement Syntax for block of code: public void run() synchronized(obj) obj.withdraw(500); Example: class Account private int balance; public Account(int amount) balance=amount; public synchronized void withdraw(int bal)

66 try Thread.sleep(1000); catch(interruptedexception ex) System.out.println( Interrupted.."+ex); balance= balance-bal; System.out.println("Balance remaining:::" + balance); class Joint_Account implements Runnable Account account; public Joint_Account(Account account) this.account=account; public void run() account.withdraw(500); class SynchEx public static void main(string args[]) Account a1=new Account(10000); Joint_Account partner1=new Joint_Account(a1); Joint_Account partner2=new Joint_Account(a1); Thread t1=new Thread(partner1); Thread t2=new Thread(partner2); t1.start(); t2.start(); Inter-Thread Communication in Java Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.it is implemented by following methods of Object class: wait() notify() notifyall() 1) wait() method Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyall() method for this object, or a specified amount of time has elapsed.

67 The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. Method public final void wait()throws InterruptedException public final void wait(long timeout)throws InterruptedException Description waits until object is notified. waits for the specified amount of time. 2) notify() method Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify() 3) notifyall() method Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyall() Understanding the process of inter-thread communication The point to point explanation of the above diagram is as follows: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyall() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock.

68 6. After completion of the task, thread releases the lock and exits the monitor state of the object. Why wait(), notify() and notifyall() methods are defined in Object class not Thread class? It is because they are related to lock and object has a lock. Difference between Wait and Sleep method wait() sleep() wait() method releases the lock is the method of Object class is the non-static method is the non-static method should be notified by notify() sleep() method doesn't release the lock. is the method of Thread class is the static method is the static method after the specified amount of time, sleep is completed. Example of inter thread communication in java class Customer int amount=10000; synchronized void withdraw(int amount) System.out.println("going to withdraw..."); if(this.amount<amount) System.out.println("Less balance; waiting for deposit..."); trywait();catch(exception e) this.amount-=amount; System.out.println("withdraw completed..."); synchronized void deposit(int amount) System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); class Test public static void main(string args[]) final Customer c=new Customer(); new Thread() public void run()c.withdraw(15000); start();

69 new Thread() public void run() c.deposit(10000); start(); Input and Output(IO) Java programs perform I/O through streams. A stream is: an abstraction that either produces or consumes information and linked to a physical device by the Java I/O system All streams behave similarly, even if the actual physical devices to which they are linked differ. Thus the same I/O classes can be applied to any kind of device as they abstract the difference between different I/O devices. Java s stream classes are defined in the java.io package. Java 2 defines two types of streams: byte streams character streams Byte streams: provide a convenient means for handling input and output of bytes are used for reading or writing binary data Character streams: provide a convenient means for handling input and output of characters use Unicode, and, therefore, can be internationalized The Predefined Streams System class of the java.lang package contains three predefined stream variables, in, out, and err. These variables are declared as public and static within System: System.out refers to the standard output stream which is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. I/O Streams hierarchy

70 Byte Stream Classes Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. BufferedInputStream BufferedOutputStream To read & write data into buffer FileInputStream FileOutputStream To read & write data into file ObjectInputStream ObjectOutputStream To read & write object into secondary device (serialization) Character Stream classes The character-based streams simply provide a convenient and efficient means for handling characters. BufferedReader To read & write data into buffer BufferedWriter FileReader FIleWriter InputStreamReader OutputStreamWriter To read & write data into file Bridge from character stream to byte stream Reading Console Input - Stream Wrapping

71 The preferred method of reading console input in Java 2 is to use a character stream InputStreamReader class acts as a bridge between byte and character streams Console input is accomplished by reading from System.in To get a character-based stream, you wrap System.in in a BufferedReader object The BufferedReader class supports a buffered input stream. Its most commonly used constructor is shown as follows: BufferedReader(Reader inputreader) Here inputreader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputstream) Because System.in refers to an object of type InputStream, it can be used for inputstream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard, and which in turn enables character input from a byte stream InputStream that is System.in). BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Reading Characters int read( ) throws IOException Whenever the read( ) method is called, it reads a character from the input stream and returns an integer value. If the end of the stream is encountered, -1 is returned. public class BRRead public static void main (String args[ ]) throws IOException char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println( Enter Characters, q to quit ); do c = (char) br.read( ); System.out.println( c ); while (c!= q ); Reading Strings To read a string from the keyboard, use the version of readline( ) that is a member of the BufferedReader class. String readline( ) throws IOException Example: import java.io.*;

72 public class BRReadLine public static void main (String args[]) throws IOException String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println( Enter Characters, stop to quit ); do str = br.readline( ); System.out.println ( str ); while (!str.equals( stop )); Writing Console Output print( ) and println( ) are console output methods defined in PrintStream class System.out is a byte stream used to write bytes. The PrintWriter Class PrintWriter is one of the character-based classes.using a character-based class for console output makes it easier to internationalize your program. PrintWriter(OutputStream outputstream, boolean flushonnewline) import java.io.*; public class PrintWriterDemo public static void main(string args[]) PrintWriter pw = new PrintWriter(System.out, true); pw.println("this is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); Reading and Writing Files The File class is a convenience class for writing character files. The File class deals directly with files and the file system. The File class does not specify how information is retrieved from, or stored in files, it describes the properties of a file itself. A File object is used to obtain or manipulate information associated with a disk file, such as the permissions, time, date and directory path.

73 Two of the most often-used stream classes are FileInputStream and FileOutputStream,which create byte streams linked to files. Methods: FileInputStream(String filename) throws FileNotFoundException FileOutputStream(String filename) throws FileNotFoundException public int read() throws IOException (Read a single character) public int read(char[] cbuf,int off,int len) throws IOException public void write(int c) throws IOException (Write a single character) Example: /* Display the content of text file.(sam.txt)*/ import java.io.*; class ShowFile public static void main(string args[]) throws IOException int i; FileInputStream fin; try fin = new FileInputStream( sam.txt ); catch(filenotfoundexception e) System.out.println("File Not Found"); return; // read characters until EOF is encountered do i = fin.read(); if(i!= -1) System.out.print((char) i); while(i!= -1); fin.close(); Example: /* Copy a text file. For example, to copy a file called FIRST.TXT to a file called SECOND.TXT */ import java.io.*; class CopyFile public static void main(string args[]) throws IOException int i; FileInputStream fin; FileOutputStream fout; try

74 // open input file try fin = new FileInputStream( first.txt ); catch(filenotfoundexception e) System.out.println("Input File Not Found"); return; // open output file try fout = new FileOutputStream( second.txt ); catch(filenotfoundexception e) System.out.println("Error Opening Output File"); return; // Copy File try do i = fin.read(); if(i!= -1) fout.write(i); while(i!= -1); catch(ioexception e) System.out.println("File Error"); fin.close(); fout.close(); Serialization Object serialization is the process of saving an object's state to a sequence of bytes (on disk), as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism to handle object serialization You can only serialize the objects of a class that implements Serializable interface After a serialized object is written to a file, it can be read from the file and deserialized (that is we can recreate the object in memory) The process of Serialization and DeSerialization is JVM independent. That is, an object can be serialized on one platform and deserialized on an entirely different platform. Classes ObjectInputStream and ObjectOutputStream are us ed for serialization & deserialization. Serializing Objects How to Write to an ObjectOutputStream FileOutputStream out = new FileOutputStream("theTime"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeobject("today"); s.writeobject(new Date()); s.flush();

75 How to Read from an ObjectOutputStream FileInputStream in = new FileInputStream("theTime"); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Date)s.readObject(); String Handling In Java, a string is a sequence of characters. many other languages that implement strings as character arrays, Java implements strings as objects of type String. once a String object has been created, you cannot change the characters that comprise that string.(immutable) StringBuffer and StringBuilder classes are used to create mutable strings that can be modified after they are created. Note: The contents of the String instance cannot be changed after it has been created. However, a variable declared as a String reference can be changed to point at some other String object at any time. The String Constructors The String class supports several constructors. 1.To create an empty string, you call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]) Here is an example: char chars[] = 'a', 'b', 'c' ; String s = new String(chars); This constructor initializes s with the string abc. 2.You can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startindex, int numchars) Here, startindex specifies the index at which the subrange begins, and numchars specifies the number of characters to use. Here is an example: char chars[] = 'a', 'b', 'c', 'd', 'e', 'f' ;

76 String s = new String(chars, 2, 3); This initializes s with the characters cde. 3.You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strobj) Here, strobj is a String object. Consider this example: // Construct one String from another. class MakeString public static void main(string args[]) char c[] = 'J', 'a', 'v', 'a'; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); String Concatenation The + operator, which concatenates two strings, producing a String object as the result. String age = "9"; String s = "He is " + age + " years old."; string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. tostring() it is the means by which you can determine the string representation for objects of classes that you create. String tostring( ) To implement tostring( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class. // Override tostring() for Box class. class Box double width; double height; double depth; Box(double w, double h, double d) width = w; height = h; depth = d; public String tostring()

77 return "Dimensions are " + width + " by " + depth + " by " + height + "."; class tostringdemo public static void main(string args[]) Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); The output of this program is shown here: Dimensions are 10.0 by 14.0 by 12.0 Box b: Dimensions are 10.0 by 14.0 by 12.0 As you can see, Box s tostring( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ). String Methods: Method Description Example int length( ) char charat (int index) char[ ] tochararray( ) int compareto(string anotherstring) int comparetoignorecase(string str) returns the number of characters in the string Returns the character at the specified index convert all the characters in a String object into a character array Compares two strings lexicographically Compares two strings lexicographically, ignoring case differences String s = chars ; System.out.println(s.length()); char ch = "abc".charat(1); String s = "This is a demo method."; char carr[]=new char[s.length()]; carr=s.tochararray(); String s1= welcome ; Sring s2= morning ; int c=s1.compareto(s2); if c value is -1then s1 <s2

78 String concat (String str) boolean equals(object str) boolean equalsignorecase(string str) int indexof(int ch) int indexof(int ch, int startindex) int lastindexof(int ch) int lastindexof(int ch, int startindex) String substring(int startindex) Concatenates the specified string to the end of this string Compares this string to the specified object Compares this string to the specified string object and ignores case differences Searches for the first occurrence of a character or substring. Searches for the last occurrence of a character or substring. Extracts a substring in a given string >=1 then s1>s2 =0 then s1 and s2 are equal String s1= welcome ; String s2= Hi ; s1.cconcat(s1); String s1 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; s1.equals(s3); s1.equalsignorecase(s4); String s = "Now is the time for all good people "; System.out.println("indexOf(t) = " +s.indexof('t')); System.out.println("indexOf(the) = " +s.indexof("the")); System.out.println("indexOf(t, 10) = " +s.indexof('t', 10)); String s = "Now is the time for all good people "; System.out.println("indexOf(t) = " +s. lastindexof ('t')); System.out.println("indexOf(the) = " +s. lastindexof ("the")); System.out.println("indexOf(t, 10) = " +s. lastindexof ('t', 10)); String org = "This is a test ; String result = org.substring(11);

79 String substring(int startindex, int endindex) String replace(char original, char replacement) String tolowercase( ) String touppercase( ) replaces all occurrences of one character in the invoking string with another character converts all the characters in a string from uppercase to lowercase converts all the characters in a string from lowercase to uppercase String s = "Hello".replace('l', 'w'); String s = "This is a test."; String upper = s.touppercase(); String lower = s.tolowercase(); StringBuffer Class StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer sb = new StringBuffer("Hello"); The important methods are: append( ):The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object insert( ):The insert( ) method inserts one string into another. StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); reverse( ): reverse the characters within a StringBuffer object. StringBuffer s = new StringBuffer("abcdef"); s.reverse(); delete( ) and deletecharat( ): delete characters within a StringBuffer object. StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); replace( ): replace one set of characters with another set inside a StringBuffer object StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); //To reverse a string

80 import java.io.*; class GFG public static void main (String[] args) StringBuffer s=new StringBuffer("GeeksGeeks"); s.reverse(); System.out.println(s); //returns skeegrofskeeg Utility Classes java.util has classes that generate pseudorandom numbers, manage date and time, observe events, manipulate sets of bits, tokenize strings, and handle formatted data. The java.util package also contains one of Java s most powerful subsystems: The Collections Framework. List of classes in java.util:

81 Scanner class Scanner reads formatted input and converts it into its binary form. Added by JDK5. Collections group multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. With help of Scanner, it is now easy to read all types of numeric values, strings, and other types of data, whether it comes from a disk file, the keyboard, or another source. The Scanner Constructors A Scanner can be created for a String, an InputStream, a File, or any object that implements the Readable or ReadableByteChannel interfaces. Syntax: Scanner(InputStream from) ; Creates a Scanner that uses the stream specified by from as a source for input. In general, to use Scanner, follow this procedure: 1. Determine if a specific type of input is available by calling one of Scanner s hasnextx methods, where X is the type of data desired. 2. If input is available, read it by calling one of Scanner s nextx methods. 3. Repeat the process until input is exhausted.

82

83 import java.util.*; class AvgNums public static void main(string args[]) Scanner sc = new Scanner(System.in); int c=sc.nextint(); //to read integer value double d=sc.nextdouble(); //to read doublevalue String st=sc.nextline(); //to read string Collections: Unlike Arrays where the size is fixed, Collections allow addition, removal of their elements.

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method Unit 3 INFORMATION HIDING & REUSABILITY -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method Inheritance Inheritance is one of the cornerstones of objectoriented programming

More information

Keyword this. Can be used by any object to refer to itself in any class method Typically used to

Keyword this. Can be used by any object to refer to itself in any class method Typically used to Keyword this Can be used by any object to refer to itself in any class method Typically used to Avoid variable name collisions Pass the receiver as an argument Chain constructors Keyword this Keyword this

More information

Mobile Application Development ( IT 100 ) Assignment - I

Mobile Application Development ( IT 100 ) Assignment - I 1. a) Explain various control structures available in Java. (6M ) Various control structures available in Java language are: 1. if else 2. switch 3. while 4. do while 5. for 6. break 7. continue 8. return

More information

Java Lecture Note. Prepared By:

Java Lecture Note. Prepared By: Java Lecture Note Prepared By: Milan Vachhani Lecturer, MCA Department, B. H. Gardi College of Engineering and Technology, Rajkot M 9898626213 milan.vachhani@yahoo.com http://milanvachhani.wordpress.com

More information

JAVA. Lab-9 : Inheritance

JAVA. Lab-9 : Inheritance JAVA Prof. Navrati Saxena TA- Rochak Sachan Lab-9 : Inheritance Chapter Outline: 2 Inheritance Basic: Introduction Member Access and Inheritance Using super Creating a Multilevel Hierarchy Method Overriding

More information

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must

More information

Hierarchical abstractions & Concept of Inheritance:

Hierarchical abstractions & Concept of Inheritance: UNIT-II Inheritance Inheritance hierarchies- super and subclasses- member access rules- super keyword- preventing inheritance: final classes and methods- the object class and its methods Polymorphism dynamic

More information

ANNAMACHARYA INSTITUTE OF TECHNOLOGY AND SCIENCES: : TIRUPATI

ANNAMACHARYA INSTITUTE OF TECHNOLOGY AND SCIENCES: : TIRUPATI ANNAMACHARYA INSTITUTE OF TECHNOLOGY AND SCIENCES: : TIRUPATI Venkatapuram(Village),Renigunta(Mandal),Tirupati,Chitoor District, Andhra Pradesh-517520. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING NAME

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

BoxDemo1.java jueves, 02 de diciembre de :31

BoxDemo1.java jueves, 02 de diciembre de :31 BoxDemo1.java jueves, 0 de diciembre de 0 13:31 1 package boxdemo1; 3 class Box { 4 double width; 5 double height; 6 double depth; 7 } 8 9 // This class declares an object of type Box. class BoxDemo1 {

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

By: Abhishek Khare (SVIM - INDORE M.P)

By: Abhishek Khare (SVIM - INDORE M.P) By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-I The Java Environment, Basics, Object Oriented Programming in Java, Inheritance The Java Environment: History

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3 Class A class is a template that specifies the attributes and behavior of things or objects. A class is a blueprint or prototype from which objects are created. A class is the implementation of an abstract

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Lecture 1: Overview of Java

Lecture 1: Overview of Java Lecture 1: Overview of Java What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Special Topics: Programming Languages

Special Topics: Programming Languages Lecture #23 0 V22.0490.001 Special Topics: Programming Languages B. Mishra New York University. Lecture # 23 Lecture #23 1 Slide 1 Java: History Spring 1990 April 1991: Naughton, Gosling and Sheridan (

More information

Java Professional Certificate Day 1- Bridge Session

Java Professional Certificate Day 1- Bridge Session Java Professional Certificate Day 1- Bridge Session 1 Java - An Introduction Basic Features and Concepts Java - The new programming language from Sun Microsystems Java -Allows anyone to publish a web page

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. Unit-2 Inheritance: Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The general form of a class declaration that inherits a super class is

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA

Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA WEB PROGRAMMING DEPARTMENT OF MCA Class II MCA Semester III Batch & Year B4 & 2012 Staff A.SALEEM RAJA, MCA.,M.Phil.,M.Tech Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 1 UNIT III JAVA FUNDAMENTALS Java

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp... 1 of 8 8/27/2014 2:15 PM Units: Teacher: ProgIIIAPCompSci, CORE Course: ProgIIIAPCompSci Year: 2012-13 Computer Systems This unit provides an introduction to the field of computer science, and covers the

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Roll Number. Common to II Year B.E.CSE & EIE INTERNAL ASSESSMENT TEST - I. Credit 3 R-2017

Roll Number. Common to II Year B.E.CSE & EIE INTERNAL ASSESSMENT TEST - I. Credit 3 R-2017 Roll Number ERODE SENGTHAR ENGINEERING COLLEGE PERDURI, ERODE 638 057 (Accredited by NBA, Accredited by NAAC with A grade, Accredited by IE (I), Kolkotta, Permanently affiliated to Anna University, Chennai

More information

INHERITANCE Inheritance Basics extends extends

INHERITANCE Inheritance Basics extends extends INHERITANCE Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that

More information

UNIT I. control- this reference- overloading methods and constructors-recursion-garbage collection- building stringsexploring

UNIT I. control- this reference- overloading methods and constructors-recursion-garbage collection- building stringsexploring JAVA PROGRAMMING 1 UNIT I OOP concepts- Data abstraction- encapsulationinheritance- benefits of inheritance- polymorphism-classes and objects- procedural and object oriented programming paradigm. Java

More information

Programming Language (2) Lecture (4) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University

Programming Language (2) Lecture (4) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University Programming Language (2) Lecture (4) Supervisor Ebtsam AbdelHakam ebtsamabd@gmail.com Department of Computer Science Najran University Overloading Methods Method overloading is to define two or more methods

More information

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing Unit 3 INFORMATION HIDING & REUSABILITY Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing Interfaces interfaces Using the keyword interface, you can fully abstract

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC. hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Objectives You will learn: Java features. Java and its associated components. Features of a Java application and applet. Java data types. Java

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Introducing Classes A class defines a new data type (User defined data type). This

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Learning the Java Language. 2.1 Object-Oriented Programming

Learning the Java Language. 2.1 Object-Oriented Programming Learning the Java Language 2.1 Object-Oriented Programming What is an Object? Real world is composed by different kind of objects: buildings, men, women, dogs, cars, etc. Each object has its own states

More information

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java What is Java? Chapter 1 Introduction to Java Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows,

More information

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Sung Hee Park Department of Mathematics and Computer Science Virginia State University September 18, 2012 The Object-Oriented Paradigm

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples: Unit IV Pointers and Polymorphism in C++ Concepts of Pointer: A pointer is a variable that holds a memory address of another variable where a value lives. A pointer is declared using the * operator before

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl... Page 1 of 13 Units: - All - Teacher: ProgIIIJavaI, CORE Course: ProgIIIJavaI Year: 2012-13 Intro to Java How is data stored by a computer system? What does a compiler do? What are the advantages of using

More information

Seminar report Java Submitted in partial fulfillment of the requirement for the award of degree Of CSE

Seminar report Java Submitted in partial fulfillment of the requirement for the award of degree Of CSE A Seminar report On Java Submitted in partial fulfillment of the requirement for the award of degree Of CSE SUBMITTED TO: www.studymafia.org SUBMITTED BY: www.studymafia.org 1 Acknowledgement I would like

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. Object and Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Communication Objects are the basic runtime entities in

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING Unit I : OVERVIEW PART A (2 Marks) 1. Give some characteristics of procedure-oriented

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information