Topics to be covered

Size: px
Start display at page:

Download "Topics to be covered"

Transcription

1 UNIT - II

2 Topics to be covered Arrays Strings Packages Java-Doc comments Inheritance Class hierarchy Polymorphism Dynamic Binding final keyword abstract classes

3 Arrays

4 Arrays: An array is a collection of similar type of elements that have contiguous memory locations. An array is a type of variable that can store multiple values. An element on an array is accessed by its index which is non-negative integer. 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 Creating an Array 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. 1. Declaration of Array Syntax: data_type arrayname[ ]; Example: int number[ ]; float [ ] marks;

5 2. Creating memory locations Syntax: Examples: arrayname = new data_type [size]; number = new int [5]; average = new float [10]; 3. Declaration and Creation in one step Syntax: Example: 4. Initialization of Arrays data_type arrayname [ ] = new data_type [size]; int number [ ] = new int [5]; Array initializer is a list of comma- seperated expressions surrounded by curly braces. Array will automatically be created large enough to hold the number of elements you specify in the array initializer. For this no need to use new operator. Syntax: Examples: data_type arrayname [ ] = list of values; int number [ ] = 10, 20,30, 40,50; int number[ ] = new int [3] 10,20,30;

6 One Dimensional Array: A list of like-typed elements. First create an array variable of the desired type. new is a special operator that allocates memory. Assigning values are based on the array variable index ranges from 0 to n-1 The values displayed in the output is also based on index. Example 1: class Arrays public static void main(string args[]) int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[6] = 31; month_days[1] = 28; month_days[7] = 31; month_days[2] = 31; month_days[8] = 30; month_days[3] = 30; month_days[9] = 31; month_days[4] = 31; month_days[10] = 30; month_days[5] = 30; month_days[11] = 31; System.out.println( April has + month_days[3] + days ); O/P: April has 30 days

7 Example 2: class SampleArray public static void main(string args[]) int a[] = new int[10]; System.out.println("Storing the numbers in array"); a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5; a[5] = 6; a[6] = 7; a[7] = 8; a[8] = 9; a[9] = 10; System.out.println("The element at a[5] is : " +a[5]); O/P : Storing the numbers in array The element at a[5] is : 6

8 Example 3: class ArrayFirst1 public static void main(string[] args) int a[] = new int[5]; a[0] = 2; a[1] = 4; a[2] = 6; a[3] = 8; a[4] = 10; for(int i=0;i<=4;i++) System.out.println(a[i]); O/P : Example 4: class ArrayFirst2 public static void main(string[] args) int a[] = new int[5]; a[0] = 2; a[1] = 4; a[2] = 6; a[3] = 8; a[4] = 10; for(int i=0;i<a.length;i++) System.out.println(a[i]); O/P :

9 Example 5: class ArrayFirst3 public static void main(string[] args) int a[] = 10,20,30; for(int i=0;i<3;i++) System.out.println(a[i]); O/P : Example 6: class ArrayFirst4 public static void main(string[] args) O/P : int a[] = 10,20,30; for(int i=0;i<a.length;i++) System.out.println(a[i] + " ");

10 Example 7: class ArraySecond public static void main(string[] args) int a[] = 1,2,3; int b[] = 2,4,6; int c[] = 3,6,9; for(int i=0;i<3;i++) System.out.print(a[i]+ " "); System.out.println(); for(int j=0;j<3;j++) System.out.print(b[j]+ " "); System.out.println(); for(int k=0;k<3;k++) System.out.print(c[k]+ " "); O/P :

11 Example 8: class ArraySecond1 public static void main(string[] args) int a[][] = 2,4,6,1,3,5,1,2,3; for(int i=0;i<3;i++) for (int j=0;j<3;j++) System.out.print(a[i][j]+" "); System.out.println(); O/P :

12 Example 9: class ArrayAddition2 public static void main(string[] args) int a[][] = 1,2,3,4,5,6,1,1,1; int b[][] = 2,4,6,1,3,5,0,0,0; int c[][] = new int[3][3]; for(int i=0;i<3;i++) O/P : for(int j=0;j<3;j++) c[i][j]=a[i][j]+b[i][j]; System.out.println(); System.out.print(c[i][j] + " ");

13 Example 10: class ArrayMul1 public static void main(string args[]) int a[][]=1,2,3,4,5,6; int b[][]=2,4,6,1,3,5; int c[][]=new int[2][3]; for(int i=0;i<2;i++) for(int j=0;j<3;j++) c[i][j]=a[i][j]*b[i][j]; System.out.print(c[i][j]+" "); System.out.println(); O/P:

14 Example 11: import java.io.*; class ArrayUsingBufRead public static void main(string[] arg)throws IOException int a[]=new int[5]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i; for(i=0;i<a.length;i++) a[i]=integer.parseint(br.readline()); System.out.println(); System.out.println("The values in the array are :" ); for(i=0;i<a.length;i++) System.out.println(" "+a[i]); O/P : The values in the array are :

