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  James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991 James GoslingPatrick Naughton  C/C++-style syntax  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! http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html  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: http://docs.oracle.com/javase/7/docs/webnotes/install/windo ws/jdk-installation-windows.html http://docs.oracle.com/javase/7/docs/webnotes/install/windo ws/jdk-installation-windows.html  On Linux: http://docs.oracle.com/javase/7/docs/webnotes/install/linux/ linux-jdk.html http://docs.oracle.com/javase/7/docs/webnotes/install/linux/ linux-jdk.html  On Mac OS X: http://docs.oracle.com/javase/7/docs/webnotes/install/mac/ mac-jdk.html http://docs.oracle.com/javase/7/docs/webnotes/install/mac/ 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 lec01.  Write HelloPrinter program using gedit editor  Save program in cs160/ch01 as HelloPrinter.java  Open a terminal and navigate (cd) to cs160/lec01  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 2 31

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

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

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 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;

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 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

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Literals  A token that represents a particular number or other value.  Examples of int literals: 0 437 30343  Examples of double literals: 37.0 37. 3.7e1 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' '%' '.' ' '

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

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 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;

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 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

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 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

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 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

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 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!

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 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

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 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.

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Escape Sequences  Java defines a number of escape sequences so that we can represent special characters, such as newline and tab characters, within String or char literals.  The most commonly used escape sequences are listed in the table below:

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35  For example, consider the following code snippet  When the preceding code is executed, the following output is displayed:  The second and third lines of output have been indented one and two tab positions, respectively, by virtue of the use of \t, and the expression "WHEEE!!!" is printed enclosed in double quotes because of our use of \".

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

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

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 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!"); }

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 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:

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 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!"); }

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 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 3.141592653589793. Print the name of the constant and its value.  What happens if you try to a assign a value to a constant?

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 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 = 1000000; // decimal notation float f = 1.5f; // trailing 'f' distinguishes from double long l = 2000000L; // 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 = 5600000L; // 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 = 3.141592653589793; // doubles are higher precision System.out.println("pi="+pi); } IdentifierDemo.java

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 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 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

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

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

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 QUESTION  What is the output of following java expressions? 1)1 / 2 2)5 / 3 3)6.1 + 2 4)7 % 3

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

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

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 6 + (2 * 3) = 12

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

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

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 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.

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

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

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 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

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 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;

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 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 98.6. Calculate value of celcius using following equation: Expected output:

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

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 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 constants: DEGREE_RATIO (5.0/9.0) and FREEZING_POINT(32.0) and adjust your equation accordingly.

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 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

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 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 = 1000.25; 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 = 1000.25; int dollars = (int) balance;  Cast discards fractional part

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

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

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 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.

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

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 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

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 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

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68  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.

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

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Complete Example import java.util.Scanner; public class ScannerTester { public static void main(String args[]) { //create scanner object Scanner in = new Scanner(System.in); //read values System.out.println("Enter name,age and isMarried seperated by whitespaces:"); String name = in.next(); int age = in.nextInt(); boolean isMarried = in.nextBoolean(); //print values System.out.println("Name:"+name+"\nage:"+age+"\nisMarried:"+isMarried); //close scanner in.close(); }

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

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

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73 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); in.close(); } ScannerDemo.java


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

Similar presentations


Ads by Google