From C++ to Java A whirlwind tour of Java for C++ programmers.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Programming Languages and Paradigms The C Programming Language.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Arrays in JAVA CS 340 Software Design Muhammad Talha.
Written by: Dr. JJ Shepherd
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
J.43 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.
Java Syntax Primitive data types Operators Control statements.
1 Strings and String Operations Overview l Creating String Objects l Substring methods l The Concatenation Operator l Strings are Immutable l Other Methods.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Fundamental Programming Structures in Java: Strings.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
DAT602 Database Application Development Lecture 5 JAVA Review.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Introduction to Java Java Translation Program Structure
August 6, 2009 Data Types, Variables, and Arrays.
Copyright Curt Hill Variables What are they? Why do we need them?
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
String Class. Variable Holds a primitive value or a reference to an object. Holds a primitive value or a reference to an object. A reference lets us know.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
Object Oriented Programming Lecture 2: BallWorld.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
Java Programming Language Lecture27- An Introduction.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
(Dreaded) Quiz 2 Next Monday.
Information and Computer Sciences University of Hawaii, Manoa
Java: Base Types All information has a type or class designation
Building Java Programs
String class.
Introduction to Programming in Java
Advanced Programming in Java
An Introduction to Java – Part I, language basics
Java Programming Language
Classes, Objects and Methods
Programming Languages and Paradigms
Introduction to java Part I By Shenglan Zhang.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

From C++ to Java A whirlwind tour of Java for C++ programmers

Java statements Identical to those of C++ Assignment Decision if else switch Repetition while for do while break, continue return catch, throw

Java scope rules The scope of a local variable extends from the point where the variable is declared to the end of the block containing the declaration. The scope of a formal parameter is the entire definition of the method. Blocks may be nested Variables may be declared anywhere within the block A variable declared within a block may not have the same name as any identifier within an enclosing block.

Java scope rules Scope of a for loop index variable is the body of the loop All variable definitions must occur within a class declaration —there are no global variables in Java!

Differences between C++ and Java Conditions in Java control statements must be boolean (C++ allows arithmetic and assignment expressions). There are no standalone functions in Java, only methods that are defined within classes. There are no global variables (variables defined outside of a class) in Java. There are no pointers in Java; however, objects are accessed via reference variables

Differences between C++ and Java A.java file usually contains a single class definition, and the name of the class is the same as the name of the file. For example, the class HelloWorld is defined in the file HelloWorld.java In Java, all parameters are passed by value; there is no “&” operator for passing parameters by reference. Operators cannot be overloaded in Java. There are no templates in Java.

Simple console output in Java Use System.out.print and System.out.println: int x = 5; double y = 3.2e4; String name = "Bob"; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("name = " + name); Output: x = 5 y = name = Bob

Simple console input in Java Not so simple, unfortunately… int n; double x; BufferedReader inData = new BufferedReader( new InputStreamReader(System.in)); n = Integer.parseInt(inData.readLine()); x = Double.parseDouble(inData.readLine()); Fortunately, we will not be doing that much console io—the bulk of our applications will be GUI-based.

Howdy.java import java.io.*; public class Howdy { public static void main(String[] args) throws IOException { BufferedReader inData = new BufferedReader( new InputStreamReader(System.in)); System.out.print(“What is your name? ”); String name = inData.readLine(); System.out.println(“Howdy there, ” + name); } }

Primitive Data Types Java primitive types include: byte short int long float double char boolean

Java classes All Java classes are descendants of the Object class. All classes inherit certain methods from Object. Variables of primitive types are not objects. There are hundreds of Java classes available to the programmer.

Java Strings Strings are sequences of characters, such as “hello” Java does not have a built in string type, but the standard Java library has a class called String String declarations: String s; // s is initially null String greeting = "Howdy!";

String concatenation + is the concatenation operator: String s1 = "Jim "; String s2 = "Bob"; String name = s1 + s2; String clone = name + 2;

substring() and length() String s = "abcdefgh"; String sub = s.substring(3,7); // sub is "defg" String sub2 = s.substring(3); // sub2 is "defgh" int len = s.length(); // len is 8