15 Example 12: class NumberSorting public static void main(string args[]) int number[] = 70,20,10,30,10; 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(int j = 0;j < i; j++) if (number[i] < number [j]) int temp = number[i]; number[i] = number[j]; number[j] = temp; System.out.println("Sorted list:"); for(int i = 0;i < n;i++) System.out.println(" " + number[i]); System.out.println(" "); O/P : Given List Sorted list:

16 Example 13: public class CmdLineArgArray public static void main(string arg[]) O/P : int a[]=new int[arg.length]; for(int i=0; i<(arg.length); i++) a[i]=integer.parseint(arg[i]); for(int i=0; i<arg.length; i++) System.out.println(a[i]); E:\Java Programs\Examples\Array>javac CmdLineArgArray.java E:\Java Programs\Examples\Array>java CmdLineArgArray

17 Example 13: public class CmdLineArgArray public static void main(string arg[]) O/P : int a[]=new int[arg.length]; for(int i=0; i<(arg.length); i++) a[i]=integer.parseint(arg[i]); for(int i=0; i<arg.length; i++) System.out.println(a[i]); E:\Java Programs\Examples\Array>javac CmdLineArgArray.java E:\Java Programs\Examples\Array>java CmdLineArgArray

18 The for-each loop: A powerful looping construct that allows repeating for each element in an array without having to confirm with index values. Syntax: for(variable : collection) statement Ex: int a[] = 10,20,30,40,50; for (int b : a) System.out.println(b); Java.util.Arrays: The java.util.arrays class contains a static factory that allows arrays to be viewed as lists. Following are the important points about Arrays: This class contains various methods for manipulating arrays (such as sorting and searching). The methods in this class throw a NullPointerException if the specified array reference is null. Class declaration public class Arrays extends Object

19 Methods static String tostring(type[] a) static type copyof(type[] a, int length) static type copyofrange(type[] a, int start, int end) static void sort(type[] a) static int binarysearch(type[] a, type v) static int binarysearch(type[] a, int start, int end,type v) static void fill(type[] a, type v) static boolean equals(type[] a, type[] b) Usage Returns a string with the elements of a Returns an array of the same type as a, of length, filled with the values of a Returns an array of the same type as a, of length end-start, filled with the values of a Sorts the array Uses the binary search algorithm to search for the value v. If it is found, its index is returned. Otherwise, a negative value r is returned Sets all elements of the array to v Returns true if the arrays have the same length, and if the elements in the corresponding indexes match

20 import java.util.*; Class SDArray public static void main(string args[]) int a[] = new int[5]; int b[] = 4,2,1,6,3; System.out.println( Array Elements in B Before Sorting ); for (int i:b) System.out.println(i); Arrays.sort(b); System.out.println( Array Elements in B After Sorting ); for(int i:b) System.out.println(i); Arrays.fill(a,1); System.out.println( Filled Array Elements in A ); for(int i:a) System.out.println(i); boolean flag = Arrays.equals(a,b); System.out.println( After Checking two Array Elements: + flags); int index = Arrays.binarySearch(b,3); System.out.println( Searched Element Index in B is: +index); System.out.println( Copied Array );

21 Output: a = Arrays.copyOf(b,4); for(int i:b) System.out.println(i); Array Elements in B Before Sorting: Array Elements in B After Sorting: Filled Array Elements in A: After checking two Arrays: false Searched Index element in array B is : 2 Copied Array:

22 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,3]; OR int [ ][ ] myarray = new int[3,3]; OR int[ ][ ] table = 0,0,0,1,1,1;

23 class MultiTable final static int ROWS = 5; final static int COLUMNS = 5; 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=1;i<rows;i++) for(j=1;j<columns;j++) product[i][j] = i * j; System.out.print(" " + product[i][j]); System.out.println(" ");

24 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] 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]

25 public class MyArrayc2 public static void main(string args[ ]) throws IOException BufferedReader br = new BufferedReader(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;

26 System.out.println(""); System.out.println("Printing the Elemnts"); for(int i=0 ; i < arr.length ; i++) for(int y=0 ; y < arr[i].length ; y++) System.out.print(arr[i][y]); System.out.print("\0"); System.out.println("");

27 String in Java

28 String: Java s String type called String, is not a Simple Type, nor is it simply an array of characters. Rather String defines an Object. The String type is used to declare string variable. Java Strings are sequences of Unicode Characters. Use an object of type string as an argument to println(); String str = Welcome to JAVA ; System.out.println(str); Implementing strings as built-in objects allows java to provide a full complement of features that make string handling convenient. Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a String. String object has been created, you cannot change the characters that comprise that string. String Constructors: The String class supports several constructors. To create an empty string call the default constructor. String str = new String(); Initialize the values through array of characters. char ch[] = a, b, c ; String str = new String(ch); o/p: abc 1. Subrange: String(char ch[], int start,int numchar); char ch[] = a, b, c, d, e,f ; String s = new String(ch,2,3); o/p: cde

29 2. String copy: String(String strobj); char ch[] = J, A, V, A ; String s1 = new String(ch); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); O/P: JAVA O/P: JAVA 3. ASCII char: String (byte asciichars[]); String(byte asciichars[], int start, int numchars); byte ascii[] =65,66,67,68,69,70; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii,2,3); System.out.println(s2); O/P: ABCDEF O/P: CDE

