Array is collection of homogenous Data items. Array is classified into three types.

Size: px
Start display at page:

Download "Array is collection of homogenous Data items. Array is classified into three types."

Transcription

1 UNIT 2 1

2 ARRAY 2

3 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 Y X 3

4 Multidimensional Arrays Z X 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; 4

5 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; 5

6 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; 6

7 System.out.println("Sorted list:"); for(int i = 0;i < n;i++) System.out.println(" " + number[i]); System.out.println(" "); 7

8 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]; OR int[ ][ ] table = 0,0,0,1,1,1; 8

9 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]); System.out.println(" "); 9

10 Variable Size Arrays Array Variable Size array is called Array of Array or Nested Array or Jagged Ex: int [ ] [ ] x = new int [3] [ ]; //Three rows array x [0] = new int [2] x [1] = new int [4] x [2] = new int [3] //First Rows has two elements //Second Rows has four elements //Third Rows has three elements x[0] x[1] x[0] [1] x[1] [3] x[2] x[2] [2] 10

11 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; 11

12 System.out.println(""); 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"); System.out.println(""); 12

13 CLASS FUNDAMENTALS 13

14 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) // body of method //... type methodnamen(parameter-list) // body of method 14

15 // 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); 15

16 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.

17 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(); 17

18 // 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(); 18

19 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; 19

20 // 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(); System.out.println("Volume is " + vol); 20

21 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; 21

22 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(); System.out.println("Volume is " + vol); 22

23 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; 23

24 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(); System.out.println("Volume is " + vol); 24

25 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; 25

26 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(); System.out.println("Volume is " + vol); 26

27 The this Keyword 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 27 this is called garbage collection.

28 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 28

29 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; 29

30 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); 30

31 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 31

32 // 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; 32

33 // 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); 33

34 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)); 34

35 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); 35

36 ACCESS CONTROL Access Specifier private Accessing Level Same Class in Same Package private protected friendly (not a keyword protected public 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; Sub Class in Same Package Non Sub Class in Same Package Sub Class in Other Package Other Class in Other Package 36

37 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()); 37

38 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. 38

39 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); 39

40 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. 40

41 // 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(); 41

42 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 42

43 INHERITANCE 43

44 INHERITANCE 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. 44

45 Inheritance achieved in two different forms 1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class Example: We can now create objects of classes A and B independently. A a; B b; //a is object of A //b is object of B 45

46 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 46

47 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; B b; // a is contained in b 47

48 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 48

49 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 49

50 2. Multilevel Inheritance (Derived from a Derived Class) A B 4. Hierarchical Inheritance (One Super class, Many Subclasses) C A B C D 50

51 Single Inheritance (Only one Super Class and One Only Sub Class) //Single Inheritance 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)); 51

52 class MainRoom public static void main(string [] args) HallRoom hr = new HallRoom(); hr.room_area(); hr.hallroom_volume(); 52

53 Multilevel Inheritance (Derived from a Derived Class) //Multilevel Inheritance 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)); 53

54 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(); 54

55 Hierarchical Inheritance (One Super Class, Many Subclasses) //Hierarchical Inheritance 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)); 55

56 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(); 56

57 INHERITANCE WITH super KEYWORD 57

58 The purpose of the super keyword: 1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods 1. 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. 58

59 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)); 59

60 class MainRoom public static void main(string [] args) HallRoom hr =new HallRoom(10,20,30); hr.room_area(); hr.hallroom_volume(); 60

61 //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)); 61

62 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(); 62

63 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(); 63

64 Inheritance with Method Overriding 64

65 1. Method overriding in java means a subclass method overriding a super class method. 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. 65

66 //Method Overriding class Room void Room_Super() System.out.println("The Room Base is Displayed"); class HallRoom extends Room void Room_Super() 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(); 66

67 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 void Room_Super() 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(); 67

68 Inheritance with Abstract Class 68

69 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. 69

