
Key Features of Java Programming Language and Handling Strings in Java
"Explore the key features of Java when it was first released and learn how to handle strings in Java with examples of string creation, manipulation, and methods usage. Understand the immutability of String objects and the indexing of characters within strings."
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
CSC 1052 Algorithms & Data Structures II Review of Java
OVERVIEW OF KEY FEATURES OF JAVA 2
The Java Programming Language Originally intended to control consumer devices special-purpose language Soon changed to a much broader scope general-purpose language First public release: 1995 Sun Microsystems was purchased by Oracle in 2010 3
The Java Programming Language Key features when Java was first released: Platform Independence not tied to one type of computer* Applets Programs that run in a web browser Object-oriented A effective programming paradigm Garbage Collection Java "cleaned up" memory by getting rid of unused objects *Java's slogan: "Write Once, Run Anywhere." 4
Strings A character string is a group of ordered characters Character strings are objects in Java, defined by the String class So a String variable is a reference to an object The String class is part of the java.lang package, so does not need to be imported 5
Strings Strings can be created with the new operator, but a double- quoted string literal is already an object String name = new String("James Gosling"); String title = "Rephactor Java"; The plus operator (+) is used to perform string concatenation System.out.println("Without " + name + ", there would be no " + title + "."); Without James Gosling, there would be no Rephactor Java. 6
Strings Strings are managed so that you can refer to individual characters by a numeric index, which starts at 0 The String class has many methods to help manage strings For example, the length method returns the number of characters in the string (14 in this case) The charAt method returns the character at a particular index int num = title.length(); char letter = title.charAt(10); 7
Strings A String object is immutable, which means you can't change the characters in the string once it is created Many String methods return new String objects String titleUpper = title.toUpperCase(); 8
Strings The substring method returns a new String that contains a subset of characters copied from another string There are two versions: one that takes one index as an argument and one that takes two str.substring(5) str.substring(7, 12) If one index is specified, the substring runs from that index to the end of the string If two indexes are specified, the substring runs from the first index up to but not including the second index 9
Strings String goBig = "Go big or go home"; String sub1 = goBig.substring(10); String sub2 = goBig.substring(3, 12); System.out.println("Original string: " + goBig); System.out.println("substring(10): " + sub1); System.out.println("substring(3, 12): " + sub2); 10
Arrays An array is an object that holds a set of values Each value can be accessed by a numeric index An array of length N is indexed from 0 to N-1 The scores array can hold 10 integers, indexed from 0 to 9 The name of the array is an object reference variable 11
Arrays Square brackets (the index operator) are used to refer to a specific element in the array int num = scores[3]; An exception is thrown if you attempt to access an array outside of the range 0 to N-1 This is called a bounds error Each element of scores can be treated as an individual integer scores[7] = 83; 12
Arrays The object reference variable is declared without specifying the size of the array int[] scores; The variable scores can refer to any array of integers The size of an array is specified when the array object is created scores = new int[10]; As with other objects, those two steps may be combined int[] scores = new int[10]; 13
Arrays In Java it is valid to associate the brackets with the array name in a declaration int myList[]; However, this is not a good idea It is far more readable to associate the brackets with the element type int[] myList; Together, they define the type of the variable (an array of int) 14
Arrays The array's element type is the type of values it stores An array can be declared to hold any primitive or object type Only values consistent with the element type can be stored in it int[] widths = new int[500]; double[] myArray = new double[20]; boolean[] flags = new boolean[80]; String[] names = new String[150]; When an array is created it is filled with the default value for the element type 15
Arrays The size of an array is stored in a constant called length Once an array has been created, its size cannot change The for and for-each loops are often used when processing arrays int[] list = new int[15]; for (int i = 0; i < list.length; i++) list[i] = i * 10; for (int value : list) System.out.print(value + " "); 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 16
Arrays Modifying particular elements of that array: list[3] = 999; list[0] = list[5]; list[12] = list[13] + list[14]; for (int value : list) System.out.print(value + " "); 50 10 20 999 40 50 60 70 80 90 100 110 270 130 140 17
Arrays An array can also be created using an initialization list, which both creates the array and fills it with values int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}; If an initialization list is used, the new operator is not The array size is determined by the number of elements in the list 18
For Statement A for statement is a loop that works well when you know or can calculate how many iterations need to be performed The for loop header contains three sections separated by semicolons Condition Increment Initialization for (int num = 1; num <= 10; num++) System.out.println(num); The control variable is often declared in the initialization section, but doesn't have to be 19
For Statement for (int num = 1; num <= 10; num++) System.out.println(num); System.out.println("Now here."); 1 2 3 4 5 6 7 8 9 10 Now here. 20
For Statement The for statement is compact and often convenient Equivalent code could always be written as a while loop 22
For Statement The increment section does not have to increment for (int i = 20; i > 0; i--) System.out.print(i + " "); System.out.println(); System.out.println("Now here."); 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Now here. 23
For Statement Printing the powers of two less than 1000: for (int num = 2; num < 1000; num *= 2) System.out.print(num + " "); System.out.println(); System.out.println("Now here."); 2 4 8 16 32 64 128 256 512 Now here. 24
For Statement Printing a triangle made of asterisks: for (int line = 1; line <= 7; line++) { for (int asterisk = 1; asterisk <= line; asterisk++) System.out.print("*"); System.out.println(); The outer loop's control variable } * ** *** **** ***** ****** ******* 25
Common Array Algorithms An array is a sequence of elements containing the same type of data. It is created using square brackets ([]) and initialized using the new operator. The array can be empty or can contain any number of initial items. int[] emptyList; int[] fullList = {7, 11, 99, 5, 17, 2, 73, 3, 9}; Arrays enable the use of many other common algorithms: Filling and printing values in an array Finding an average, minimum or maximum Searching for and swapping elements 26
Common Array Algorithms: Filling & Printing An array can be filled by initializing it with values, and printed either directly or using a for loop. int[] values = {58, 23, 70, 105, 64, 12, 174, 33}; System.out.println(values[0]); for (int num : values) System.out.println(num + " "); 58 58 23 70 105 64 12 174 33 51 4 27
Common Array Algorithms: Filling & Printing An array can also be filled programmatically by setting each value directly, and then printed. int[] evens = new int[10]; for (int i = 0; i < evens.length; i++) evens[i] = i * 2; System.out.println(evens[0]); for (int i = 0; i < evens.length; i++) System.out.println(" | ", evens[i]); 0 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 28
Common Array Algorithms: Average Value To calculate the average value for an array of values, sum the values using a loop and divide by the number of values. int[] values = {58, 23, 70, 105, 64, 12, 174, 33, 51, 4}; double sum = 0.0; for (int num : values) sum += num; double average = sum / values.length; System.out.println("Average: " + average); Average: 59.4 29
Common Array Algorithms: Minimum Value A common algorithm used with arrays is finding a minimum. int[] values = {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8}; int minIndex = 0; for (int i = 1; i < values.length; i++) if (values[i] < values[minIndex]) minIndex = i; System.out.println("Minimum: " + values[minIndex]); System.out.println("At index: " + minIndex); Minimum: 2 At index: 5 30
Common Array Algorithms: Maximum Value Finding the maximum value works the same way as minimum. int[] values = {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8}; int maxIndex = 0; for (int i = 1; i < values.length; i++) if (values[i] > values[maxIndex]) maxIndex = i; System.out.println("Maximum: " + values[maxIndex]); System.out.println("At index: " + maxIndex); Minimum: 99 At index: 2 31
Common Array Algorithms: Searching Searching for a specific value in an unordered list can be done using a linear search. int[] values = {7, 11, 99, 5, 17, 2, 73, 3, 9, 12, 8}; int target = 73; int index = 0; while (index < values.length && values[index] != target) index++; if (index < values.length) System.out.println(target + " found at " + index); else System.out.println(target + " not in array "); 73 found at index 6 32
Common Array Algorithms: Swapping Swapping one item for another requires a temporary variable. int[] values = {58, 23, 70, 105, 64, 12, 174, 33, 51, 4}; for (int num : values) System.out.print(num + " "); System.out.println(); # Swap elements index 3 (105) and index 9 (4) int temp = values[3]; values[3] = values[9]; values[9] = temp; for (int num : values) System.out.print(num + " "); 58, 23, 70, 105, 64, 12, 174, 33, 51, 4 58, 23, 70, 4, 64, 12, 174, 33, 51, 105 33
Eclipse Eclipse is an integrated development environment (IDE) for Java programmers that is well-suited to programmers at all levels of experience. An IDE is software that combines the tools that a programmer uses to write, save, edit, and run code. 35
Install Eclipse Visit the Eclipse website and click on the Download button Select the version of the Eclipse IDE for Java Developers that's right for your system, download and install it.
Write & Run a Program Select File > New > Java Project. On the New Java Project dialog, type HelloEclipse as the name. Click Don't Create when asked. Then select File > New > Class and create a HelloEclipse class.
Write & Run a Program Enter this code: public class HelloEclipse { public static void main(String[] args) { System.out.println("Hello, Eclipse!"); } } Run by clicking Hello, Eclipse!
Objects and Classes An object is a fundamental program component It represents something in terms of attributes and behaviors Potential attributes of a car: make, model, color, current speed, current direction Potential behaviors of a car: accelerate, stop, change gears, turn Which attributes and behaviors are actually represented depends on what the system does A car object in a racing game would be different than a car object in a dealer inventory system 42
Objects and Classes An object is defined by a class A class is: the type of the object the pattern from which it is created You might write a class called Car and then create many Car objects using it The word class comes from the word classification A class represents a group of similar objects An object is an instance of a class Each object has its own instance data that represents its attributes 43
Objects and Classes An object has three properties identity the way you specify an individual object A reference variable is the object's identity in a program state the values of its instance data One car: green Honda CRV heading northeast at 55 MPH Another car: black Ford Focus heading south at 40 MPH behavior the list of services an object can perform The methods you can invoke on an object define its behavior (also known as its public interface) 44
Objects and Classes A class is like the blueprint of an object The concept The realization You can't live in a blueprint, but it defines the house Houses made from the same blueprint are the same type of house, but have room for different furniture and families 45
Objects and Classes A class defines the types of data an object will have and determines how that data will be organized But it doesn't reserve any memory space for it until an object is created Each object has its own memory space and therefore its own state The class contains the code for the methods that define an object's behavior But the methods are called through a particular object, which determines which data is used and updated 46
Creating Objects The java.awt.Point class represents a two-dimensional x, y coordinate To create a Point object, we use the new operator Point p = new Point(4, 7); A call to the object's constructor sets up the new object A constructor is like a method that initializes instance data and whatever else is necessary to get the object ready to use A constructor has the same name as the class 47
Creating Objects These activities are often combined this way, but they don't have to be 48
Creating Objects If a reference variable is null, it doesn't refer to any object Point target = null; Later on, it can be assigned an object target = new Point(12, 15); 49
Creating Objects Beware the null reference! Following a null reference will cause a NullPointerException to be thrown Point nowhere = null; double x = nowhere.getX(); When in doubt, check to see if a reference is null if (myPoint != null) x = myPoint.getX(); 50