30 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. 1. String Literals To find the length of a String Assigning values to the object. Syntax: String obj = value; class Str_Length 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()); System.out.println(" The Length of the String is: " + s2.length());

31 Output E:\Programs\javapgm\RUN>javac Str_Length.java E:\Programs\javapgm\RUN>java Str_Length The Displayed String_1 is:abc The Displayed String_2 is:chettinad The Length of the String is: 11 The Length of the String is: 9

32 2. String in Reverse direction class Str_Reverse public static void main(string args[]) char str[] = 'C','H','E','T','T','I','N','A','D'; String S = new String(str); System.out.println("The String S is " +S); for(int i=s.length()-1;i>=0;i--) System.out.print(str[i]); Output E:\Programs\javapgm\RUN>javac Str_Reverse.java E:\Programs\javapgm\RUN>java Str_Reverse The String S is CHETTINAD DANITTEHC

33 3. String Concatenation class String_Concat public static void main(string args[]) String age = " 9 "; String s = "He is" + age + "Years old."; System.out.println(s); Output E:\Programs\javapgm\RUN>javac String_Concat.java E:\Programs\javapgm\RUN>java String_Concat He is 9 Years old. class String_Concat1 public static void main(string args[]) String str = new String(" Welcome to "); String str1 = new String(" III IT "); System.out.println(str.concat(str1)); Output E:\Programs\javapgm\RUN>javac String_Concat1.java E:\Programs\javapgm\RUN>java String_Concat1 Welcome to III IT

34 String Concatenation with Other Data Types class String_Concat2 public static void main(string args[]) int age = 9; String s1 = "He is " + age + " Years old. "; System.out.println(s1); String s2 = "four: " ; System.out.println(s2); String s3 = "four: " + (2 + 2); System.out.println(s3); Output E:\Programs\javapgm\RUN>javac String_Concat2.java E:\Programs\javapgm\RUN>java String_Concat2 He is 9 Years old. four: 22 four: 4

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

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

37 CHARACTER EXTRACTION The String class provides a number of ways in which characters can be extracted form a String object. That is Character Extraction. 1. charat() Syntax: char charat(int where) class Char_At public static void main(string args[ ]) char ch; ch = "Chettinad".charAt(6); System.out.println("The 6th Character is:" + ch); Output E:\Programs\javapgm\RUN>javac Char_At.java E:\Programs\javapgm\RUN>java Char_At The 6th Character is:n

38 2. getchars() getchars() method. If you need to extract more than one character at a time, you can use the Syntax: void getchars(int sourcestart,int sourceend,char target [ ],int targetstart) class Get_Chars 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); Output E:\Programs\javapgm\RUN>javac Get_Chars.java E:\Programs\javapgm\RUN>java Get_Chars demo

39 3. 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() class Str_ToCharArray public static void main(string args[]) String str = "einstein relativity concept is still a concept of great discussion"; char ch[ ] = str.tochararray(); System.out.println("Converted value from String to char array is: "); System.out.println(ch); Output E:\Programs\javapgm\RUN>javac Str_ToCharArray.java E:\Programs\javapgm\RUN>java Str_ToCharArray Converted value from String to char array is: einstein relativity concept is still a concept of great discussion

40 STRING COMPARISON 1. equals() and equalsignorecase() To compare two strings for equality, use equals() Syntax: boolean equals(string 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.

41 Example - equals class StrEquals public static void main (String args[]) String s1 = new String("WELCOME"); String s2 = new String("welcome"); //if(s1.equals(s2) == true) if(s1.equalsignorecase(s2) == true) System.out.println("\n The two strings are equal"); else System.out.println("\n The two strings are not equal"); Output E:\Programs\javapgm\RUN>javac StrEquals.java E:\Programs\javapgm\RUN>java StrEquals The two strings are equal

42 Example equalsignorecase class StrEquals1 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)); Output E:\Programs\javapgm\RUN>javac StrEquals1.java E:\Programs\javapgm\RUN>java StrEquals1 Hello equals Hello -> true Hello equals Good - Bye -> false Hello equals HELLO -> false Hello equalsignorecase HELLO -> true

43 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 comparisons. Syntax: boolean regionmatches(int str1startindex, String str2, int str2startindex, int numchars) boolean regionmatches(boolean ignorcase, int str1startindex, String int str2startindex, int numchars) str2,

44 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, 8); System.out.println(result); Output: true 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, 8); System.out.println(result); Output : true

45 2. startswith() and endswith() string. The startswith() method determines whether a given String begins with a specified 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