Strings are immutable Objects of the String class are immutable, which means you cannot change the individual characters in a String. To change a String, use assignment to make the object point to a different String: String s = "Mike"; s = s.substring(0,2) + "lk"; // s is now "Milk"

Testing Strings for equality The equals method tests for equality: String s1 = "Hello", s2 = "hello"; s1.equals(s2) returns false s1.equals("Hello") is true The equalsIgnoreCase method returns true if 2 Strings are identical except for upper/lower case: s1.equalsIgnoreCase(s2) returns true Do not use == to compare strings—you are comparing string locations when you do!

Useful String methods char charAt(int index) returns the character at the specified index int compareTo(String s) returns negative value if the String is alphabetically less than s, positive value if the String is alphabetically greater than s 0 if the strings are equal boolean equals(String s) returns true if the String equals s

Useful String methods boolean equalsIgnoreCase(String s) returns true if the String equals s, except for upper/lower case differences int indexOf(String s) int indexOf(String s, int fromIndex) return the start of the first substring equal to s, starting at index 0 or at fromIndex if s is not contained in String, return –1.

Useful String methods int length() returns the length of the string String substring(int beginNdx) String substring(int beginNdx, int endNdx) return a new string consisting of all characters from beginNdx to the end of the string or until endNdx (exclusive)

Useful String methods String toLowerCase() returns a new string with all characters converted to lower case String toUpperCase() returns a new string with all characters converted to upper case String trim() returns a new string by eliminating leading and trailing blanks from original string

Java arrays There are 2 equivalent notations for defining an array: int a[]; int[] a; Note that space for the array is not yet allocated In Java, steps for creating an array are: Define the array Allocate storage Initialize elements

Allocating storage for an array Allocate a 100-element array: a = new int[100]; You can specify initial values like this: a = new int[]{1,2,3,4,5}; You can declare and initialize all in a single step: int a[] = {1,2,3,4,5};

Be careful! String[] names = new String[4]; At this point, names contains 4 elements, all of which have the value null. The elements of names must be initialized before they can be used. For example: names[0] = “bob”; This situation arises whenever you have an array of objects. Remember to Allocate storage for the array, and Initialize the elements

Array operations The member variable length contains the length of the array: for(int i=0; i < a.length; i++) { System.out.println(a[i]); }

Array operations Array assignment is permitted: int a[] = {1,2,3,4}; int b[]; b = a; for(int i = 0; i < b.length; i++) { System.out.println(b[i]); }

Arrays of objects When creating arrays of objects, keep in mind that you must create the individual objects before accessing each one. The following example illustrates the process of using arrays of objects. In the example we use a class named MyClass (defined on the next slide)

MyClass public class MyClass { static int count=0; private int data; public MyClass() { count++; data = count; } public String toString() { return “” + data; } }

An array of MyClass objects // declare an array: MyClass arr[] = new MyClass[5]; // Now the array holds references to // MyClass objects, not objects itself. // The following code produces a // runtime error: System.out.println(arr[0]); // arr[0] is null!

An array of MyClass objects // To fix this error, we create objects : MyClass arr[] = new MyClass[] { new MyClass(), new MyClass(), new MyClass(), new MyClass() }; // alternately, we could initialize the // array with a for loop.

Multidimensional arrays int[][] arr = { {1, 2, 3}, {4, 5, 6} }; for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[i].length; j++) { System.out.println(arr[i][j]); }

Multidimensional arrays MyClass arr[][]= new MyClass[2][5]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 5; j++) { arr[i][j] = new MyClass(); } } // create the objects before you use the // array!

Ragged arrays int[][] arr = { {1,2}, null, {3,4,5}, {6} }; for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } } System.out.println(); }

Methods can return arrays public static String[] getNames(int n) throws IOException { BufferedReader inData = new BufferedReader( new InputStreamReader(System.in)); String[] names = new String[n]; for (int i = 0; i < n; i++) names[i] = inData.readLine(); return names; }

End of the Tour