Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 1 of 69. Lecture B Lesson B - Basic Java Elements Unit B1 – Program Elements.

Similar presentations


Presentation on theme: "Slide 1 of 69. Lecture B Lesson B - Basic Java Elements Unit B1 – Program Elements."— Presentation transcript:

1 Slide 1 of 69. Lecture B Lesson B - Basic Java Elements Unit B1 – Program Elements

2 Slide 2 of 69. Lecture B Hello World Program, Again // My First Program!! public class HelloWorld { public static void main(String[] args){ System.out.println(“Hello World!”); }

3 Slide 3 of 69. Lecture B Identifiers: Syntax Identifiers are the words a programmer uses in a program Identifier syntactic rules:  Can be made up of any length of letters digits underscore character (_) dollar sign ($)  Cannot begin with a digit Java is case sensitive  User and user are completely different identifiers

4 Slide 4 of 69. Lecture B Identifiers: Semantics Identifiers names can come from the following sources  Fixed in Java as reserved words public, class, static, void, method, …  Chosen by the programmer to denote something HelloWorld, main, args  Chosen by a programmer whose code we use: String, System, out, println

5 Slide 5 of 69. Lecture B Naming style The correctness of the program is not affected by the names used public class X7_65Tx { … } Names play a central role in the readability of the program They are part of its documentation They should thus be chosen carefully  BankAccount, size, numberOfElements Follow conventions in choosing names!

6 Slide 6 of 69. Lecture B White Space Spaces, blank lines, and tabs are collectively called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many different ways Programs should be formatted to enhance readability, using consistent indentation

7 Slide 7 of 69. Lecture B Valid, but bad Indentation public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”) ;}}

8 Slide 8 of 69. Lecture B Comments Comments are ignored and are treated as white space They should be written to enhance readability  Explain what a piece of code does (its interface)  Explain any special tricks, limitations, … Java has three comment formats :  // comment to end of line  /* comment until closing */  /** API specification comment */

9 Slide 9 of 69. Lecture B Lesson 2 - Basic Java Elements Unit B2 - Variables and Data Types

10 Slide 10 of 69. Lecture B Variables A variable is a location in memory that can hold values of a certain data type Each variable must be declared before it is used The declaration allocates a location in memory to hold values of this type Variable types can be  primitive  reference to an object

11 Slide 11 of 69. Lecture B VariableExample Program public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); }

12 Slide 12 of 69. Lecture B VariableExample Program (2) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } x x

13 Slide 13 of 69. Lecture B VariableExample Program (3) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } x x 3 3

14 Slide 14 of 69. Lecture B VariableExample Program (4) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } x x 3 3

15 Slide 15 of 69. Lecture B VariableExample Program (5) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } x x 4 4

16 Slide 16 of 69. Lecture B VariableExample Program (6) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } x x 4 4

17 Slide 17 of 69. Lecture B Primitive Data Types A data type is defined by a set of values and the operators you can perform on them The Java language has several predefined types, called primitive data types The following reserved words represent the eight different primitive data types:  byte, short, int, long, float, double, boolean, char

18 Slide 18 of 69. Lecture B Integers There are four integer data types. They differ by the amount of memory used to store them TypeBitsValue Range byte8-127 … 128 short16-32768 … 32767 int32about 9 decimal digits long65about 18 decimal digits

19 Slide 19 of 69. Lecture B Floating Point There are two floating point types TypeBitsRange (decimal digits) Precision (decimal digits) float32387 double6430815

20 Slide 20 of 69. Lecture B Characters A char value stores a single character from the Unicode character set A character set is an ordered list of characters  ‘A’, ‘B’, ‘C’, …, ‘a’, ‘b’, …,‘0’, ‘1’, …, ‘$’, … The Unicode character set uses 16 bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages The ASCII character set is a subset of Unicode ASCII is the current standard (outside of Java)

21 Slide 21 of 69. Lecture B Boolean A boolean value represents a true/false condition. It can also be used to represent any two states, such as a light bulb being on or off The reserved words true and false are the only valid values for a boolean type

22 Slide 22 of 69. Lecture B Variable Declarations The syntax of a variable declaration is data-type variable-name; For example Multiple variables can be declared on the same line Variables can be initialized (given an initial value) in the declaration int total; long total, count, sum; int total = 0, count = 20; double unitPrice = 57.25;

23 Slide 23 of 69. Lecture B Variable Declaration Example public class DeclarationExample { public static void main (String[] args) { int weeks = 14; long numberOfStudents = 120; double averageFinalGrade = 78.6; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); }

24 Slide 24 of 69. Lecture B More Variable Examples double pi, conversionRate, temprature; long salary; boolean isOn; char c; pi = 3.14159; isOn = false; c = ‘A’; salary = 34000; isOn = true;