46 class Str_Start_End 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 End of the String is:" + b); Output E:\Programs\javapgm\RUN>javac Str_Start_End.java E:\Programs\javapgm\RUN>java Str_Start_End The Start of the String is: false The End of the String is:true

47 3. 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. Syntax: obj1.equals(obj2); (obj1 == obj2); return type is Boolean. class StrEquals2 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)); Output E:\Programs\javapgm\RUN>javac StrEquals2.java E:\Programs\javapgm\RUN>java StrEquals2 Hello1234 equals Hello1234 -> true Hello1234 == Hello1234 -> false

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

49 class Str_Compare public static void main(string args[]) String s1 = "Chettinad1"; 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"); Output E:\Programs\javapgm\RUN>javac Str_Compare.java E:\Programs\javapgm\RUN>java Str_Compare The Two String are Equal

50 MODIFYING A STRING 1. substring() substring() has two forms. 1. String substring(int startindex) 2. String substring(int startindex,int endindex) class Str_SubString1 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,12); System.out.println("The Sub String of S2 is: " + s2); System.out.println("The Sub String of S3 is: " + s3); Output E:\Programs\javapgm\RUN>javac Str_SubString1.java E:\Programs\javapgm\RUN>java Str_SubString1 The Sub String of S2 is: is a test. This is, too. The Sub String of S3 is: is a te

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

52 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 Str_Replace public static void main(string args[ ]) String s = "Hello".replace('l','w'); System.out.println("The Replacement of the String is:" + s); Output E:\Programs\javapgm\RUN>javac Str_Replace.java E:\Programs\javapgm\RUN>java Str_Replace The Replacement of the String is:hewwo

53 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 Str_Trim public static void main(string args[ ]) String s = " Hello world".trim(); System.out.println("The Removable Whitespace of the String is: " + s); Output E:\Programs\javapgm\RUN>javac Str_Trim.java E:\Programs\javapgm\RUN>java Str_Trim The Removable Whitespace of the String is:hello world

54 5. touppercase() and tolowercase() class Str_Upper_Lower public static void main(string args[]) String str = new String("Welcome to III IT"); System.out.println("\n The Original String is: " +str); String str_upper = str.touppercase(); System.out.println("The Upper Case String is: " +str_upper); String str_lower = str.tolowercase(); System.out.println("The Lower Case String is: " +str_lower); Output E:\Programs\javapgm\RUN>javac Str_Upper_Lower.java E:\Programs\javapgm\RUN>java Str_Upper_Lower The Original String is: Welcome to III IT The Upper Case String is: WELCOME TO III IT The Lower Case String is: welcome to iii it

55 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() - The default constructor reserves room for 16 characters without reallocation. 2. StringBuffer(int size) - The second version accepts an integer argument that explicitly sets the size of the buffer. 3. StringBuffer(String str) - 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.

56 1. length() and capacity() Syntax: int length() int capacity() class Str_Length_Capacity 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. Output E:\Programs\javapgm\RUN>javac Str_Length_Capacity.java E:\Programs\javapgm\RUN>java Str_Length_Capacity Buffer = Hello Length = 5 Capacity = 21

57 2. setlength() Syntax: To set the length of the buffer within a StringBuffer object, use setlength(). 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 Str_SBSetLength public static void main(string[ ] args) // Construct a StringBuffer object: StringBuffer s = new StringBuffer("Hello world!"); s.setlength(7); // Change the length of buffer to 7 characters: System.out.println(s); Output E:\Programs\javapgm\RUN>javac Str_SBSetLength.java E:\Programs\javapgm\RUN>java Str_SBSetLength Hello w

58 3. 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.

59 class Str_SetCharAt1 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)); Output E:\Programs\javapgm\RUN>javac Str_SetCharAt1.java E:\Programs\javapgm\RUN>java Str_SetCharAt1 Buffer before = Hello charat (1) before = e Buffer after = Hi charat(1) after = i

60 class Str_SetCharAt2 public static void main(string args[]) StringBuffer sb = new StringBuffer("Great"); System.out.println("The String is: " + sb); sb.setcharat(1,'o'); sb.setcharat(2,'d'); sb.setlength(3); System.out.println("Now the String is: " +sb); Output E:\Programs\javapgm\RUN>javac Str_SetCharAt2.java E:\Programs\javapgm\RUN>java Str_SetCharAt2 The String is: Great Now the String is: God

61 4. append() 1. The append() method concatenates the string representation of any other type of data to 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().

62 StringBuffer append(string str) public class Str_Append1 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) + "."); Output E:\Programs\javapgm\RUN>javac Str_Append1.java E:\Programs\javapgm\RUN>java Str_Append1 The ratio is: 3.14.

63 StringBuffer append(int num) class Str_Append2 public static void main(string args[]) String s; int a = 42; StringBuffer sb = new StringBuffer(); s = sb.append("a = ").append(a).append("!").tostring(); System.out.println(s); Output E:\Programs\javapgm\RUN>javac Str_Append2.java E:\Programs\javapgm\RUN>java Str_Append2 a = 42!