70 //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( ); 70

71 Inheritance with final Keyword 71

72 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); 72

73 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(); 73

74 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 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(); 74

75 STRING COMPARISON 1. 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. Syntax: 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. 75

76 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)); 76

77 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) 77

78 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); 78

79 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); 79

80 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 80 means that s1 and s2 do not refer to the same objects.

81 5. compareto() Syntax: int compareto(string str); Value Less than zero Greater than zero Zero Meaning The invoking string is less than str. The invoking string greater than str. The two strings are equal. 81

82 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 Second String"); 82

83 1. substring() MODIFYING A STRING 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); 83

84 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); 84

85 3. replace() 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); 85

86 StringBuffer Functions 1. 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) 86

87 (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. 1. 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. 87

88 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()); 88

89 3. setlength() setlength(). Syntax: To set the length of the buffer within a StringBuffer object, use 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); 89

90 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(). Syntax: 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. 90

91 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)); 91

92 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); 92

93 6. append() 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) + "."); 93

94 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) + "."); 94

95 7. insert() 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); 95

96 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); 96

97 8. reverse() reversed(). Syntax: You can reverse the character within s StringBuffer object using StringBuffer reverse() class String_Operation public static void main(string args[]) StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); 97

98 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); 98

99 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); 99

100 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); System.out.println("The Substring is: " + sb); 100

Lab 14 & 15: String Handling

Lab 14 & 15: String Handling Lab 14 & 15: String Handling Prof. Navrati Saxena TA: Rochak Sachan String Handling 9/11/2012 22 String Handling Java implements strings as objects of type String. Once a String object has been created,

More information

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Internal Examination 1 Answer Key DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Branch & Sec : CSE Date : 08.08.2014 Semester : V Sem Max Marks : 50 Marks Sub Code& Title : CS2305 Programming Paradigms

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

Topics to be covered

Topics to be covered UNIT - II Topics to be covered Arrays Strings Packages Java-Doc comments Inheritance Class hierarchy Polymorphism Dynamic Binding final keyword abstract classes Arrays Arrays: An array is a collection

More information

TEST (MODULE:- 1 and 2)

TEST (MODULE:- 1 and 2) TEST (MODULE:- 1 and 2) What are command line arguments? Write a program in JAVA to print Fibonacci series using command line arguments? [10] Create a class employee with data members empid, empname, designation

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

UNIT - II Object Oriented Programming - Inheritance

UNIT - II Object Oriented Programming - Inheritance UNIT - II Object Oriented Programming - Inheritance Topics to be Covered: 1. Inheritance 2. Class Hierarchy 3. Polymorphism 4. Dynamic Binding 5. Final Keyword 6. Abstract Classes 7. Object Class 8. Reflection

More information

String. Other languages that implement strings as character arrays

String. Other languages that implement strings as character arrays 1. length() 2. tostring() 3. charat() 4. getchars() 5. getbytes() 6. tochararray() 7. equals() 8. equalsignorecase() 9. regionmatches() 10. startswith() 11. endswith() 12. compareto() 13. indexof() 14.

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

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O UNIT - V Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O 1 INHERITANCE 2 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit

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

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

2. All the strings gets collected in a special memory are for Strings called  String constant pool. Basics about Strings in Java 1. You can create Strings in various ways:- a) By Creating a String Object String s=new String("abcdef"); b) By just creating object and then referring to string String a=new

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

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

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

This document can be downloaded from with most recent updates.

This document can be downloaded from   with most recent updates. This document can be downloaded from www.chetanahegde.in with most recent updates. 1 MODULE 3 Syllabus: Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference Variables,

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

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

