Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Introduction.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Introduction."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Introduction

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 What is java?  Developed by Sun Microsystems  General-purpose and Object-oriented language  Widespread acceptance

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Java Features  Simple no pointers automatic garbage collection rich pre-defined class library  Object oriented all functions are associated with objects potentially better code organization and reuse  Platform independent Same application runs on all platforms Java bytecode can run on any JVM, on any platform …including mobile phones and other hand-held devices

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Java Virtual Machine (JVM)  Steps: 1.Write all source code is in plain text files ending with the.java extension. 2.Compile those source files into.class files by the javac compiler. A.class file contains bytecodes — the machine language of the Java Virtual Machine(Java VM). 3.Run the bytecode/.class file using JVM

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Java Virtual Machine (JVM)  Because the Java VM is available on many different operating systems, the same.class files are capable of running on any platform.

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Java Versions

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Writing first application  You need: The Java SE Development Kit 7 (JDK 7) A text editor: Simple text editors: – Notepad, Notepad++, ….. Integrated Development Environment (IDE): – Eclipse, Netbeans, DrJava, …..

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 QUESTION  What is the difference between JDK and JRE? Java Download page has both!  ANSWER: You need to answer the question: Do you want to run Java programs or do you want to develop Java programs? JRE: If you want to run Java programs, but not develop them, download the JRE. JDK: If you want to develop Java applications, download the Java Development Kit, or JDK. The JDK includes the JRE, so you do not have to download both separately.

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Installing Java JDK  On Windows: ws/jdk-installation-windows.html ws/jdk-installation-windows.html  On Linux: linux-jdk.html linux-jdk.html  On Mac OS X: mac-jdk.html mac-jdk.html

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Your first Program: HelloPrinter.java  Choice 1: Using simple text editor STEP1: Write and save your program in text editor as HelloPrinter.java STEP2: Compile the source file into a.class file STEP3: Run the program

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Programming Question  In your home directory create a folder cs160. Inside it create a folder ch01.  Write HelloPrinter program using gedit editor  Save program in cs160/ch01 as HelloPrinter.java  Open a terminal and navigate (cd) to cs160/ch01  Compile program (if no errors, verify.class file is generated)  Run program

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Your first Program: HelloPrinter.java  Choice 2: Using IDE 1.Start the Java development environment (We use DrJava). 2.Write a simple program. 3.Run the program. 4.Organize your work.

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Becoming Familiar with Your Programming Environment 1. Write and save program (File->save) 2. Compile 3. Run

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Comments  Java supports three types of comments: 1.single-line comment: 2.multiline comment 3.document comment

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Identifiers  Names chosen by the programmer  E.g. variable names, method names, class names etc.  Identifiers are subject to the following rules: Identifiers may contain letters (both uppercase and lowercase), digits, and underscores ( _ ). Identifiers begin with a letter or underscore. There’s no limit on the length of an identifier. Lowercase letters are not equivalent to uppercase letters. (A language in which the case of letters matters is said to be case-sensitive.) Cannot be reserved words (keywords)

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Reserved Words  Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs.

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Multiword Identifiers  When an identifier consists of multiple words, it’s important to mark the boundaries between words.  One way to break up long identifiers is to use underscores between words: last_index_of  Another technique is to capitalize the first letter of each word after the first: lastIndexOf This technique is the one commonly used in Java.

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Java Conventions  A rule that we agree to follow, even though it’s not required by the language 1.Begin a class name with an uppercase letter: Student Employee String 2.Names of variables and methods, never start with an uppercase letter. age  variable name print()  method name 3.Identifier names follow camel casing (For subsequent words in name, first word capitalizd) totalSalary  variable name getName()  method name SalariedEmployee  class name

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Variables  Stores values/state  Must be declared before they can be used static typing

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Primitive Data Types  Java supports eight basic data types known as primitive types. integer floating point

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Declaring Variables  Syntax: ;  Example: int i; // Declares i to be an int variable  Several variables can be declared at a time: int i, j, k;  It’s often better to declare variables individually.

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Initializing Variables  Assign a value to the variable for the first time.  us =, the assignment operator: i = 0; byte z = 22; double h = 3.1l3; char x = ‘x’;  Variables always need to be initialized before the first time their value is used.  You can initialize variables at the time of declaration too: boolean found=true, contains; int a, b=20, c;

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Changing the Value of a Variable  The assignment operator can be used both to initialize a variable and to change the value of the variable later in the program: i = 1; // Value of i is now 1 … i = 2; // Value of i is now 2

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Literals  A token that represents a particular number or other value.  Examples of int literals:  Examples of double literals: e1 3.7e+1.37e2 370e-1  The only boolean literals are true and false.  char literals are enclosed within single quotes: 'a' 'z' 'A' 'Z' '0' '9' '%' '.' ' '

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Constants: final  Represents values that do not change.  Use keyword final when declaring a variable as a constant  Convention: use all-uppercase names for constants Words separated by underscore(“_”) final double PENNY_VALUE = 0.01; final double NICKEL_VALUE = 0.05;

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Class Declaration  Classes: are the fundamental building blocks of Java programs: The name of the public class MUST match the name of the file containing the class: Class HelloPrinter must be contained in a file named HelloPrinter.java 1 public class HelloPrinter 2 { 3 public static void main(String[] args) 4 { 5 // Display a greeting in the console window 6 7 System.out.println("Hello, World!"); 8 } 9 } Class declaration Class body

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Methods  Each class contains declarations of methods.  Each method contains a sequence of instructions describing how to carry out a particular task.  A method is called by specifying the method and its arguments.  Every Java application contains a class with a main method When the application starts, the instructions in the main method are executed

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 1 public class HelloPrinter 2 { 3 public static void main(String[] args) 4 { 5 // Display a greeting in the console window 6 7 System.out.println("Hello, World!"); 8 } 9 } Method declaration Method body

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Statements  The body of the main method contains statements.  Every statement ends with a semicolon (“;”)  Our method has a single statement: System.out.println("Hello, World!");  It prints a line of text: Hello, World!

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 1 public class HelloPrinter 2 { 3 public static void main(String[] args) 4 { 5 // Display a greeting in the console window 6 7 System.out.println("Hello, World!"); 8 } 9 } Statement 1

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Print statement  System.out.print Prints in the same line  System.out.println Prints in a new line System.out.println();// Prints in an empty line  Printing Multiple Items The + operator can be used to combine multiple items into a single string for printing purposes: int I = 10; System.out.println(“The value of i is: " + i); At least one of the two operands for the + operator must be a string.

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Syntax 1.1 Java Program

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Indentation  Programmers use indentation to indicate nesting.  An increase in the amount of indentation indicates an additional level of nesting.  The HelloPrinter program consists of a statement nested inside a method nested inside a class: public class HelloPrinter { public static void main(String[] args) { // Display a greeting in the console window System.out.println("Hello, World!"); }

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 public class HelloPrinter{ public static void main(String[] args) { // Display a greeting in the console window System.out.println("Hello, World!"); } Brace Placement  Brace placement is another important issue.  Option1: Put each left curly brace at the end of a line. The matching right curly brace is lined up with the first character on that line:

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Brace Placement  Option2: Some programmers prefer to put left curly braces on separate lines: This makes it easier to verify that left and right braces match up properly. However, program files become longer because of the additional lines. public class HelloPrinter { public static void main(String[] args) { // Display a greeting in the console window System.out.println("Hello, World!"); }

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Programming Question  Write a tester class IdentifierDemo that does the following: Create seven variables, one for each of the primitive number types in Java Initialize each variable with any appropriate value. Print out the name of each variable and its value. Modify the value of each variable with an assignment statement Print out the names of the variables and their new values. Next, create a double constants pi with value Print the name of the constant and its value.  What happens if you try to a assign a value to a constant?

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Answer public class IdentifierDemo { public static void main(String[] args) { boolean bln = true; // booleans can only be 'true' or 'false' byte b = 20; short s = 500; char c = '%'; // must use single quotes to denote characters int i = ; // decimal notation float f = 1.5f; // trailing 'f' distinguishes from double long l = L; // trailing 'L' distinguishes from int System.out.println("bln="+bln); System.out.println("b="+b); System.out.println("c="+c); System.out.println("i="+i); System.out.println("f="+f); System.out.println("bln="+bln); System.out.println("l="+l); bln = false; // booleans can only be 'true' or 'false' b = 70; s = 800; c = 't'; // must use single quotes to denote characters i = 23; // decimal notation f = 3.0f; // trailing 'f' distinguishes from double l = L; // trailing 'L' distinguishes from int System.out.println(); System.out.println("bln="+bln); System.out.println("b="+b); System.out.println("c="+c); System.out.println("i="+i); System.out.println("f="+f); System.out.println("bln="+bln); System.out.println("l="+l); final double pi = ; // doubles are higher precision System.out.println("pi="+pi); } IdentifierDemo.java

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Java Language Basics: Operators  Java provides a rich set of operators to manipulate variables. Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Java Language Basics: Operators  Arithmetic Operators: Assume variables A=10, B=20

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 QUESTION  What is the output of following java expressions? 1)1 / 2 2)5 / 3 3) )7 % 3 5)1.0/0.0 6)-1.0/0.0 7)0.0/0.0

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Answer

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Operator Precedence  What’s the value of * 3 ? (6 + 2) * 3, which yields 24? 6 + (2 * 3), which yields 12?  Operator precedence resolves issues such as this.

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45  *, /, and % take precedence over + and -.  Examples: / 2  5 + (2 / 2)  6 8 *  (8 * 3) - 5  * 7  6 - (1 * 7)  –1 9 /  (9 / 4) + 6  % 3  6 + (2 % 3)  8

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Associativity  Precedence rules are of no help when it comes to determining the value of  Associatively rules come into play when precedence rules alone aren’t enough.  The binary +, -, *, /, and % operators are all left associative:  (2 + 3) - 4  1 2 * 3 / 4  (2 * 3) / 4  1

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Parentheses in Expressions  Parentheses can be used to override normal precedence and associativity rules.  Parentheses in the expression (6 + 2) * 3 force the addition to occur before the multiplication.

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Question  What is the default parenthesis used in java for following expression:  2+3*4+1+4/2

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Answer  (((2+(3*4))+1)+(4/2))

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Compound Assignment Operators  The compound assignment operators make it easier to modify the value of a variable.  A partial list of compound assignment operators: += Combines addition and assignment -= Combines subtraction and assignment *= Combines multiplication and assignment /= Combines division and assignment %= Combines remainder and assignment

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Compound Assignment Operators  Examples: i += 2; // Same as i = i + 2; i -= 2; // Same as i = i - 2; i *= 2; // Same as i = i * 2; i /= 2; // Same as i = i / 2; i %= 2; // Same as i = i % 2;

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 Programming Question  Write a tester class FtoC that convert a Fahrenheit temperature to Celsius. In the main method declare two variables fahrenheit and celsius. Initialize fahrenheit to Calculate value of celcius using following equation: Expected output:

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Answer // Converts a Fahrenheit temperature to Celsius public class FtoC { public static void main(String[] args) { double fahrenheit = 98.6; double celsius = (fahrenheit ) * (5.0 / 9.0); System.out.println("Celsius equivalent: “ + celsius); } FtoC.java

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Programming Question  Note that the ratio 5.0/9.0 and value 32.0 is a constant in FtoC program. Modify your program so that you define a constant DEGREE_RATIO (5.0/9.0) and FREEZING_POINT(32.0) and adjust your equation accordingly.

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Answer // Converts a Fahrenheit temperature to Celsius public class FtoC { public static void main(String[] args) { final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; double fahrenheit = 98.6; double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO; System.out.println("Celsius equivalent: “+celsius); } FtoC.java

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Converting Floating-Point Numbers to Integers - Cast  The compiler disallows the assignment of a double to an int because it is potentially dangerous  This is an error: double balance = total + tax; int dollars = balance; // Error: Cannot assign double to int  Use the cast operator (int) to convert a floating-point value to an integer. double balance = total + tax; int dollars = (int) balance;  Cast discards fractional part

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Syntax 4.2 Cast

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Packages  Java classes are grouped into packages. java.net package  classes for networking java.io package  input/output functions javax.swing package  graphical user interface development Refere javadoc API  To use a class in a package, you must import the package E.g. to use Rectangle class in java.awt package: import java.awt.Rectangle;  Put the line at the top of your program.  You DON’T need to import classes in the java.lang package such as String and System.

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Syntax 2.4 Importing a Class from a Package

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Read user input  Use a class called Scanner to read keyboard input.  To use the Scanner class, import it by placing the following at the top of your program file (before class definition): import java.util.Scanner

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 2.Obtain a Scanner object: Scanner in = new Scanner(System.in); 1.Prompt user a message asking to input data: System.out.println(“Enter the Fahrenheit temperature : ”); By default, a scanner uses white space to separate tokens. White space characters include blanks, tabs, and line terminators. 2.Read the user input: Read int: use nextInt() method Read double: nextDouble() method Read string: next() method Refer Scanner page in Oracle JavaAPI

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62  nextInt() example: System.out.print("Please enter the number of bottles: "); int bottles = in.nextInt(); When the nextInt method is called, The program waits until the user types a number and presses the Enter key; After the user supplies the input, the number is placed into the bottles variable; The program continues.

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63  To read different and multiple inputs from user, creating one scanner object is enough.

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 Programming Question  Write a tester class ScannerDemo.java that accepts two numbers from user and prints the sum.  Sample output:

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 Answer import java.util.Scanner; public class ScannerDemo { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter number 1: "); int n1 = in.nextInt(); System.out.print("Enter number 2: "); int n2 = in.nextInt(); int total = n1 + n2; System.out.println(n1+ " + "+n2+ " = "+total); } ScannerDemo.java

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 Formatted Output  Use the printf method to specify how values should be formatted.  Suppose you have a variable price with value  If you use System.out.println(price) Will print :  If you want a formatted output(e.g. only 2 decimal points displayed): System.out.printf("%.2f", price); Will print: 1.22

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Formatted Output  You can also specify a field width: System.out.printf("%10.2f", price); This prints 10 characters, six spaces followed by the four characters 1.22  This command System.out.printf("Price per liter:%10.2f", price); Prints Price per liter: 1.22

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Formatted Output

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Formatted Output  You can print multiple values with a single call to the printf method.  Example System.out.printf("Quantity: %d Total: %10.2f",quantity, total);  Output explained:


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Introduction."

Similar presentations


Ads by Google