64 StringBuffer append(object obj) class Str_Append3 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: "); Output // Append the object and display the buffer: System.out.println(s.append(d) + "."); E:\Programs\javapgm\RUN>javac Str_Append3.java E:\Programs\javapgm\RUN>java Str_Append3 The ratio is: 3.14.

65 5. 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.

66 StringBuffer insert(int index,string str) class Str_Insert1 public static void main(string[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello!"); String s = new String("there"); // Construct a String object: buf = buf.insert(6,s); // Insert the string "s" at offset 6: Output System.out.println(buf); // Display the buffer: E:\Programs\javapgm\RUN>javac Str_Insert1.java E:\Programs\javapgm\RUN>java Str_Insert1 Hello there!

67 StringBuffer insert(int index,string str) class Str_Insert4 public static void main(string[] args) StringBuffer str = new StringBuffer(" in need is a in deed"); StringBuffer new_str = new StringBuffer(" FRIEND"); System.out.println("Initially the String is: "+str); str.insert(13,new_str); str.insert(0,new_str); System.out.println("Now the String is: " +str); Output E:\Programs\javapgm\RUN>javac Str_Insert4.java E:\Programs\javapgm\RUN>java Str_Insert4 Initially the String is: in need is a in deed Now the String is: FRIEND in need is a FRIEND in deed

68 StringBuffer insert(int index,char ch) public class Str_Insert2 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); Output E:\Programs\javapgm\RUN>javac Str_Insert2.java E:\Programs\javapgm\RUN>java Str_Insert2 HelloJ #!

69 StringBuffer insert(int index, object obj) class Str_Insert3 public static void main(string[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello!"); Object d = new Double(3.45); // Construct an object: buf = buf.insert(6,d); // Insert d at the offset 6: System.out.println(buf); // Display the buffer: Output E:\Programs\javapgm\RUN>javac Str_Insert3.java E:\Programs\javapgm\RUN>java Str_Insert3 Hello 3.45!

70 6. reverse() Syntax: You can reverse the character within StringBuffer object using reverse(). StringBuffer reverse() class Str_BufReverse public static void main(string args[]) StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); Output E:\Programs\javapgm\RUN>javac Str_BufReverse.java E:\Programs\javapgm\RUN>java Str_BufReverse abcdef fedcba

71 7. 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 Str_BufDelete public static void main(string args[]) StringBuffer sb = new StringBuffer("This is a Test."); sb.delete(0,3); System.out.println("After delete: " + sb); sb.deletecharat(3); System.out.println("After deletecharat: " + sb); Output E:\Programs\javapgm\RUN>javac Str_BufDelete.java E:\Programs\javapgm\RUN>java Str_BufDelete After delete: s is a Test. After deletecharat: s i a Test.

72 8. replace() It replace one set of character with another set inside a StringBuffer object. StringBuffer replace(int startindex, int endindex, String str); class Str_BufReplace public static void main(string args[]) StringBuffer sb = new StringBuffer("This is a test."); System.out.println("Original String: " + sb); sb.replace(5,7, "was"); System.out.println("After Replace: " + sb); sb.replace(2,4, "at"); System.out.println("After Replace: " + sb); Output E:\Programs\javapgm\RUN>javac Str_BufReplace.java E:\Programs\javapgm\RUN>java Str_BufReplace Original String: This is a test. After Replace: This was a test. After Replace: That was a test.

73 9. substring() Syntax: String substring(int startindex) String substring(int startindex,int endindex) class Str_BufSubString public static void main(string args[]) StringBuffer sb = new StringBuffer("Chettinad"); System.out.println("The Original string is: " +sb); String s2=sb.substring(6); System.out.println("The Substring is: " +s2); String s3=sb.substring(2,5); System.out.println("The Substring is: " +s3); Output E:\Programs\javapgm\RUN>javac Str_BufSubString.java E:\Programs\javapgm\RUN>java Str_BufSubString The Original string is: Chettinad The Substring is: nad The Substring is: ett

74 PACKAGES

75 What is Packages? A package is a group of similar types of classes, interfaces and sub-packages. The grouping is usually done according to functionality. In fact, packages act as containers for classes. Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Benefits of Packages 1. The classes contained in the packages 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. Package 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.

76

77 Types of Packages Java packages are therefore classified into two types. 1. Pre defined packages (Java API Packages) 2. User defined packages 1.Java API Packages Package Name java.lang java.util java.io java.awt java.net java.applet Contents 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 Language utility classes such as date, vectors, hash tables, random numbers, etc. Input / Output support classes. They provide facilities for the input and output of data. Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on. Classes for networking. They include classes for communicating with local computers as well as with internet servers. Classes for creating and implementing applets.

78 2. USER DEFINED PACKAGES How to Create 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;

79

80 Example : package pack; public class mypack public static void main(string args[]) System.out.println( Welcome ); How to compile & run: Z:\Programs\javapgm>javac -d. mypack.java Z:\Programs\javapgm>java pack.mypack Welcome Z:\Programs\javapgm> The d specifies the destination where to put the generated class file. The. (dot) represents the current folder.

81 Example: Create Package: How to import the package: package package1; public class ClassA public void displaya() System.out.println("Class A"); import package1.classa; class PackageTest1 public static void main(string args[]) ClassA objecta = new ClassA() objecta.displaya();

82 How to run: Z:\Programs\javapgm>javac -d z:\programs\javapgm z:\programs\javapgm\classa.java Z:\Programs\javapgm>javac PackageTest1.java Z:\Programs\javapgm>java PackageTest1 Class A

83 Example : PACKAGE: package PackageTest; import java.io.*; public class Book int book_no, book_id, book_pages; public Book(int a, int b, int c) book_no=a; book_id=b; book_pages=c; public void bookinfo() System.out.println( The Book No +book_no); System.out.println( The Book Id +book_id); System.out.println( The Book Pages +book_pages);

84 Example 2: PROGRAM: import java.io.*; import PackageTest.Book; public class BookReader public static void main(string[] args) Book b=new Book(10, 15, 90); b.bookinfo(); How to run: Z:\Programs\javapgm>javac -d z:\programs\javapgm z:\programs\javapgm\book.java (or) Z:\Programs\javapgm>javac d. Book.java Z:\Programs\javapgm>javac BookReader.java Z:\Programs\javapgm>java BookReader The Book No: 12 The Book Id: 15 The Book Pages: 86 Z:\Programs\javapgm>

85 How to Access package from another package 1.import package.*; 2.import package.classname; 3.fully qualified name Using packagename.* If packagename.* is used then all the classes and interfaces of this package will be accessible but not subpackages. A.Java B.Java package mypackb; package packa; import packa.*; public class A class B public void msg() public static void main(string args[]) System.out.println( Welcome ); A obj=new A(); obj.msg();

86 using package.classname; A.Java package packa; public class A public void msg() System.out.println( Chettinad ); B.Java package mypackb; import packa.a; class B public static void main(string args[]) A obj=new A(); obj.msg();

87 Using fully qualified name Only declared class of this package will be accessible A.Java package packa; public class A public void msg() System.out.println( EEE ); B.Java package mypackb; class B public static void main(string args[]) packa.a obj=new packa.a(); //using fully qualified name obj.msg();

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

89 This is file Derived.java: package p1; public class Derived_Prot extends Protection public 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);

90 This is file SamePackage.java: package p1; public class SamePackage public 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);

