Download presentation
Presentation is loading. Please wait.
Published byΖένια Καλάρης Modified over 5 years ago
1
■ Simple ■ Secure ■ Portable ■ Object-oriented ■ Robust
The Java Buzzwords or Java Features or Java Characteristics ■ Simple ■ Secure ■ Portable ■ Object-oriented ■ Robust ■ Multithreaded ■ Interpreted ■ High performance ■ Distributed ■ Dynamic 1
2
What is Java? 1. It is a Pure Object Oriented Programming language. 2. Independent platform language. 3. Java a really simple, reliable, portable, and powerful language. 4. The new language Java on C and C++ but removed a number of features of C and C++. A Simple Java Program class Sample { public static void main(String args[ ]) System.out.println(“Java is Better than C and C++); }
3
JAVA COMPILATION PROCESS
Java Source Code Java Compiler Java Byte Code (Java Class File) Java Interpreter Java Machine Code JAVA VIRTUAL MACHIN (JVM) The Java Compiler is converting from Source code into the Byte code. But java compiler is not executable code. Rather, it is byte code. Bytecode is highly optimized set of instructions designed to be executed by the Java run – time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode.
4
Java Tokens Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements. A Java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are: 1. Reserved Keywords 2. Identifiers 3. Literals 4. Operators 5. Separators Reserved Keywords Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords. Java keywords, combined with operators and separators according to a syntax, form definition of the Java language.
6
Identifiers Identifiers are programmer – designed tokens. They are used for nameing classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not begin with a digit. 3. Uppercase and Lowercase letters are distinct. 4. They can be of any length. Names of all public methods and instance variables start with a leading lowercase letter. Example: average sum When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. dayTemperature firstDayofMonth totalMarks
7
All private and local variables use only lowercase letters combined with underscores
Example: length batch_strength All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter). Student HelloJava Vehicle MototCycle Variables that represent constant values use all uppercase letters and underscores between words. TOTAL F_MAX PRINCIPAL_AMOUNT
8
Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals Operators An operator is a symbol that takes one or more arguments and operates on them to produce a result. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise operators Special operators
9
Separators Separators are symbols used to indicate where groups of code are divide and arranged. They basically define the shape and function of our code. Name What it is used for paraentheses() Method definitions and invocation braces { } Automatically initialized arrays brackets [ ] declare array types semicolon ; Used to separate statements comma , Used to separate variable declaration period Used to separate package name
10
Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals
11
Single Character Literals
Java Literals Character Literals Boolean Literals Numeric Literals Integer Literals Real Single Character Literals String Integer Literals An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Literals Ex: Valid Ex: ,000 $ Invalid Hexadecimal integer Literals Ex: 0X2 0X9F 0Xbcd 0x 11
12
are all valid real literals.
Integer literals are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like Such numbers are called real (or floating point) numbers. Further examples of real literals are: These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, are all valid real literals. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points literals are: 12
13
Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, may be written as 7.5E9 or 75E8. Similarly, , equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 13
14
There are two Boolean literal values: . true . false
Boolean Literals There are two Boolean literal values: . true . false Single Character Literals A single-character literal (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Literals A string literal is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 14
15
Backslash Character Literal
Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 15
16
1. They must not begin with a digit.
VARIABLE A variable is an identifier that denotes a storage location used to store a data value. Unlike constant that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values ca be stored in the variable. A variable name can be chosen by the programmer in a meaningful way so as to reflect what represents in the program. Some examples of variable names are: average height totaCheight classStrength As mentioned earlier, variable names may consist of alphabets, digits and the underscore ( - ), subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length. 16
17
CONSTANTS Constants in Java refer to fixed values that do not change during the execution of a program. Java supports several types of constants:
18
Single Character Constants
Java Constants Character Constants Boolean Constants Numeric Constants Integer Constants Real Single Character Constants String Integer Constants An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Constants Ex: Valid Ex: ,000 $ Invalid Hexadecimal integer Constants Ex: 0X2 0X9F 0Xbcd 0x 18
19
are all valid real constants.
Integer Constants are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like Such numbers are called real (or floating point) numbers. Further examples of real Constants are: These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, are all valid real constants. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points constants are: 19
20
Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, may be written as 7.5E9 or 75E8. Similarly, , equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 20
21
There are two Boolean constant values: . true . false
Single Character Constant A single-character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Constant A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 21
22
Backslash Character Constant
Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 22
23
DATA TYPES Every variable in java has a data type. Data types specify the size and type of values that can be stored. Java language is rich in its data types. The variety of data types available allow the programmer to select the type appropriate to the needs of the applications. DATA TYPES IN JAVA Premitive (Intrinsic) Non – Primitive ( Derived Classes Arrays Numeric Non -Numeric Interface Integer Floating - Point Character Boolean
24
Integer Types Type Size Minimum Size Maximum Size byte One byte -128
short int long Type Size Minimum Size Maximum Size byte One byte -128 127 short Two byte -32,768 32, 767 int Four byte -2, 147, 483, 648 2, 147, 483, 647 long Eight byte -9, 223, 372, 036, 854, 775, 808
25
Floating Point Types Type Size Minimum Size Maximum Size Float 4 bytes
Double Type Size Minimum Size Maximum Size Float 4 bytes 3.4e – 038 3.4e + 038 Double 8 bytes 1.7e – 308 1.7e + 308
26
Character Type In order to store character constants in memory. Java provides a character data type called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single character Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a boolean type can take: true or false. Remember, both these words have been declared as keywords. Boolean type is denoted by the keyword boolean and uses only one bit of storage.
27
Arithmetic Operations
TYPE CONVERSION Type Conversion Casting Operations Arithmetic Operations Explicit Conversion Implicit Conversion Convert a data of one type to another before it is used in arithmetic operations or to store a value of one type into a variable of another type. Example: byte b1 = 50; byte b2 = 60; byte b3 = b1 + b2; Error: “cannot implicitly covert type int to type byte” int b3 = b1 + b2; // No Error In C#, type conversions take place in two ways 1. Implicit conversions 2. Explicit conversions 27
28
Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1;
Implicit Conversions The conversion can always be performed without any loss of data. For numeric types, this implies that the destination type can fully represent the range of the source type. For example, a short can be converted implicitly to an int, because the short range is a subset of the int range. Therefore, short b = 75; int a = b; C# does the conversion automatically. An implicit conversion is also known as automatic type conversion. The process of assigning a smaller type to a larger one is known as widening or promotion. Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1; int x3 = x2; long x4 = x3; float x5 = x4; decimal x6 = x4; 28
29
Conversion hierarchy chart
8 – bit types byte 16 – bit types short char 32 – bit types int long 64 – bit types float double 29
30
type variable1 = (type) variable2
Explicit Conversions The process of assigning a larger type to a smaller one is known as norrowing. The norrowing may result in loss of information. There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the compiler will give an error message. For example, the following conversions cannot be made implicitly: int to short int to long long to int float to int decimal to any numeric type any numeric type to char However, we can explicitly carry out such conversions using the ‘cast’ operator. The process is known as casting and is done as follows: type variable1 = (type) variable2 30
31
Automatic Type Promotion in Expressions
Example: int m = 50; byte n = (byte) m; long x = 1234L; int y = (int) x; float f = 50.0F long y = (long) f; Automatic Type Promotion in Expressions In addition to assignments, there is another place where certain type conversions may occur: in expressions. To see why, consider the following. In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand. For example, examine the following expression: byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte or short operand to int when evaluating an expression. This means that the subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte. As useful as the automatic promotions are, they can cause confusing compile-time errors. For example, this seemingly correct code causes a problem: b = b * 2; // Error! Cannot assign an int to a byte! 31
32
The Type Promotion Rules
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value being assigned would still fit in the target type. In cases where you understand the consequences of overflow, you should use an explicit cast, such as byte b = 50; b = (byte)(b * 2); which yields the correct value of 100. The Type Promotion Rules In addition to the elevation of bytes and shorts to int, Java defines several type promotion rules that apply to expressions. They are as follows. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double. The following program demonstrates how each value in the expression gets promoted to match the second argument to each binary operator:
33
class Promote { public static void main(String args[]) byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); }
34
OPERATORS 34
35
Subtraction or Unary Minus
C# supports a rich set of operators. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise logical operators Special operators ARITHMETIC OPERATORS Integer Arithmetic a % b equivalent to a – ( a / b ) * b -14 % 3 = -2 -14 % -3 = -2 -14 % -3 = 2 Real Arithmetic Mixed – Mode Arithmetic Ex: / 10.0 produces the result 1.5 15 / 10 produces the result 1 Operator Meaning + Addition or Unary plus - Subtraction or Unary Minus * Multiplication / Division % Modulo Division 35
36
Is greater than or equal to
RELATIONAL OPERATOR LOGICAL OPERATOR Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to Operator Meaning && Logical AND || Logical OR ! Logical NOT BITWISE LOGICAL OPERATOR C# supports operators that may be used for manipulation of data at bit level. These operators may be used for testing the bits or shifting them to the right or left. Bitwise operators may not be applied to floating – point data. Operator Meaning & Bitwise Logical AND | Bitwise Logical OR ^ Bitwise Logical XOR ~ One’s Complement << Left Shift >> Right Shift 36
37
Bitwise Complement ( ~ )
Variable Value Binary Pattern X 23 ~X 132 Y FF ~Y 00 Shift Operations Left Shift Variable Value Binary Pattern X (8 bits) X << 3 the bit pattern of X value is left shifted by thrice. The Resultant bit pattern will be 37
38
Variable Value Binary Pattern Y 41 0 0 1 0 1 0 0 1
Right Shift Variable Value Binary Pattern Y Y>>3 the bit pattern of the Y value is right shifted by thrice. The Resultant bit pattern will be Bitwise Logical AND Bitwise Logical OR Bitwise Exclusive OR Variable Value Binary Pattern X 5 Y 2 X & Y A 6 B 3 A & B Variable Value Binary Pattern X 5 Y 2 X | Y 7 A 6 B 1 A & B Variable Value Binary Pattern X 5 Y 2 X ^ Y 7 A 6 B 3 A ^ B 38
39
op - is the binary operator v op= exp is equivalent to v = v op(exp);
Assignment Operator Assignment operators are used to assign the value of an expression to a variable. C# has a set of ‘shorthand’ assignment operators which are used in the form v op= exp v - is the variable exp - is the expression op - is the binary operator v op= exp is equivalent to v = v op(exp); Ex: x + = y + 1; is equivalent to x = x + (y +1) Advantages: . What appears on the left – hand side need not be repeated and therefore it becomes easier to write. . The statement is more concise and easier to read. . The use of shorthand operators results in a more efficient code. 39
40
Increment and Decrement Operator The operators are ++ and - -
++ means Increment Operator - - means Decrement Operator The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the following form: ++m; or m++ --m or m— ++m; is equivalent to m = m + 1 (or m + = 1;) --m; is equivalent t o m = m – 1 (or m - = 1;) We use the increment and decrement operators extensively in for and while loops For Example: Case 1 m = 5; y = ++m; The statement a [ i ++ ] = 10; is equivalent to a [ i ] = 10; i = i + 1; Case 2 m = 5; y = m--; 40
41
Special Operators Conditional Operator
It is also known as Ternary operator Syntax: exp_1? exp_2: exp_3 Special Operators Instanceof Operator The instanceof is an object reference operator and returns true if the object on the left – hand side is an instance of the class given on the right – hand side. This operator allows us to determine whether the object belongs to a particular class or not. Example: person instanceof student Dot Operator The dot operator (.) is used to access the instance variables and methods of class objects. person1.age //Reference to the variable age person1.salary( ) //Reference to the method salary( ) 41
42
DECISION MAKING – BRANCHING and LOOPING
42
43
Decision making with IF statement 1. Simple if statement
2. if… else statement 3. Nested if…else statement 4. else if ladder Simple if statement if (Boolean-expression) { Statement-block } Statement – x if…else statement if (Boolean-expression) { True-block statement(s) } else Flase-block statement(s) Statement-x; 43
44
Nesting if…else statement if (Boolean-expression) {
True-block statement(S) True-block Statement(s) } else False-block Statement(s) False-block statement(s) 44
45
Default-Statement-x;
else if Ladder if (condition_1) Statement_1; else if (condition_2) Statement_2; else if (condition_3) Statement_3; . else if (condition_n) Statement_n; else Default-Statement-x; 45
46
THE SWITCH STATEMENT switch (expression) { case value_1: block_1;
break; case value_2: block_2; case value_3: block_3; default: default_block } Statement_x; 46
47
DECISION MAKING AND LOOPING
The C# language provides for four constructs for performing loop operations. They are: The while statement The do statement The for statement The do statement Syntax: initialization do { Body of the Loop } while (test_condition); The while statement Syntax: initialization; while(test_condition) { Body of the Loop } The for statement Syntax: for (initialization;test_condition;increment) { Body of the Loop } 47
48
Case 6: for (j = 1000; j>0; j = j – 1); Case 7:
Additional Features of the for Loop Case 1: p = 1; for (n = 0; n<17;++n) can be rewritten as for (p=1,n=0;n<17;++n) Case 2: for (n=1,m=50;n<=m; n=n+1,m=m-1) { } Case 3: sum = 0; for ( i =1, i<20 && sum <100; i++) Case 4: for (x = (m+n)/2; x>0;x = x/2) Case 5: m = 5; for (;m != 100;) System.out.println(m); m = m + 5; Case 6: for (j = 1000; j>0; j = j – 1); Case 7: for (j = 1000;j>0; j= j-1); 48
49
Jumps in Loops break; continue; goto; class Gobreakcontinue {
public static void main(String args[ ] ) for (int i = 1;i< 100;i++) System.out.println( “ “); if (i >= 10) Break; for(int j = 1;j<100;j++) System.out.println(“ * “); if (j == i) goto loop1; } loop: continue; System.out.println(“Termination by BREAK”); 49
50
ARRAY 50
51
3. Multi Dimensional Array
Array is collection of homogenous Data items. Array is classified into three types. 1. One Dimensional Array 2. Two Dimensional Array 3. Multi Dimensional Array One Dimensional Array Two Dimensional Arrays X Y 51
52
Multidimensional Arrays
X Z Creating an Array 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. 1. Declaration of Arrays Syntax: type [ ] arrayname; Example: int [ ] counter; float [ ] marks; int [ ] x,y; 52
53
2. Creating memory locations Syntax: arrayname = new type [size];
Examples: number = new int [5]; average = new float [10]; 3. Declaration and Creation in one step Syntax: type [ ] arrayname = new type [size]; Examples: int [ ] number = new int [5]; 4. Initialization of Arrays Syntax: type [ ] arrayname = {list of values}; Example: int [ ] number = {32,45,34,56,34}; int [ ] number = new int [3] {10,20,30}; 53
54
class NumberSorting { public static void main(String args[]) int number[] = {55,40,80,65,71}; int n = number.length; System.out.println("Given List"); for(int i = 0;i<n;i++) System.out.println(" " + number[i]); } System.out.print("\n"); for(int i = 0;i < n; i++) for(j = 1;j < n; j++) if (number[i] < number [j]) int temp = number[i]; number[i] = numbdf[j]; number[j] = temp;
55
System.out.println("Sorted list:");
for(int i = 0;i < n;i++) { System.out.println(" " + number[i]); } System.out.println(" ");
56
Two Dimensional Array Case:
It is possible to assign an array object to another. Ex: int [ ] a = {1,2,3}; int [ ] b; b = a; Two Dimensional Array Declaration for the Two Dimensional Array int [ ][ ] myArray; myArray = new int[3,4]; OR int [ ][ ] myArray = new int[3,4]; int[ ][ ] table = {{0,0,0},{1,1,1}}; 56
57
class MultiTable { final static int ROWS = 20; final static int COLUMNS = 20; public static void main(String args[]) int product[][] = new int[ROWS][COLUMNS]; int row,column; System.out.println("Multiplication Table"); System.out.println(" "); int i,j; for(i=10;i<ROWS;i++) for(j=10;j<COLUMNS;j++) product[i][j] = i * j; System.out.println(" " + product[i][j]); }
58
int [ ] [ ] x = new int [3] [ ]; //Three rows array
Variable – Size Arrays Variable – Size array is called Array of Array or Nested Array or Jagged Array Ex: int [ ] [ ] x = new int [3] [ ]; //Three rows array x [0] = new int [2] //First Rows has two elements x [1] = new int [4] //Second Rows has four elements x [2] = new int [3] //Third Rows has three elements x[0] x[1] x[2] x[0] [1] x[1] [3] x[2] [2] 58
59
public static void main(String args[ ])
public class MyArrayc2 { public static void main(String args[ ]) BufferedReader br = new BufferedRead(new InputStreamReader(System.in)) int [ ][ ]arr=new int[4][ ]; arr[0]=new int[3]; arr[1]=new int[2]; arr[2]=new int[5]; arr[3]=new int[4]; System.out.println("Enter the numbers for Jagged Array"); for(int i=0 ; i < arr.Length ; i++) for(int x=0 ; x < arr[i].Length ; x++) String st= br.readLine(); int num=Integer.parseInt(st); arr[i][x]=num; } 59
60
System.out.println("Printing the Elemnts");
for(i=0 ; i < arr.Length ; i++) { for(y=0 ; y < arr[i].Length ; y++) System.out.println(arr[x][y]); System.out.println("\0"); } 60
61
CLASS FUNDAMENTALS
63
The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its data. A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) // body of method } type methodname2(parameter-list) type methodnameN(parameter-list)
64
// APPLICATION OF CLASSES AND OBJECTS
using System; class Rectangle { public int length, width; public void GetData(int x,int y) length = x; width = y; } public int RectArea () int area = length * width; return (area); class RectArea public static void Main() int area1,area2; Rectangle rect1 = new Rectangle (); Rectangle rect2 = new Rectangle (); rect1.length = 15; rect1.width = 10; area1 = rect1.length * rect1.width ; rect2.GetData (20,10); area2 = rect2.RectArea (); System.out.println("Area1 = " + area1); System.out.println("Area2 = " + area2);
65
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does? Box b1 = new Box(); Box b2 = b1; You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. This situation is depicted here: Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2. For example: Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.
66
ADDING METHODS class Box { double width; double height; double depth;
// display volume of a box void volume() System.out.print("Volume is "); System.out.println(width * height * depth); } class BoxDemo3 public static void main(String args[] Box mybox1 = new Box(); Box mybox2 = new Box();
67
// assign values to mybox1's instance variables
mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); }
68
Returning a Value class Box { double width; double height;
double depth; // compute and return volume double volume() return width * height * depth; } class BoxDemo4 public static void main(String args[]) Box mybox1 = new Box(); Box mybox2 = new Box(); double vol;
69
// assign values to mybox1's instance variables
mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }
70
Adding a Method That Takes Parameters
class Box { double width; double height; double depth; // compute and return volume double volume() return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) width = w; height = h; depth = d;
71
class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize 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(); }
72
Constructors class Box { double width; double height; double depth;
// This is the constructor for Box. Box() System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() return width * height * depth;
73
class BoxDemo6 { 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(); }
74
Parameterized Constructors
class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) width = w; height = h; depth = d; } // compute and return volume double volume() return width * height * depth;
75
class BoxDemo7 { public static void main(String args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }
76
The this Keyword Garbage Collection
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted. To better understand what this refers to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } Garbage Collection Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.
77
The finalize( ) Method The constructor method is used to initialize an object when it is declared. This process is known as initalisation. Similarly, Java supports a concept called finalization, which is just opposite to initialization. We know that java run – time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non – object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free resources we must use a finaliser method. This is similar to destructor in C++. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here }
78
Overloading Methods 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;
79
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); System.out.println("Result of ob.test(123.25): " + result); }
80
Overloading Constructors
class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box
81
// constructor used when cube is created
Box(double len) { width = height = depth = len; } // compute and return volume double volume() return width * height * depth; class OverloadCons public static void main(String args[]) // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol;
82
// get volume of first box
vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); }
83
Using Objects as Parameters
// Objects may be passed to methods. class Test { int a, b; Test(int i, int j) a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) if(o.a == a && o.b == b) return true; else return false; class PassOb public static void main(String args[]) Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3));
84
Returning Objects // Returning an object. class Test { int a;
Test(int i) a = i; } Test incrByTen() Test temp = new Test(a+10); return temp; class RetOb public static void main(String args[]) Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: “ + ob2.a);
85
Access Specifier Accessing Level
ACCESS CONTROL Access Specifier Accessing Level private Same Class in Same Package private protected Sub Class in Same Package friendly (not a keyword Non – Sub Class in Same Package protected Sub Class in Other Package public Other Class in Other Package 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; } }
86
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! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); }
87
Understanding static There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a 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. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. 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.
88
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);
89
Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.
90
// Demonstrate an inner class.
class Outer { int outer_x = 100; void test() Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner void display() System.out.println("display: outer_x = " + outer_x); class InnerClassDemo public static void main(String args[]) Outer outer = new Outer(); outer.test(); } }
91
Using Command-Line Arguments
Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy—they are stored as strings in the String array passed to main( ). For example, the following program displays all of the command-line arguments that it is called with: // Display all command-line arguments. class CommandLine { public static void main(String args[]) for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } Try executing this program, as shown here: java CommandLine this is a test When you do, you will see the following output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1
92
II – UNIT Inheritance Inheritance with Super Keyword
Inheritance with Method Overriding Inheritance with Abstract Class Inheritance with Final Keyword Interfaces Packages String Functions StringBuffer Functions
93
INHERITANCE
94
INHERITANCE A B What is Inheritance?
Inheritance is the mechanism which allows a class B to inherit properties/characteristics- attributes and methods of a class A. We say “B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class.
95
Inheritance achieved in two different forms
1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class
96
In Such cases, we say that the object b is a type of a
In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as ‘is – a’ relationship Example 1. Dog is – a type of animal 2. Manager is – a type of employee 3. Ford is – a type of car Animal Horse Dog Lion
97
Containment Inheritance
We can also define another form of inheritance relationship known as containership between class A and B. Example: class A { } class B A a; // a is contained in b B b;
98
In such cases, we say that the object a is contained in the object b
In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as ‘has – a’ relationship. The outer class B which contains the inner class A is termed the ‘parent’ class and the contained class A is termed a ‘child’ class. Example: 1. car has – a radio. 2. House has – a store room. 3. City has – a road. Car object Radio object
99
1. Single Inheritance (Only one Super Class and One Only Sub Class)
Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B
100
2. Multilevel Inheritance (Derived from a Derived Class)
B C 4. Hierarchical Inheritance (One Super class, Many Subclasses) A B C D
101
Single Inheritance (Only one Super Class and One Only Sub Class)
class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Valoume of the HallRoom is:" + (length * breadth * height));
102
class MainRoom { public static void main(String [] args) HallRoom hr = new HallRoom(); hr.Room_Area(); hr.HallRoom_Volume(); }
103
Multilevel Inheritance (Derived from a Derived Class)
class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));
104
class BedRoom extends HallRoom
{ int height_1; BedRoom() length = 10; breadth = 20; height = 30; height_1 = 40; } void BedRoom_Volume1() System.out.println("The Volume of the the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume1();
105
Hierarchical Inheritance (One Super Class, Many Subclasses)
class Room { protected int length, breadth, height; Room() length = 10; breadth = 20; height = 30; } class HallRoom extends Room void HallRoom_Area() System.out.println("The Area of the HallRoom is:" + (length * breadth));
106
class BedRoom extends Room
{ void BedRoom_Volume() System.out.println("The Volume of the BedRoom is:" + (length * breadth * height)); } class MainRoom public static void main(String [] args) HallRoom hr =new HallRoom(); BedRoom br = new BedRoom(); hr.HallRoom_Area(); br.BedRoom_Volume();
107
INHERITANCE WITH super KEYWORD
108
The purpose of the ‘super’ keyword:
1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods Using super to Call Superclass Constructor A Subclass can call a constructor method defined by its superclass by use of the following form of super: super (parameter – list) Here, parameter – list specifies any parameter needed by the constructor in the superclass, super() must always be the first statement executed inside a subclass constructor. Restriction of the Subclass constructor 1. super may only be used within a subclass constructor method. 2. The call to superclass constructor must appear as the first statement within the subclass constructor 3. The parameters in the super call must match the order and type of the instance variable declared in the superclass.
109
class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));
110
class MainRoom { public static void main(String [] args) HallRoom hr =new HallRoom(10,20,30); hr.Room_Area(); hr.HallRoom_Volume(); }
111
//super keyword in Multilevel Inheritance
class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));
112
class BedRoom extends HallRoom
{ int height_1; BedRoom(int length, int breath, int height, int height_1) super(length,breath,height); this.height_1 = height_1; } void BedRoom_Volume_1() System.out.println("The Volume 1 of the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br =new BedRoom(10,20,30,40); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume_1();
113
2. Using super to Call Superclass Method
//super keyword call Super Class Methods class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room void HallRoom_Intermetiate() System.out.println("The Hall Room is Displayed"); class BedRoom extends HallRoom void BedRoom_Sub() super.Room_Super(); super.HallRoom_Intermetiate(); System.out.println("The Bed Room is Displayed"); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.BedRoom_Sub(); } }
114
Inheritance with Method Overriding
115
1. Method overriding in java means a subclass method overriding a super
2. Superclass method should be non-static. 3. Subclass uses extends keyword to extend the super class. 4. In the example class B is the sub class and class A is the super class. 5. In overriding methods of both subclass and superclass possess same signatures. 6. Overriding is used in modifying the methods of the super class. 7. In overriding return types and constructor parameters of methods should match.
116
//Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super();
117
Super Keyword in Method Overriding
If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). //Super keyword in Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); super.Room_Super(); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super();
118
Inheritance with Abstract Class
119
abstract type name (parameter – list)
Abstract Class You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super class . Thus, a subclass must override them – it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract type name (parameter – list) Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in from of the class keyword at the beginning of the class declaration. Conditions for the Abstract Class 1. We cannot use abstract classes to instantiate objects directly. For example. Shape s = new Shape(); is illegal because shape is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods.
120
//Abstract Class Implementation
abstract class A { abstract void callme( ); // Abstract Method void callmetoo( ) // Concrete Method System.out.println("This is a Concrete method"); } class B extends A void callme( ) //Redefined for the Abstract Method System.out.println("B's Implementation of Callme"); class MainRoom public static void main(String [] args) B b = new B( ); b.callme( ); b.callmetoo( ); } }
121
Inheritance with final Keyword
122
What is the purpose of final keyword?
1. Can’t initialize to variable again and again (Equivalent to Constant) 2. Can’t Method Overriding 3. Can’t Inherited 1. Can’t initialize to variable again and again (Equivalent to Constant) class Final { public static void main(String args[]) final int a = 45; a = 78; //cannot assign the value to final Variable System.out.println("The A Value is:" + a); }
123
2. Can’t Method Overriding
class Super { final void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //Super method in sub cannot override Super_Method() in super; Overridden //method is final void Super_Method() System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();
124
3. Can’t Inherited final class Super { void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //cannot inherit from final super System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();
125
Interface
126
Why are you using Interface?
1. Java does not support multiple inheritances. That is, classes in java cannot have more than one superclass. For instances, 2. a is not permitted in Java. However, the designers of java could not overlook the importance of multiple inheritances. 3. A large number of real life applications require the use of multiple inheritances whereby we inherit methods and properties from several distinct classes. 4. Since C++ like implementation of multiple inheritances proves difficult and adds complexity to the language, Java provides an alternate approach known as interfaces to support the concept of multiple inheritances. 5. Although a java class cannot be a subclass or more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritances. class A extends B extends C { }
127
Defining Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Syntax: interface Interface_name { Variable declaration; Method declaration; } Ex: interface Item { static final int code = 1001; static final String name = “CCET”; void display (); } Ex: interface Area { final static float pi = 3.142F; float compute (float x,float y); void show(); }
128
How to Interface implements to the Classes
Syntax: class class_name implements interface_name { //Member of the Classes //Definition of the Interfaces } Ex: interface student { int slno = 12345; String name = "CCET"; void print_details(); } class Inter_Def implements student void print_details() System.out.println("The Serial Number is:" + slno); System.out.println("The Student name is:" + name);
129
Abstract classes Interfaces
Difference between Abstract Classes and Interfaces Abstract classes Interfaces Abstract classes are used only when there is a “is-a” type of relationship between the classes. Interfaces can be implemented by classes that are not related to one another. You cannot extend more than one abstract class. You can implement more than one interface. it contains both abstract methods and non Abstract Methods Interface contains all abstract methods Abstract class can implemented some methods also. Interfaces can not implement methods. With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.
130
Difference between Classes and Interfaces
Interface is little bit like a class... but interface is lack in instance variables....that's can't create object for it. Interfaces are developed to support multiple inheritances. 3. The methods present in interfaces are pure abstract. 4. 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 6. In Class the variable declaration as well as initialization, but interface only for initializing.
131
Types of Interfaces A B C A B C D E A B C Interface Implementation
Class Extension A B C D E Class Extension Interface Implementation A B C Interface Implementation Class
132
A B C D Interface Implementation Class Extension
133
// HIERARICHICAL INHERITANCE USING INTERFACE interface Area {
final static float pi = 3.14F; float compute (float x,float y); } class Rectangle implements Area public float compute(float x,float y) return (x * y); class Circle implements Area return (pi * x * x); A B C Interface Implementation Class
134
class InterfaceTest { public static void main(String args[]) Rectangle rect = new Rectangle (); Circle cir = new Circle(); Area area; //Interface object area = rect; System.out.println("Area of Rectangle = " + area.compute(10,20)); area = cir; System.out.println("Area of Circle = " + area.compute(10,0)); }
135
D //HYBRID INHERITANCE USING INTERFACES class Student {
int rollnumber; void getnumber(int n) rollnumber = n; } void putnumber() System.out.println("Roll No: " + rollnumber); class Test extends Student float part1, part2; void getmarks(float m1,float m2) part1 = m1; part2 = m2; void putmarks() System.out.println("Marks obtained"); System.out.println("Part1 = " + part1); System.out.println("Part2 = " + part2); A B C Interface Implementation Class Extension D
136
interface Sports { float sportwt = 6.0F; void putwt(); } class Results extends Test implements Sports float total; public void putwt() System.out.println("Sports Wt = " + sportwt); void display() total = part1 + part2 + sportwt; putnumber(); putmarks(); putwt(); System.out.println("Total Score = " + total);
137
class Hybrid { public static void main(String args[]) Results stud = new Results(); stud.getnumber(1234); stud.getmarks(27.5F, 33.0F); stud.display(); }
138
What is Partial Implementation?
The Interface is implementation to the Abstract class is called Partial Implementation. Example: interface Partial_Interface { public void display_one(); } abstract class Abstract_Class implements Partial_Interface public void display_one() //Definition for the Interface Method System.out.println("This is Interface Method"); void display_two() //Concrete Method System.out.println("This is Concrete Method"); abstract void display_three(); //Abstract Method
139
class Pure_Class extends Abstract_Class
{ void display_three() //Definition for the Abstract Method System.out.println("This is Abstract Method"); } class Final public static void main(String args[]) Pure_Class pc = new Pure_Class(); pc.display_one(); pc.display_two(); pc.display_three();
140
Package
141
What is Packages? Packages are java’s way of grouping a variety of classes and / or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “containers” for classes. What are the benefits of Packages? 1. The classes contained in the packages of other programs can be easily reused. 2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred by their fully qualified name, comprising the package name and class name. 3. Packaged provide a way to “hide classes thus preventing other programs or package from accessing classes that are meant for internal use only. 4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decide their relationships, and then we can implement the java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.
142
Java packages are therefore classified into two types.
Types of Packages Java packages are therefore classified into two types. 1. Pre – defined packages (Java API Packages) 2. User – defined packages Java API Packages Package Name Contents java.lang Language support classes. These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions java.util Language utility classes such as vectors, hash tables, random numbers, date, etc. java.io Input / Output support classes. They provide facilities for the input and output of data. java.awt Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on. java.net Classes for networking. They include classes for communicating with local computers as well as with internet servers. java.applet Classes for creating and implementing applets.
143
2. USER DEFINED PACKAGES How to Creating our own Packages
Creating our own package involves the following steps: 1. Declare the package at the beginning of a file using the form package package_name; 2. Define the class that is to be put in the package and declare it public 3. Create a subdirectory under the directory where the main source files are stored. 4. Store the listing as the classname.java file in the subdirectory created. 5. Compile the file. This creates .class file in the subdirectory. 6. The subdirectory name must match the package name exactly. Note: Java also supports the concept of package hierarchy. This done by specifying multiple names in a package statement, separated by dots. Example: package firstPackage.secondpackage;
144
Example: Create Package: package package1; public class ClassA { public void displayA() System.out.println("Class A"); } How to import the package: import package1.ClassA; class PackageTest1 { public static void main(String args[]) ClassA objectA = new ClassA() objectA.displayA(); }
145
ACCESS PROTECTION Access Modifier Access Location Public Protected
friendly (default) private protected private Same Class Yes Subclass in same package No Other classes in same package Subclass in other package Non – subclasses in other packages
146
Example program for the above Access Protection Tabular
Protection.java: package p1; public class Protection { int n = 1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4; public Protection() System.out.println("base constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }
147
This is file Derived.java:
package p1; class Derived extends Protection { Derived() System.out.println("derived constructor"); System.out.println("n = " + n); //System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same class //in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }
148
This is file SamePackage.java:
package p1; class SamePackage { SamePackage() Protection p = new Protection(); System.out.println("same package constructor"); System.out.println("n = " + p.n); //System.out.println("n_pri = " + p.n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); }
149
This is file OtherPackage.java:
package p2; class Protection2 extends p1.Protection { Protection2() System.out.println("derived other package constructor"); // System.out.println("n = " + n); //Cannot Access because //accessing level is non – sub //class same class // System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }
150
This is file OtherPackage.java:
package p2; class OtherPackage { OtherPackage() p1.Protection p = new p1.Protection(); System.out.println("other package constructor"); // System.out.println("n = " + p.n); // Cannot access because the // accessing level is non – sub // class in same package // System.out.println("n_pri = " + p.n_pri); // Cannot access // because the accessing // level is same class in // same package // System.out.println("n_pro = " + p.n_pro); // Cannot access // because the accessing // level is sub – class in // other package System.out.println("n_pub = " + p.n_pub); }
151
String functions
152
SPECIAL STRING OPERATIONS
1. Automatic creation of new String instances from string literals. 2. Concatenation of multiple String object by used of the + operators 3. Conversion of other data types to a string representation. String Literals class String_Operation { public static void main(String args[]) char chars [ ] = {'a', 'b', 'c'}; String s1 = new String(chars); String s2 = "Chettinad"; //Use String Literals, Java automatically //constructs a String object System.out.println("The Displayed String_1 is:" + s1); System.out.println("The Displayed String_2 is:" + s2); System.out.println("The Length of the String is: " + "Chettinad".length()); }
153
2. String Concatenation class String_Operation { public static void main(String args[]) String age = " 9 "; String s = "He is" + age + "Years old."; //Java does not allow ( // )operators to be // applied to String // objects. System.out.println(s); }
154
3. String Concatenation with Other Data Types
class String_Operation { public static void main(String args[]) int age = 9; String s1 = "He is " + age + " Years old. "; // The int value in age is // automatically // converted into its string // representation within a //String object. System.out.println(s1); String s2 = "four: " ; System.out.println(s2); String s3 = "four: " + (2 + 2); System.out.println(s3); }
155
4. String Conversion and toString()
To implement toString(), simply return a String object that contains the human readable string. class Box { double width; double height; double depth; Box(double w,double h,double d) width = w; height = h; depth = d; } public String toString() return "Dimensions are " + width + " by " + depth + " by " + height + ".";
156
class String_Operation
{ 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); System.out.println(s); }
157
CHARACTER EXTRACTION The String class provides a number of ways in which characters can be extracted form a String object. That is Character Extraction. charAt() Syntax: char charAt(int where) class String_Operation { public static void main(String args[ ]) char ch; ch = "Chettinad".charAt(4); System.out.println("The 4 Character is:" + ch); }
158
2. getChars() If you need to extract more than one character at a time, you can use the getChars() method. Syntax: void getChars(int sourceStart,int sourceEnd,char target [ ],int targetStart) class String_Operation { public static void main(String args[]) String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf [ ] = new char[end - start]; s.getChars(start,end,buf,0); System.out.println(buf); }
159
3. getBytes() There is an alternative to getChars() that stores the character in an array of bytes. This method is called getBytes(), and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form: byte [] getBytes(); Other forms of getBytes are also available. getBytes is most useful when you are exporting a String value into an environment that does not support 16 - bit unicode character. For example, most Internet protocols and text file formats use 8 - bit ASCII for all text interchage. class String_Operation { public static void main(String args[]) String msg="HelloWorld"; byte b[ ]=msg.getBytes(); System.out.println("The Character in array of Bytes is: " + b); }
160
4. toCharArray() If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray(). It returns an array of characters for the entire string. It has this general form: char [ ] toCharArray() This function is provided as a convenience, since it is possible to use getChars() to achieve the same result. class String_Operation { public static void main(String args[]) String str = "einstein relativity concept is still a concept of great discussion"; char heram[ ] = str.toCharArray(); System.out.print("Converted value from String to char array is: "); System.out.println(heram); }
161
STRING COMPARISON equals() and equalsIgnoreCase()
To compare two strings for equality, use equals() Syntax: boolean equals(Object str) Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case - sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase(). When it compares two string, it considers A - Z to be the same as a - z. boolean equalsIgnoreCase(String str) Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise.
162
class String_Operation
{ public static void main(String args[]) String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good - Bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " s1.equalsIgnoreCase(s4)); }
163
2. regionMatches() The regionMatches() method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisions Syntax: boolean regionMatches(int startIndex,String str2,int str2StartIndex,int numChars) boolean regionMatches(boolena ignorCase,int startIndex,String str2,int strStrartIndex,int numChars)
164
class String_Operation
{ public static void main(String args[]) String str1 = new String("Java is a wonderful language"); String str2 = new String("It is an object-oriented language"); boolean result = str1.regionMatches(20, str2, 25, 0); System.out.println(result); } class String_Operation { public static void main(String args[]) String str1 = new String("Java is a wonderful language"); String str2 = new String("It is an object-oriented language"); boolean result = str1.regionMatches(true, 20, str2, 25, 0); System.out.println(result); }
165
3. startsWith() and endsWith()
The startsWith() method determines whether a given String begins with a specified string. The endsWith() method determines whether the String in questions ends with a specified string. Syntax: boolean startsWith(String str) boolean endsWith(String str) str is the String object being tested. If the string matches, true is returned. Otherwise false is returned class String_Operation { public static void main(String args[]) boolean a, b; a = "Chettinad".startsWith("Chi"); b = "Chettinad".endsWith("nad"); System.out.println("The Start of the String is: " + a); System.out.println("The Ends of the String is:" + b); }
166
4. equals() Versus == The equals function and == operator are perform two different operations The equals() method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. class String_Operation { public static void main(String args[]) String s1 = "Hello1234"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } The Contents of the two String objects are identical, but they are distinct object, This means that s1 and s2 do not refer to the same objects.
167
5. compareTo() Syntax: int compareTo(String str); Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string greater than str. Zero The two strings are equal.
168
class String_Operation
{ public static void main(String args[]) String s1 = "Chettinad"; String s2 = "Chettinad"; int n = s1.compareTo(s2); if (n==0) System.out.println("The Two String are Equal"); else if(n>0) System.out.println("The First Strings is Greater than the Second String"); else if(n<0) System.out.println("The First String is Smaller than the }
169
MODIFYING A STRING substring() substring() has tow forms.
1. String substring(int startIndex) 2. String substring(int startIndex,int endIndex) class String_Operation { public static void main(String args[ ]) String s1 = "This is a test. This is, too."; String s2 = s1.substring(5); String s3 = s1.substring(5,8); System.out.println("The Sub String of S2 is: " + s2); System.out.println("The Sub String of S3 is: " + s3); }
170
2. concat() You can concatenate two strings using concat() Syntax: String concat(String str); class String_Operation { public static void main(String args[ ]) String s1 = "One"; String s2 = s1.concat(" Two"); System.out.println("The Concatenation of Two String is: " + s2); }
171
String replace(char original, char replacement)
The replace() method replaces all occurences of one character in the invoking string with another character. Syntax: String replace(char original, char replacement) class String_Operation { public static void main(String args[ ]) String s = "Hello".replace('l','w'); System.out.println("The Replacement of the String is:" + s); } 4. trim() The trim() method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. Syntax: String trim() class String_Operation { public static void main(String args[ ]) String s = " Hello world ".trim(); System.out.println("The Removable Whitspace of the String is: " + s); }
172
StringBuffer Functions
StringBuffer is a peer class of String that provides much of the functionality of strings. 2. String Buffer represents growable and writeable character sequences. 3. String Buffer may have characters and substrings inserted in the middle or appended to the end. 4. String Buffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. StringBuffer Constructors StringBuffer defined these three constructors: 1. StringBuffer() 2. StringBuffer(int size) 3. StringBuffer(String str)
173
(1) The default constructor reserves room for 16 characters without reallocation.
(2) The second version accepts an integer argument that explicitly sets the size of the buffer. (3) The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. length() and capacity() Syntax: int length() int capacity() class String_Operation { public static void main(String args[ ]) StringBuffer sb = new StringBuffer("Hello"); System.out.println("Buffer = " + sb); System.out.println("Length = " + sb.length()); System.out.println("Capacity = " + sb.capacity()); //Its capacity is 21 //because room for 16 additional characters is automatically added. }
174
2. ensureCapacity() 1. If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity() to set the size of the buffer. 2. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer.ensureCapacity() has this general form: void ensureCapacity(int capacity); Here, capacity specifies the size of the buffer. class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("Rose India"); //Returns the current capacity of the String buffer. System.out.println("Buffer : "+sb+"\nCapacity : " + sb.capacity()); //Increases the capacity, as needed, to the specified amount in the //given string buffer object sb.ensureCapacity(27); System.out.println("New Capacity = " + sb.capacity()); }
175
3. setLength() To set the length of the buffer within a StringBuffer object, use setLength(). Syntax: void setLength(int len) Here, len specifies the length of the buffer. This value must be non - negative. when you increase the size of the buffer, null characters are added to the end of the existing buffer. class String_Operation { public static void main(String[ ] args) // Construct a StringBuffer object: StringBuffer s = new StringBuffer("Hello world!"); // Change the length of buffer to 5 characters: s.setLength(5); System.out.println(s); }
176
4. charAt() and setCharAt()
1. The value of a single character can be obtained from a StringBuffer via the charAt() method. Syntax: char charAt(int where) For charAt(), where specifies the index of the character being obtained. 2. You can set the value of a character within a StringBuffer using setCharAt(). void setCharAt(int where,char ch) For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.
177
class String_Operation
{ public static void main(String args[]) StringBuffer sb = new StringBuffer("Hello"); System.out.println("Buffer before = " + sb); System.out.println("charAt (1) before = " + sb.charAt(1)); sb.setCharAt(1,'i'); sb.setLength(2); System.out.println("Buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); }
178
5. getChars() To copy a substring of a StringBuffer into an array, use the getChars() method. Syntax: void getChars(int sourceStart,int sourceEnd,char target[],int targetStart); class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer src = new StringBuffer("To learn JAVA, start with keywords."); // Declare a new char array: char[] dst = new char[2]; // Copy the chars #9 and #10 to dst: src.getChars(9,11,dst,0); // Display dst: System.out.println(dst); }
179
3. Here are a few of its forms: StringBuffer append(String str)
1. The append() method concatenates the string representation of any other type of data ot the end of the invoking StringBuffer object. 2. It has overloaded versions for all the built - in types and for Object. 3. Here are a few of its forms: StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) 4. String.valueOf() is called for each parameter to obtain its string representation. 5. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append(). StringBuff append(String str) public class String_Operation { public static void main(String[] args) // Construct a String object: String s1 = new String("3.14"); // Construct a StringBuffer object: StringBuffer s = new StringBuffer("The ratio is: "); // Append the string and display the buffer: System.out.println(s.append(s1) + "."); }
180
StringBuffer append(int num)
class String_Operation { public static void main(String args[]) String s; int a = 42; StringBuffer sb = new StringBuffer(40); s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); } StringBuffer append(Object obj) /*class String_Operation { public static void main(String[] args) // Declare and initialize an object: Object d = new Double(3.14); // Construct a StringBuffer object: StringBuffer s = new StringBuffer("The ratio is: "); // Append the object and display the buffer: System.out.println(s.append(d) + "."); }
181
1. The insert() method inserts one string into another.
2. It is overloaded to accept values of all the simple types, plus Strings and Objects. 3. Like append(), it calls String.valueOf() to obtain the string representation of the value it is called with. 4. These are a few of its forms: StringBuffer insert(int index,String str) StringBuffer insert(int index,char ch) StringBuffer insert(int index, object obj) Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. StringBuffer insert(int index,String str) class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello !"); // Construct a String object: String s = new String("there"); // Insert the string "s" at offset 6: buf = buf.insert(6,s); // Display the buffer: System.out.println(buf); }
182
StringBuffer insert(int index,char ch)
public class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello #!"); // Insert 'J' at the offset 6: buf = buf.insert(6,'J'); // Display the buffer: System.out.println(buf); } StringBuffer insert(int index, object obj) class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello !"); // Construct an object: Object d = new Double(3.45); // Insert d at the offset 6: buf = buf.insert(6,d); // Display the buffer: System.out.println(buf); } }
183
8. reverse() You can reverse the character within s StringBuffer object using reversed(). Syntax: StringBuffer reverse() class String_Operation { public static void main(String args[]) StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); }
184
9. delete() and deleteCharAt()
StringBuffer the ability to delete characters using the methods delete() and deleteCharAt(). Syntax: StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("This is a Test."); sb.delete(4,7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); }
185
10. replace() It replace one set of character with another set inside a StringBuffer object. StringBuffer replace(int startIndex, int endIndex, String str); class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5,7, "was"); System.out.println("After Replace: " + sb); }
186
11. substring() Syntax: String substring(int startIndex) String substring(int startIndex,int endIndex) class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("Chettinad"); sb.substring(6); System.out.println("The Substring is: " + sb); sb.substring(2,5); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.