25 Slide 25 of 69. Lecture B Constants We may declare that a variable is a constant and its value may never change. Advantages:  readability  efficiency  error detection final double PI = 3.14159; final int CHINA_OLYMPICS_YEAR = 2008;

26 Slide 26 of 69. Lecture B Lesson 2 - Basic Java Elements Unit B3 - Expressions

27 Slide 27 of 69. Lecture B Assignment Statements An assignment statement takes the following form variable-name = expression; The expression is first evaluated Then, the result is stored in the variable, overwriting the value currently stored in the variable

28 Slide 28 of 69. Lecture B Arithmetic Operators An operator is a mapping that maps one or more values to a single value: Binary Operators: a + b adds a and b a - b subtracts b from a a * b multiplies a and b a / b divides a by b a % b the reminder of divining a by b Unary Operator: -a The negation of a

29 Slide 29 of 69. Lecture B Pounds to Kg conversion public class PoundsToKg { public static void main(String[] args){ double weightInPounds = 200.0; final double KILOS_IN_POUND = 0.455; double weightInKg; weightInKg = weightInPounds * KILOS_IN_POUND ; System.out.println(weightInKg); }

30 Slide 30 of 69. Lecture B Pounds to Kg conversion 2 public class PoundsToKg2 { public static void main(String[] args){ final double KILOS_IN_POUND = 0.455; System.out.println(200.0 * KILOS_IN_POUND); }

31 Slide 31 of 69. Lecture B Integer Division When division is performed on integers ( byte, short, int, long ), the result is truncated to an integer. int j = 5; double x = 5.0, y; System.out.println(j / 2); // 2 System.out.println(x / 2.0); // 2.5 System.out.println(5 / 2); // 2 y = j / 2 ; // 2

32 Slide 32 of 69. Lecture B Complex Expressions Expressions can combine many operators and operands Examples: x -34 weight * 2.73 2 * PI * r a - (7 – b) 1 + 2 + 3 + 4 (x + y) * (2 - z + (5 - q)) * -(1-x)

33 Slide 33 of 69. Lecture B Operator Precedence Multiplication, division, and remainder (%) have a higher precedence than addition and subtraction. Operators with same precedence evaluate from left to right. Parenthesis can be used to force order of evaluation.

34 Slide 34 of 69. Lecture B Operator Precedence Examples ExpressionResult 10 - 7 - 1 2 10 - (7 - 1) 4 1 + 2 * 3 7 (1 + 2) * 3 9 1 - 2 * 3 + 4 * 5 15

35 Slide 35 of 69. Lecture B Conversions Data types can be mixed in an expression When the expression is evaluated one type is converted to another Data is converted to a wider type in three cases  assignment conversion  arithmetic promotion  casting Can be converted to a narrower type only by casting List of types from narrowest to widest: Narrow … Wide byte short int long float double

36 Slide 36 of 69. Lecture B Conversion Examples double f, x; int j; f = 5; f = 5.0 / 2; f = x * j; f = 5 / 2; f = (float) j / 5; j = (int) f; j = (int) 5.0 / 2.0;

37 Slide 37 of 69. Lecture B Lesson 2 - Basic Java Elements Unit B4 - Objects and Method Invocation

38 Slide 38 of 69. Lecture B Reference Types Variables can be declared to be of an object type. In this case they hold a reference to an object of this type (class). Turtle t; String myName; Date today; Memory t t today myName

39 Slide 39 of 69. Lecture B Creating Objects Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle();

40 Slide 40 of 69. Lecture B Creating Objects (2) Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today

41 Slide 41 of 69. Lecture B Creating Objects (3) Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today 12345

42 Slide 42 of 69. Lecture B Creating Objects (4) Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); t t today 12345

43 Slide 43 of 69. Lecture B Strings Strings are objects that are treated by the compiler in special ways:  Can be created directly using “xxxx”  Can be concatenated using + String myName = “John Jones”; String hello; hello = “Hello World”; hello = hello + “!!!!”; int year = 2008; String s = “See you in China in “ + year;

44 Slide 44 of 69. Lecture B Method invocations You may invoke methods on an object. Methods may receive parameters. Methods may also return values. Turtle leonardo = new Turtle(); leoardo.moveForward(100); String lennon = “John Lennon”; int len = lennon.length(); char initial = lennon.charAt(5);

45 Slide 45 of 69. Lecture B APIs To use an object you only need to know its application programmer interface (API). The API of an object class includes a description of:  all available constructors and methods and what they do  the parameters they take and the values that they return The API is usually given in a special format called javadoc.

46 Slide 46 of 69. Lecture B Javadoc example

47 Slide 47 of 69. Lecture B Javadoc example (2)

48 Slide 48 of 69. Lecture B Class Libraries A class library is a collection of classes that we can use when developing programs There is a standard class library that comes with every Java environment. Class Libraries are organized into packages  java.net, java.lang, java.io,... To use classes from a package you must either  Import the package   Or, use a fully qualified class name import java.io.*; File f = new File( “John” ); java.io.File f = new java.io.File ( “John” );

49 Slide 49 of 69. Lecture B RandomNumbers.java import java.util.Random; public class RandomNumbers { public static void main (String[] args){ Random generator = new Random(); int num = generator.nextInt(); System.out.println ("A random int: " + num); num = generator.nextInt(); System.out.print(“Another one: “ + num); }

50 Slide 50 of 69. Lecture B Lesson 2 - Basic Java Elements Unit B5 - Input and Output

51 Slide 51 of 69. Lecture B Types of Input and Output (I/O) Terminal-based I/O  System.out.println()  System.in.xxxxx() Graphic User Interface  Windows, Buttons, Mouse, … Stream based I/O  Files, Web, Communication, Terminal-based I/O In this course we also provide our own classes:  InputRequestor, OutputWindow

52 Slide 52 of 69. Lecture B The InputRequestor Class To use the input requestor, you must first create the object: InputRequestor inp = new InputRequestor(); Then, you may use it to read primitive data types: int i = inp.requestInt(); int i = inp.requestInt(“Enter age:”); float f = inp.requestFloat();

53 Slide 53 of 69. Lecture B InputRequestor Behaviour A window will pop up every time you use the requestXXX() method: The window will disappear only after you have typed a legal input. The method returns this input.

54 Slide 54 of 69. Lecture B The OutputWindow Class Just as System.out enables you to display output in the MS-DOS window, you may display output in your own window. Create an OutputWindow object: Useful methods in the output window:  println() - just as regular println().  clear() - clears the output window.  showMessage() - pop up a message on the desktop. OutputWindow outwin = new OutputWindow();

55 Slide 55 of 69. Lecture B The Output Window

56 Slide 56 of 69. Lecture B The showMessage() Pop-up Window

57 Slide 57 of 69. Lecture B Circle Area and Circumference public class CircleCalc { public static void main(String[] args){ final double PI = 3.14159; InputRequestor in = new InputRequestor(); OutputWindow out = new OutputWindow(); double r = in.requestDouble("Radius: "); out.println("Radius = " + r); out.println("Area = " + PI * PI * r); out.println("Circumference = " + 2 * PI * r); }

58 Slide 58 of 69. Lecture B Lesson 2 - Basic Java Elements Unit B6 - Introduction to Applets and Graphics

59 Slide 59 of 69. Lecture B The Web

60 Slide 60 of 69. Lecture B My First HTML Example My First HTML File Hello World!!! Here is a link to CNN !

61 Slide 61 of 69. Lecture B My First Web Page

62 Slide 62 of 69. Lecture B Running programs in a web page Java was invented so that running programs can be embedded in web-pages Such Java programs are called Applets This had to solve some problems  Platform independence browsers have a built-in Java byte-code interpreter  Security the program runs in the browser in a sandbox

63 Slide 63 of 69. Lecture B A Web Page with an Embedded Applet

64 Slide 64 of 69. Lecture B Writing Applets An Applet does not have a main method. Instead, it has a set of methods that control the interaction with the user. An Applet inherits this interface from the java.applet.Applet class The paint method has to paint the screen  It receives a Graphics object, and uses it to paint  The Graphics class has various drawXXX() methods

65 Slide 65 of 69. Lecture B Smiley.java import java.applet.Applet; import java.awt.*; public class Smiley extends Applet{ public void paint (Graphics page){ page.setColor(Color.yellow); page.fillOval(50,50,300,300); page.setColor(Color.black); page.fillOval(125,125,50,50); page.fillOval(225,125,50,50); page.drawLine(150,275,250,275); }

66 Slide 66 of 69. Lecture B Smiley.HTML The Smiley.class file should be placed in the same directory with Smiley.HTML My Smiley Applet Above this text you should see Smiley!!

67 Slide 67 of 69. Lecture B Smiley

68 Slide 68 of 69. Lecture B Graphics Coordinates X Y 10 20 150 45 page.drawLine (10, 20, 150, 45);

69 Slide 69 of 69. Lecture B Drawing an Oval X Y 175 20 50 80 page.drawOval (175, 20, 50, 80);


Download ppt "Slide 1 of 69. Lecture B Lesson B - Basic Java Elements Unit B1 – Program Elements."

Similar presentations


Ads by Google