91 This is file OtherPackage.java: package p1.p2; public class Protection2 extends p1.protection public 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);

92 This is file OtherPackage.java: package p1.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);

93 JavaDoc Comments

94 JavaDoc Comments: Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code which has required documentation in a predefined format. The Java language supports three types of comments: Types of Comments Class Comments - /*.*/ and /* * */ Method @throws Field Comments Data Members - /* * */ General @since.

95 Single Line Comments Single line comments are used to add a very brief comment within some code, often a long or complex method. They begin with a double forward slash (//) and end with the end of line or carriage return. As an example consider: private static String name = Welcome"; //The name to print Multi Line Comments If a comment is going to span across more than one line then a multi-line comment should be used. These are often useful for providing more in-depth information. It start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). Consider: /* Getter method provides public access in read only fashion. This function returns the port number. */ int getport()...

96 Javadoc Comments Javadoc Comments are specific to the Java language and provide a means for a programmer to fully document his / her source code as well as providing a means to generate an Application Programmer Interface (API) for the code using the javadoc tool that is bundled with the JDK The Format of Javadoc Comments A Javadoc comment precedes any class, interface, method or field declaration and is similar to a multi-line comment except that it starts with a forward slash followed by two atserisks (/**). The basic format is a description followed by any number of predefined tags. Generally paragraphs should be separated or designated with the <p> tag. Java supports the following types of comments. Class level comments which describe the purpose of classes and Member level comments describe the purpose of members.

97 EXAMPLE Class Level Comments author XYZ The Employee class contains salary of each employee */ public class Employee //Employee class code Member Level Comments XYZ */ /** Class Description of MyClass */ public class MyClass /** Field Description of integer value for myintfield */ public int myintfield; /** Constructor Description of MyClass() */ public MyClass() // Do something...

98 Example /** * The HelloWorld program implements an application that * simply displays "Hello World!" to the standard output. * John */ public class HelloWorld public static void main(string[] args) /* Prints Hello, World! on standard output. */ System.out.println("Hello World!");

99 The JavaDoc Tags:

100

101

102

103 General Order of Tags The general order in which the tags occur is

104

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

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

Array is collection of homogenous Data items. Array is classified into three types. UNIT 2 1 ARRAY 2 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

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

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

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

Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key)

Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key) Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key) Branch & Section : B.Tech-IT / III Date: 06.09.2014 Semester : III Year V Sem Max.

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

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

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

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

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents character strings. All string literals in Java programs,

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

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

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

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

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