import java.io.*; class OutputExample { public static void main(string[] args) { try{ PrintWriter pw = new PrintWriter

import java.io.*; class OutputExample { public static void main(string[] args) { try{ PrintWriter pw = new PrintWriter class OutputExample try PrintWriter pw = new PrintWriter (new BufferedWriter(new FileWriter("test1.txt"))); pw.println("outputexample pw.close() catch(ioexception e) System.out.println(" class InputExample

More information

1SFWJFX FYDMVTJWF FYDFSQUT GSPN CSBOE OFX BOE GPSUIDPNJOH 0SBDMF 1SFTT +BWB +%, CPPLT

1SFWJFX FYDMVTJWF FYDFSQUT GSPN CSBOE OFX BOE GPSUIDPNJOH 0SBDMF 1SFTT +BWB +%, CPPLT TM 1SFWJFX FYDMVTJWF FYDFSQUT GSPN CSBOE OFX BOE GPSUIDPNJOH 0SBDMF 1SFTT +BWB +%, CPPLT 'FBUVSJOH BO JOUSPEVDUJPO CZ CFTUTFMMJOH QSPHSBNNJOH BVUIPS )FSC 4DIJMEU 8SJUUFO CZ MFBEJOH +BWB FYQFSUT 0SBDMF

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

Selected Questions from by Nageshwara Rao

Selected Questions from  by Nageshwara Rao Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)

More information

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class Chapter 6 Inheritance Extending a Class Introduction; Need for Inheritance; Different form of Inheritance; Derived and Base Classes; Inheritance and Access control; Multiple Inheritance Revisited; Multilevel

More information

ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC JAVA PROGRAMMING

ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC JAVA PROGRAMMING ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC 2010 080230021-JAVA PROGRAMMING 1. What are the Java Features? 1. Compiled and Interpreted 2. Platform Independent and

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

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

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Example program for FORM VALIDATION

Example program for FORM VALIDATION Example program for FORM VALIDATION function validate() var name = document.forms["regform"]["name"]; var email = document.forms["regform"]["email"]; var phone = document.forms["regform"]["telephone"];

More information

ECS-503 Object Oriented Techniques

ECS-503 Object Oriented Techniques UNIT-4 Part-2 ECS-503 Object Oriented Techniques CHAPTER 16 String Handling Java implements strings as objects of type String. Implementing strings as built-in objects allows Java to provide a full complement

More information

STRINGS AND STRINGBUILDERS. Spring 2019

STRINGS AND STRINGBUILDERS. Spring 2019 STRINGS AND STRINGBUILDERS Spring 2019 STRING BASICS In Java, a string is an object. Three important pre-built classes used in string processing: the String class used to create and store immutable strings

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

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

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

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015 More on Strings Lecture 10 CGS 3416 Fall 2015 October 13, 2015 What we know so far In Java, a string is an object. The String class is used to create and store immutable strings. Some String class methods

More information

String related classes

String related classes Java Strings String related classes Java provides three String related classes java.lang package String class: Storing and processing Strings but Strings created using the String class cannot be modified

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

TEXT-BASED APPLICATIONS

TEXT-BASED APPLICATIONS Objectives 9 TEXT-BASED APPLICATIONS Write a program that uses command-line arguments and system properties Write a program that reads from standard input Write a program that can create, read, and write

More information

Class Library java.lang Package. Bok, Jong Soon

Class Library java.lang Package. Bok, Jong Soon Class Library java.lang Package Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr Object class Is the root of the class hierarchy. Every class has Object as a superclass. If no inheritance is specified

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Creating Strings. String Length

Creating Strings. String Length Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE

POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE COURSE NAME: OBJECT ORIENTED PROGRAMMING COURSE CODE: OOP521S NQF LEVEL: 6 DATE: NOVEMBER 2015 DURATION: 2 HOURS

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

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the

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

Building Strings and Exploring String Class:

Building Strings and Exploring String Class: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Lecture Notes K.Yellaswamy Assistant Professor CMR College of Engineering & Technology Building Strings and Exploring

More information

Programming with Java

Programming with Java Programming with Java String & Making Decision Lecture 05 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives By the end of this lecture you should be able to : Understand another

More information

2. Introducing Classes

2. Introducing Classes 1 2. Introducing Classes Class is a basis of OOP languages. It is a logical construct which defines shape and nature of an object. Entire Java is built upon classes. 2.1 Class Fundamentals Class can be

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Lecture Notes K.Yellaswamy Assistant Professor K L University

Lecture Notes K.Yellaswamy Assistant Professor K L University Lecture Notes K.Yellaswamy Assistant Professor K L University Building Strings and Exploring String Class: -------------------------------------------- The String class ------------------- String: A String

More information

Prashanth Kumar K(Head-Dept of Computers)

Prashanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-III 1 1. Define Array. (Mar 2010) Write short notes on Arrays with an example program in Java. (Oct 2011) An array

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

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

STUDENT LESSON A10 The String Class

STUDENT LESSON A10 The String Class STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of

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

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

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Prasanth Kumar K(Head-Dept of Computers)

Prasanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-II 1 1. Define operator. Explain the various operators in Java. (Mar 2010) (Oct 2011) Java supports a rich set of

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

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE

INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE 1 NUMBERS PROGRAM FOR SUM OF SERIES USING 2 MATHPOWER METHOD 3 PROGRAM ON COMMAND LINE ARGUMENT 4 PROGRAM TO PRINT FIBONACI

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

المملكة العربية السعودية وزارة التعليم العالى

المملكة العربية السعودية وزارة التعليم العالى KINGDOM OF SAUDI ARABIA MINISTRY OF HIGHER EDUCATION JAZAN UNIVERSITY COLLEGE OF COMPUTER SCIENCE & INFORMATION SYSTEMS FINAL EXAMINATION QUESTION PAPER(Answer Key) Term: ( Fall / Spring) Academic Year:

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

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

public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); }

public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println(The age is  + age); } Question No :1 What is the correct ordering for the import, class and package declarations when found in a Java class? 1. package, import, class 2. class, import, package 3. import, package, class 4. package,

More information

Class. Chapter 6: Data Abstraction. Example. Class

Class. Chapter 6: Data Abstraction. Example. Class Chapter 6: Data Abstraction In Java, there are three types of data values primitives arrays objects actually, arrays are a special type of object Class In Java, objects are used to represent data values

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

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

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Top-down programming design

Top-down programming design 1 Top-down programming design Top-down design is a programming style, the mainstay of traditional procedural languages, in which design begins by specifying complex pieces and then dividing them into successively

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

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

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

10 COMPUTER PROGRAMMING

10 COMPUTER PROGRAMMING 10 COMPUTER PROGRAMMING CLASS AND OBJECT CONTENTS GENERAL STRUCTURE OF THE CLASS DECLARATION OF THE CLASS OBJECT CREATION MEMBER VARIABLE, HOW TO ACCESS MEMBER VARIABLE CONSTRUCTOR KEYWORD METHOD 2 GENERAL

More information

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CS212 Midterm. 1. Read the following code fragments and answer the questions. CS1 Midterm 1. Read the following code fragments and answer the questions. (a) public void displayabsx(int x) { if (x > 0) { System.out.println(x); return; else { System.out.println(-x); return; System.out.println("Done");

More information

Object-Oriented Programming

Object-Oriented Programming Data structures Object-Oriented Programming Outline Primitive data types String Math class Array Container classes Readings: HFJ: Ch. 13, 6. GT: Ch. 13, 6. Đại học Công nghệ - ĐHQG HN Data structures 2

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

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

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

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

More information

Object Oriented Programming(OOP).

Object Oriented Programming(OOP). Object Oriented Programming(OOP). OOP terminology: Class : A class is a way to bind data and its associated function together. It allows the data to be hidden. class Crectangle Data members length; breadth;

More information

The Decaf Language. 1 Lexical considerations

The Decaf Language. 1 Lexical considerations The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

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

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

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 In Previous Lecture We

More information