1 / 56

Java Language

Java Language. Java Basics. Java is Familiar, Simple & Small. Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of C/C++ enables programmers to migrate easily.

marsha
Download Presentation

Java Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Language Java Basics

  2. Java is Familiar, Simple & Small • Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of C/C++ enables programmers to migrate easily. • Java is simple and small (there are only 49 keywords in Java). This is because Java removes many of the complex, redundant, dubious and error-prone features of C/C++, such as pointer, multiple inheritance, operator overloading, memory management (malloc, free), preprocessor (#define, typedef, header files), struct, union, enum, goto, automatic coercions, and etc.The number of language constructs you need to understand to get your job done in Java is minimal.

  3. A First Program in Java 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); 10 11 } // end method main 12 13 } // end class Welcome1

  4. Compile and execute

  5. Statements • A single statement ends with a semi-colon ‘;’, just like C/C++. • A block statement consists of many statements surrounded by a pair of braces {statement(s)} as in C/C++. • // Declaration statements • int score; • boolean validScore; • // Assignment statements • score = 70; • validScore = true; • // Conditional if statement • if((score < 0) || (score > 100)){ • validScore = true; • System.out.println("valid score"); • }

  6. Comments • Multi-line comments: begin with /* and end with */ (like C/C++). Eg: • /* I learn Java • because I’ve been told that • Java is Kool! • */ • Single-line comments: begin with // and end at the end-of-line (like C++). • int len = 5;// Declare, init len to 5 • len = 10;// Set len to 10

  7. Variables (or Fields) • Variables are “typed” and must be declared with a type and a name (like C/C++) as follows: • TypeName; • StringmyName;// "Tan Ah Teck" • intmyAge;// 18 • doublemyWeight;// 103.33 • booleanisMarried;// false or true • Java is case sensitive!!!!!! A rose is NOT a Rose and is NOT a ROSE • Variable Naming Convention: nouns, made-up of several words. First word is in lowercase and the rests are initial capitalized. Eg. thisIsALongVariableName. • The type can either be a build-in primitive type (eg. int, double) or an object class (eg. String, Circle).

  8. Primitive Data Types

  9. Assignment, Increment/Decrement • Examples: • i = 4; • x = y = z = 0; • x += y; // same as x = x + y; • x *= y; // same as x = x * y; • x++; // same as x = x + 1; • --x; // same as x = x - 1; • What is the difference between: • y = x++; • y = ++x;

  10. Operators - Arithmetic & Comparison OperatorMeaningExample + addition 3 + 4 (=7) - subtraction 6 - 4 (=2) * multiplication 3 * 5 (=15) / division 9 / 2 (=4) % modulus (reminder) 9 % 2 (=1) ==equal 1==2 (false) !=not equal 1!=2 (true) <less than 1<2 (true) >more than 1>2 (false) <=less than or equal to 1<=2 (true) >= more than or equal to 1>=2 (false)

  11. Operators - Arithmetic

  12. Arrays • An array is a list of elements of the same type. • Identified by a pair of square brackets []. • Must be declared with a type and a name. • Storage must be allocated using operator newor during initialization. E.g., • int[] temps;// Declare an int array temps • int temps[];// Same as above • temps = newint[5];// Allocate 5 items • // Declare & allocate array in one statement, • // initialize to default value. • int[] temps = newint[5]; • // Declare, allocate & initialize an array • int[] temps = {1, 2, 3, 4, 5};

  13. First Index Last Index Index: 0 1 2 3 n-1 arrayName n length Array (cont.)

  14. Arrays (cont.) • Array index begins with 0 (like C/C++) and must be of type int, e.g., • temps[4] = temps[2]; • The length of array is kept in an associated variable called length and can be retrieved using dot ‘.’ operator. • int[] temps = new int[5];// 5-item array • int len = temps.length;// len = 5 (How to find the array length in C?) • Build-in array bounds check: index out-of-bound triggers an ArrayIndexOutOfBoundsException at runtime. (Software Engineering more important than execution speed!) • Multidimensional arrays, eg, • int[][] matrix = new int[10][10];

  15. Flow Control - Conditional • if: if (booleanExpression) trueCase • if(x < y)System.out.println("x < y"); • if-else: if (booleanExp) trueCase else falseCase • if(x ==0) { • System.out.println("x is 0"); • }else{ • System.out.println("x is not zero"); • x =0;// set it to zero • }

  16. Flow Control - Conditional (cont.) • switch-case (Selection) • switch(theOperator) {// type char or int • case('+'): • result = x + y; • break; • case('-'): • result = x - y; • break; • default: • System.out.println("unknown operator"); • }

  17. Flow Control - Loop • for: for (initialization; test; increment) statements • int[] temps = newint[5]; • for(int i=0; i<temps.length; i++) { • System.out.println(temps[i]); • } • while: while (booleanExpression) trueCase • int[] temps = newint[5]; • int i=0; • while(i < temps.length) { • System.out.println(temps[i]); • i++; • }

  18. Flow Control - Loop (cont.) • do-while: do trueCase while (booleanExpression) • int[] temps = newint[5]; • int i=0; • do{ • System.out.println(temps[i]); • i++; • }while(i < temps.length); • What is the difference between while and do-while? • break: break and exit the innermost loop. • continue: abort the current iteration and continue to the next iteration of the loop.

  19. Class String • String is a sequence of 16-bit Unicode characters enclosed with a pair of double quotes (" "), eg. • "Hi, I'm a string!"// single quote OK • "" // an empty string • A Java String is NOT an array of characters (unlike C/C++), but an object class. (Classes and OOP will be covered later). • Need to use the escape sign (\) for special characters such as new-line (\n), tag (\t), double-quote (\"), backslash (\\), carriage-return (\r), form-feed (\f), Unicode character (\uhhhh), e.g., • "A \"string\" nested inside a string." • "Hello, \u4f60\u597d!" • // 4f60H & 597dH are Unicode • Single-quote (') does not require escape sign.

  20. String Concatenation – ‘+’ operator • You can use operator plus ‘+’ to concatenate multiple Strings together into a longer String. • ‘+’ is the only overloaded operator in Java. Overloading means different actions will be taken depending on the operands given to the ‘+’ operator. For example, • 1+2 is 3 (int + int gives int) • 1.0+2.1 is 3.1 (double + double gives double) • 1.1+2 is 3.1 (double + int: the int will be promoted to double, resulted in double + double gives double) • "Hello "+"world" is "Hello world" (String + String: concatenate two Strings and give a String) • "Hello "+5 is "Hello 5" (String + int: the int will be converted to String, and the two Strings concatenated) • "Hello "+1.1 is "Hello 1.1" (String + double: the double will be converted to String, and the two Strings concatenated)

  21. String Concatenation Example • String str1 = "Java is hot!"; • // String literal in common pool • String str2 = newString("I'm kool!"); • // new String object in heap • int len; • System.out.println(str1 +" and "+ str2); • // Gives "Java is hot! and I'm kool!" • len = str1.length(); • // Get the length of str1 • System.out.println("Counted " + len • + " characters."); • // Gives "Counted 12 characters." • // int len is converted to String • // automatically.

  22. Class String - Examine strings • Methods to examine String (refer to Java API): int length(); String substring(int startIdx, int endIdx); char charAt(int index); int indexOf(char leftMostChar); int lastIndexOf(char rightMostChar); boolean endsWith(String rightMostSubstring); • String str = "Java is cool!"; • str.length();// return int 13 • str.charAt(2);// return char 'v' • str.substring(0, 3);// return "Jav" • str.indexOf('a');// return 1 • str.lastIndexOf('a');// return 3 • str.endsWith("cool!");// return true

  23. Class String - Conversion • String is a class in java.lang.String. Many useful methods (or functions) provided in class String for manipulating strings (see Java API). (We will discuss classes & methods later in OOP). • Converting a String to other primitive types: • int anInt = Integer.parseInt(aStr); • float aFolat = Float.parseFloat(aStr); • long aLong = Long.parseLong(aStr); • double aDouble = Double.parseDouble(aStr); • Converting a primitive type to String: • String str = Integer.toString(anInt); • String str = Long.toString(aLong); • String str = Float.toString(aFloat); • String str = Double.toString(aDouble);

  24. Type Casting for Primitives • Any numeric type (integer and floating point) can be cast (transformed) to anther type, but some precision may be lost. For example: • double f = 3.5; • int i; • i = (int) f;// i = 3, cast optional • f = (double) i;// f = 3.0, cast required • Java prohibits C/C++ style of “automatic type coercions”. Explicit casting is needed if type conversion would result in a loss of precision, e.g., from int to double.

  25. Command-line Arguments Exercise 4d: Command-line Arguments • You can supply command-line arguments when invoking an application. For example, • > java Arithmetic 1234 456 + • In Java, command-line arguments are packed into a String array and passed into the main(String[] args) method, as the sole parameter args. • In the above example, the 3 String arguments "1234", "456" and "+" are packed into a String[], where: • args.length is 3 // Length of the array args • args[0] is "1234" // Item 0 of the array • args[0].length() is 4 // Length of String of Item 0 • args[1] is "456" // Item 1 of the array • args[1].length() is 3 // Length of String of Item 1

  26. Exercise 4e: Inputs From Keyboard import java.io.*; public class NumberGuess { public static void main(String[] args) throws IOException { int numberIn; String inStr; // Chain the System.in to a Reader and buffered. BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); // Read the guess System.out.print("Enter your guess: "); inStr = in.readLine(); // return input String numberIn = Integer.parseInt(inStr); ...

  27. Java Language Object-Oriented Programming (OOP)

  28. Object-oriented Programming (OOP) • Objects are reusablesoftware components that model items in the real world, e.g., student, car, rectangle, computer, purchase order etc. • OOP Analogy 1: PC = motherboard + CPU + monitor + hard disk + ... To assemble a PC, you need not understand each part in depth or how the parts are manufactured, but merely the interfaces between parts. You can build the part by yourself or get it off the shelve. • OOP Analogy 2: LOGO set. • OOP Analogy 3: A car is made up of engine, transmission, body etc. Do you have to know the details of the engine to drive the car? • Objects are like “software” ICs (Integrated Circuits). • Question: How to program a soccer computer game?

  29. Why OOP? • Modular and reusable software components. No need to re-invent the wheel! • Enable programmer to think of program element as real world objects, and model them accordingly. • More productive in software development. • Ease in software maintenance. “SOFTWARE ENGINEERING” • OOP is in contrast to “Procedural Programming” (in C, Pascal, Basic), and was adopted in C++, Java, C#. • Procedural Programming forces the programmers to think in terms of machine's bits and bytes, object-oriented programming lets the programmers to think in the problem space.

  30. Class & Instance • A class is a definition, implementation, template, or blueprint of “objects of the same kind”. • An instance is a “concrete realization” of a particular item of a class. An instance of class is referred to as an object. • Example: • class: Student • instances: “Tan Ah Teck”, “Mohammed Ali”, “Raja Kumar”.

  31. Name Student id=1888 name="Tan Ah Teck" ... getName() printGrades() ... Circle radius=1.4 color="red" ... getRadius() computeArea() ... Variables(orFields)(or Attributes) Methods(or operations) Class • A class has 3 components: 1.Name (Identity): a unique identifier. 2.Variables (state): static properties, attributes, state, data. Java API docs call fields. 3.Methods (behavior): dynamic behaviors. Also called function, procedure or operation.

  32. Encapsulation • A class in a self-contained 3-compartment box of name, variables and methods. • A class encapsulates variables (static attributes) and methods (dynamic operations) inside a 3-compartment box. The variables and methods are intimately tied together. • Procedural language like C is made up of functions. Data are separated from the functions (in the header files and global variables). Procedural language components are hard to reuse in a new application. • OOP program is made up of classes, which are self-contained and encapsulate both the data and methods. You can reuse OOP classes in a new application easily.

  33. Class Declaration - Examples publicclass Circle {// class name privatedouble radius;// variables privateString color; publicdouble computeArea() {...}//methods publicdouble getRadius() {...} } publicclass Student { // class name privateint id;// variables privateString name; publicString getName() {...}// methods publicvoid printGrades() {...} }

  34. Class Naming Convention • Class Naming Convention: nouns, in mixed case with the first letter of each internal word capitalized, e.g., RasterImage, PrintStream.

  35. Creating Instances of a Class • To create an instance of a class: 1. Declare a name of the instance, belonging to a particular class. 2. Allocate storage for the instance using the new operator. • // 1. Declare 3 instances of class Circle. • Circle c1, c2, c3; • // 2. Allocate using new, with different initial constructions. • c1 = new Circle(); • c2 = new Circle(2.0); • c3 = new Circle(3.0, "red"); • Circle c4 = new Circle(); • // Combine declare & allocate in one statement, same as: • //Circle c4; • //c4 = new Circle();

  36. Dot Operator • To refer to the variables and methods of an object, use dot‘.’ operator, e.g., • // Declare & allocate an instance of class Circle. • Circle c1 = new Circle(); • // Invoke methods of the class using dot operator. • c1.getRadius(); • c1.computeArea(); • // Modify public variables with dot operator. • c1.radius = 5.0; • c1.color = "green"; • Math.PI //Constant PI in class Math.

  37. Methods (Dynamic Behaviors) • Methods receive arguments (or parameters), perform some operations and return a single result (or voidi.e., nothing). • You have been using main() method, which is a public method accessible by all classes, takes an array of String (command-line arguments) as argument, performs the operations specified in the method's body, and return void (or nothing) to the caller. publicstaticvoid main (String[] args){ ...method's body... }

  38. Method (cont.) • Method naming convention: verbs, in mixed case with the first letter lowercase and the first letter of each internal word capitalized. E.g., getBackground(), setColor(). • Examples: • publicdouble computeArea () { • return radius*radius*Math.PI; • }

  39. Constructor Methods • A constructor is a special method that shares the same name as the class in which it is defined. • Constructor is to initialize the instance variables of an object when a new object is first instantiated. • Constructor has no return type (or implicitly return void). Hence, no return statement is needed in the body of constructor.

  40. C1:Circle radius=2.0 color="blue" methods Circle double radius String color getRadius() getColor() computeArea() C3:Circle radius=1.0 color="red" methods C2:Circle radius=2.0 color="red" methods Instances Class OOP Basics - Example • A class called Circle is declared with: • 3 constructor methods, • 2 private variablesradius (double), color (String) • 3 public methodsgetRadius(), getColor(), computeArea(). Three instances of the class c1, c2 and c3 are to be created in another class called TestCircle.

  41. publicclass Circle { privatedouble radius;// private variables privateString color; public Circle ()// constructors { radius=1.0; color="red"}// overloading public Circle (double r) { radius=r; color="red"} public Circle (double r, String c) { radius=r; color=c } publicdouble getRadius ()// assessor methods {return radius; } publicString getColor () {return color; } publicdouble computeArea () {return radius*radius*Math.PI; } }

  42. publicclass TestCircle { publicstaticvoid main(String[] args){ Circle c1 = new Circle(2.0, "blue"); System.out.println( "Radius = " + c1.getRadius() + " Color = " + c1.getColor() + " Area = " + c1.computeArea()); Circle c2 = new Circle(2.0); System.out.println( "Radius = " + c2.getRadius() + " Color = " + c2.getColor() + " Area = " + c2.computeArea()); Circle c3 = new Circle(); System.out.println( "Radius = " + c3.getRadius() + " Color = " + c3.getColor() + " Area = " + c3.computeArea()); } }

  43. Method Overloading • More than one methods may share the same name as long as they may be distinguished either by the number of parameters, or the type of parameters. E.g., • int average(int n1)// A • {return n1; } • int average(int n1, int n2)// B • {return(n1+n2)/2; } • int average(int n1, int n2, int n3) // C • {return(n1+n2+n3)/3; } • average(1)// Use A, returns int 1 • average(1, 2)// Use B, returns int 1 • average(1, 2, 3)// Use C, returns int 2

  44. Access Control • Access-control modifiers are used to control the accessibility (or visibility) of the variables/methods by other classes. • public: accessible by any class. • private: accessible only from within the same class. • Examples: • privatedouble radius;// Within the class only • publicint count;// Accessible by all classes

  45. Information Hiding • Variables are usually hidden from outside class, with modifier private. • Access to the variables is provided through the public accessor's methods defined in the class, e.g., getName(), getRadius(), comupteArea(). • In the previous exercise, can you change the radius with c1.radius=2.0? How to change the radius? • Objects communicate with each others using well-defined interfaces, objects are not allowed to know how the other objects are implemented – implementation details are hidden within the objects themselves. • Rule of thumb: Don't make any variable public without good reason.

  46. Get and Set Methods • To allow others to read the value of a private variable, the class can provide a “get” method (or accessor method). A get method need not expose data in the raw format. It can edit the data and limit the view of the data others will see. • To enable others to modify a private variable, the class can provide a “set” method (or mutator method). A set method can provide data validation (such as range checking), or translate the format of data used inside the class to another format used by outsiders.

  47. Student radiuscolor Circle Undergraduate Graduate radiuscolorheight Cylinder Yr 1 Yr 2 Yr 3 Yr 4 Inheritance • Classes are organized in strict hierarchy. The classes in the lower hierarchy inherit all the variables (attributes) and methods (behaviors) from the upper hierarchy, e.g.,

  48. Superclass and Subclass • The existing class is called superclass (or parent class, base class). The class derived is called subclass (or child, extended, derived class). • In Java, each class has one and only one superclass. Each superclass can have one or many subclasses. • Java does not support multiple inheritance (i.e., multiple parents) as in C++. • Subclass is not a “subset” of superclass. In fact, subclass usually contains more detailed information (variables and methods) than its superclass. • To define a subclass, use extends operator: class UnderGraduate extends Student {...} class Cylinder extends Circle {...} class MyApplet extends java.applet.Applet {...}

  49. Superclass Circle double radius String color getRadius() getColor() computeArea() Subclass Cylinder double height getHeight() computeVolume() Inheritance - Example • In this exercise, a subclass called Cylinder is derived from superclass Circle as shown. Figure out how the subclass Cylinder uses the superclass’s constructors (thru the super() method) and inherits variables and methods from its superclass Circle.Re-use the Circle class defined in the earlier exercise.

  50. publicclass Circle { privatedouble radius;// private variables privateString color; public Circle ()// constructors { radius=1.0; color="red"}// overloading public Circle (double r) { radius=r; color="red"} public Circle (double r, String c) { radius=r; color=c } publicdouble getRadius ()// assessor methods {return radius; } publicString getColor () {return color; } publicdouble computeArea () {return radius*radius*Math.PI; } }

More Related