USING LIBRARY CLASSES

USING LIBRARY CLASSES USING LIBRARY CLASSES Simple input, output. String, static variables and static methods, packages and import statements. Q. What is the difference between byte oriented IO and character oriented IO? How

More information

We now start exploring some key elements of the Java programming language and ways of performing I/O

We now start exploring some key elements of the Java programming language and ways of performing I/O We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects

More information

package p1; public class Derivation extends Protection { public Derivation() { System.out.println("Derived class constructor");

package p1; public class Derivation extends Protection { public Derivation() { System.out.println(Derived class constructor); PROGRAM:1 WAP to implement the packages //package 1: package p1; public class Protection int n=1; public int n_pub=2; private int n_pri=3; protected int n_pro=4; public Protection () System.out.println("Base

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

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

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation

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

CS251L REVIEW Derek Trumbo UNM

CS251L REVIEW Derek Trumbo UNM CS251L REVIEW 2010.8.30 Derek Trumbo UNM Arrays Example of array thought process in Eclipse Arrays Multi-dimensional arrays are also supported by most PL s 2-dimensional arrays are just like a matrix (monthly

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

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

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide

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

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

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

* Mrs. K.M. Sanghavi

* Mrs. K.M. Sanghavi * Mrs. K.M. Sanghavi *Packages are those class which contains methods without the main method in them. *Packages are mainly used to reuse the classes which are already created/used in other program. *We

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

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

S.E (Computer ) (Second Semester) EXAMINATION, Time : Two Hours Maximum Marks : 50

S.E (Computer ) (Second Semester) EXAMINATION, Time : Two Hours Maximum Marks : 50 S.E (Computer ) (Second Semester) EXAMINATION, 2017 PRINCIPLES OF PROGRAMMING LANGUAGE (2015 PATTERN) Time : Two Hours Maximum Marks : 50 N.B. :- (i) All questions are compulsory (ii)neat diagrams must

More information

More non-primitive types Lesson 06

More non-primitive types Lesson 06 CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.

More information

appreciate the difference between a char and a string understand and use the String class methods

appreciate the difference between a char and a string understand and use the String class methods 1 8 THE STRING CLASS Terry Marris 16 April 2001 8.1 OBJECTIVES By the end of this lesson the student should be able to appreciate the difference between a char and a string understand and use the String

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

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Strings and Enumerations 2018W (Institute of Pervasive Computing, JKU Linz) CHARACTER ENCODING On digital systems, each character is represented by a specific number. The character

More information

Q-2 Why java is known as Platform-independent language?

Q-2 Why java is known as Platform-independent language? Q-1 Explain the various features of the java programming language. Ans:-Various features of java programming language are as given below- 1.Java is very simple programming language.even though you have

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

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017 Intro to Strings Lecture 7 COP 3252 Summer 2017 May 23, 2017 Strings in Java In Java, a string is an object. It is not a primitive type. The String class is used to create and store immutable strings.

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

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Unit 4 - Inheritance, Packages & Interfaces

Unit 4 - Inheritance, Packages & Interfaces Inheritance Inheritance is the process, by which class can acquire the properties and methods of its parent class. The mechanism of deriving a new child class from an old parent class is called inheritance.

More information

Lesson:9 Working with Array and String

Lesson:9 Working with Array and String Introduction to Array: Lesson:9 Working with Array and String An Array is a variable representing a collection of homogeneous type of elements. Arrays are useful to represent vector, matrix and other multi-dimensional

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Introductory Mobile Application Development

Introductory Mobile Application Development Notes Quick Links Introductory Mobile Application Development 152-160 Java Syntax Part 2 - Activity String Class Add section on Parse ArrayList Class methods. Book page 95. Toast Page 129 240 242 String

More information

CHAPTER 6 MOST COMMONLY USED LIBRARIES

CHAPTER 6 MOST COMMONLY USED LIBRARIES LIBRARY CHAPTER 6 - A set of ready-made software routines (class definitions) that can be reused in new programs, is called a Library. - Some commonly used java libraries are : Math Library String Library

More information

CS 1301 Ch 8, Part A

CS 1301 Ch 8, Part A CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String

More information

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B 1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these 2. How many primitive data types are there in Java? A. 5 B. 6 C. 7 D. 8 3. In Java byte, short, int and long

More information

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

More on variables and methods

More on variables and methods More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class

More information

- Thus there is a String class (a large class)

- Thus there is a String class (a large class) Strings - Strings in Java are objects - Thus there is a String class (a large class) - In a statement like this: System.out.println( Hello World ); the Java compiler creates a String object from the quoted

More information

5. PACKAGES AND INTERFACES

5. PACKAGES AND INTERFACES 5. PACKAGES AND INTERFACES JAVA PROGRAMMING(2350703) Packages: A is a group of classes and interfaces. Package can be categorized in two form: built-in such as java, lang, awt, javax, swing, net, io, util,

More information

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

c) And last but not least, there are javadoc comments. See Weiss.

c) And last but not least, there are javadoc comments. See Weiss. CSCI 151 Spring 2010 Java Bootcamp The following notes are meant to be a quick refresher on Java. It is not meant to be a means on its own to learn Java. For that you would need a lot more detail (for

More information

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16 Intro to Strings Lecture 7 CGS 3416 Spring 2017 February 13, 2017 Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, 2017 1 / 16 Strings in Java In Java, a string is an object. It is not a primitive

More information

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your

More information

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

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

More information

Advanced Object Concepts

Advanced Object Concepts Understanding Blocks Blocks - Appears within any class or method, the code between a pair of curly braces Outside block- The first block, begins immediately after the method declaration and ends at the

More information

Chapter 10: Text Processing and More about Wrapper Classes

Chapter 10: Text Processing and More about Wrapper Classes Chapter 10: Text Processing and More about Wrapper Classes Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley.

More information

Chapter 8 Strings. Chapter 8 Strings

Chapter 8 Strings. Chapter 8 Strings Chapter 8 Strings Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Pace University. Fundamental Concepts of CS121 1

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

More information

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects CS200: Computer Science I Module 19 More Objects Kevin Sahr, PhD Department of Computer Science Southern Oregon University 1 Class API a class API can contain three different types of methods: 1. constructors

More information

Prepared By: Shiba R. Tamrakar

Prepared By: Shiba R. Tamrakar Note: It is assumed that the students have some basic knowledge of C and C++ so some common keywords and other concepts are skipped (like loop, array etc if required do refer to class room note). What

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

Eng. Mohammed Abdualal

Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 2 String & Character Eng. Mohammed Abdualal String Class In this lab, you have

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information

CS112 Lecture: Characters and Strings

CS112 Lecture: Characters and Strings CS112 Lecture: Characters and Strings Objectives: Last Revised 3/21/06 1. To introduce the data type char and related basic information (escape sequences, Unicode). 2. To introduce the library classes

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Chapter 12 Strings and Characters. Dr. Hikmat Jaber Chapter 12 Strings and Characters Dr. Hikmat Jaber 1 The String Class Constructing a String: String message = "Welcome to Java ; String message = new String("Welcome to Java ); String s = new String();

More information

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 CHAPTER 8 STRINGS Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract

More information

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

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

More information

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

Class Libraries and Packages

Class Libraries and Packages Class Libraries and Packages Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang

More information

CS11 Java. Fall Lecture 1

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

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

copy.dept_change( CSE ); // Original Objects also changed

copy.dept_change( CSE ); // Original Objects also changed UNIT - III Topics Covered The Object class Reflection Interfaces Object cloning Inner classes Proxies I/O Streams Graphics programming Frame Components Working with 2D shapes. Object Clone Object Cloning

More information

PIC 20A The Basics of Java

PIC 20A The Basics of Java PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and

More information

INHERITANCE Inheritance Basics extends extends

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

More information

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Third Year Diploma Courses in Computer Science & Engineering, Computer Engineering, Computer Technology & Information Technology Branch.

Third Year Diploma Courses in Computer Science & Engineering, Computer Engineering, Computer Technology & Information Technology Branch. Third Year Diploma Courses in Computer Science & Engineering, Computer Engineering, Computer Technology & Information Technology Branch. Java Programming Specific Objectives: Contents: As per MSBTE G Scheme

More information

( &% class MyClass { }

( &% class MyClass { } Recall! $! "" # ' ' )' %&! ( &% class MyClass { $ Individual things that differentiate one object from another Determine the appearance, state or qualities of objects Represents any variables needed for

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

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

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture. CSE1710 Click to edit Master Week text 12, styles Lecture 23 Second level Third level Fourth level Fifth level Fall 2014! Thursday, Nov 27, 2014 1 Big Picture Today is last day covering Ch 6 Tuesday, Dec

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

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

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs Ananda Gunawardena Java APIs Think Java API (Application Programming Interface) as a super dictionary of the Java language. It has a list of all Java packages, classes, and interfaces; along with all of

More information

CST242 Strings and Characters Page 1

CST242 Strings and Characters Page 1 CST242 Strings and Characters Page 1 1 2 3 4 5 6 Strings, Characters and Regular Expressions CST242 char and String Variables A char is a Java data type (a primitive numeric) that uses two bytes (16 bits)

More information

Java Foundations: Unit 3. Parts of a Java Program

Java Foundations: Unit 3. Parts of a Java Program Java Foundations: Unit 3 Parts of a Java Program class + name public class HelloWorld public static void main( String[] args ) System.out.println( Hello world! ); A class creates a new type, something

More information

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. Java Programming String Processing 1 Copyright 2013, Oracle and/or its affiliates. All rights Overview This lesson covers the following topics: Read, search, and parse Strings Use StringBuilder to create

More information