Presentation is loading. Please wait.

Presentation is loading. Please wait.

An introduction to Java Primitive Java– Chapter 1.

Similar presentations


Presentation on theme: "An introduction to Java Primitive Java– Chapter 1."— Presentation transcript:

1 An introduction to Java Primitive Java– Chapter 1

2 The General Environment Source Code resides in a text file with the extension.java Object Code - compiled code Java byte-code, or j-code in a file whose extension is.class The Java interpreter, java interprets and runs the j-code

3 Input Java programs can get input from several different places…. For example, The terminal -- standard input command-line arguments A file A Web resource

4 1. public class FirstProgram 2. { 3. public static void main(String [] args) 4. { 5. 6. BufferedReader in = 7. new BufferedReader(new InputStreamReader(System.in)) ; 8. try 9. { 10. String str1=in.readLine(); 11. double n = Double.parseDouble(str1); 12. System.out.println(“Input Number = “+ number); 13. } 14. catch(IOException e) 15. { 16. System.out.println("Exception : "+e.toString()); 17. } 18. } 19. } Input from the terminal I

5 1. import javax.swing.JOptionPane; 2. public class FirstProgram 3. { 4. public static void main(String [] args) 5. { 6. String fnumber = JOptionPane.showInputDialog(“Enter a Number : “); 7. int number = Integer.parseInt(fnumber); 8. } 9. } Input from the terminal II

6 Comments Java has three forms of comments begins with /* and ends with */ allows multi-line comments comments DO NOT nest begins with // and ends at the end of the line begins with /** and ends with */ provides information to the javadoc utility, which is used to create documentation from the comments

7 Sample First Program // Sample First Program public class FirstProgram { public static void main(String [] cs1302_args) { System.out.println(“Hello World"); System.out.print(“Hello World”); } }

8 Terminal Output The Sample program consists of two statements a constant String, “Hello World”, is placed on the standard output stream, System.out, by sending the println message to it (sometimes calls, “invoking the println method.”) What is the difference between sending println() message and print() message?

9 The eight primitive types

10 Constants Integer constants decimal octal - leading 0 hexadecimal - leading 0x or 0X 37, 045, and 0x25 each represents 37 BE CAREFUL with leading 0’s! Float constants 12.0, 12.0F, 12.0D,

11 Constants continued Character constants Unicode standard contains over 30,000 distinct characters. (www.unicode.org) enclosed in single quotes - ‘a’ Special escape sequences ‘\n’ -- newline ‘\\’ -- backslash ‘\’’ -- single quote ‘\”’ -- double quote String constants -- enclosed in double quotes - - “Hello”

12 public static void main(String [] args) { double x ; // x = 1/2; System.out.println(“x1-value = “ + x); // x = 1.0/2.0; System.out.println(“x2-value = “ + x); // x = 1.0/2 ; System.out.println(“x3-value = “ + x); } Importance of Type

13 How to print Japanese in Java? The following statement will print a Japanese Katanaga small letter A System.out.println("\u30A1"); You can see the Katanaga small letter A only when your computer or editor supports Katanaga small letter A. Otherwise, you will see only ?.

14 String inside story Two different ways of creating string object. Method 1 String s1 = new String(“Hello”) ; String s2 = new String(“Hello”) ; Method 2 String s1 = “Hello” ; String s2 = “Hello” ;

15 Java Identifiers Rules for identifiers made up of any combination of letters, digits, the $ sign, and underscores may not begin with a digit may not be a Java reserved word Java is case sensitive Fred and fred are different identifiers $Fred, $fred, _Fred, $, _, $1, $10 Setup your own rule of naming convention dollarValue, dollar_value, dollarvalue, dvalue

16 Declaration and Initialization A variable be declared before its first use Example declarations method 1 int minWage = 5.15 ; // minWage………. method 2 int minWage ; minWage = 5.15

17 Golden Rule of OOP Always initialize variables

18 Basic Operations Types of Java operators Unary operators ++, -- Binary operators +, -, *, /, ==, !=, Ternary operators (x==0? 1: 2) These operators are used to form express x= 10.2+20.5; if ( x==10 ) System.out.println(“x is 10”);

19 Unary Operators Unary minus/plus (),[],.,++,--,(unary post-, pre-), !, (type) -x // evaluates to the negative of x +x // does not change the value of x Operators precedence uniary > binary > ternary increment operator (++) ++x // preincremental operator // add 1 before the value of x is used x++ // postincremental operator // adds 1 after the value of x is used

20 Magic of Unary Operators I public class UnaryOperator { public static void main(String [] args) { int a,b,c ; b=1; c=10; a= b++ + c++ ; System.out.println("a-value = "+a); b=1; c=10; a= ++b + c++ ; System.out.println("a-value = "+a); }

21 public class UnaryOperator { public static void main(String [] args) { int a,b,c ; b=1; c=10; a= b++ + ++c ; System.out.println("a-value = "+a); b=1; c=10; a= ++b + ++c ; System.out.println("a-value = "+a); } Magic of Unary Operators II

22 Magic of Unary Operators III public class UnaryOperator { public static void main(String [] args) { int a,b; b=1; a= b++ + b-- ; System.out.println("a-value = "+a); // 3 b=1; a= ++b + b-- ; System.out.println("a-value = "+a); // 4 }

23 Magic of Unary Operators IV public class UnaryOperator { public static void main(String [] args) { int a,b ; b=1; a= b++ + b++ ; System.out.println("a-value = "+a); b=1; a= ++b + b++ ; System.out.println("a-value = "+a); }

24 Type Conversion Narrowing : Conversion from double to int int x; double dnumber =1.0; x = (int) dnumber ; Widening int x = 10; double dnumber; dnumber = x ;

25 Type Conversion Pay attention to precedence. int x=10; int y=20 ; double quotient; quotient = (double) x/y; //creates a temporary double // variable with x’s value and // forces real division -- 0.75

26 Relational and Equality Operators The equality operators ==is equal to !=is not equal to The relational operators greater than >=greater than or equal to

27 Logical Operators Java’s logical operators are used to simulate Boolean algebra concepts: && AND (conjunction) || OR (disjunction) !NOT (negation) Java uses short-circuit evaluation of && and || if the result can be determined from the first expression, the second is not evaluated

28 Figure 1.4 Result of logical operators

29 Programming Constructs There are three basic constructs used for flow of control in good programs sequentialblocks of statements selectionconditional statements repetitionlooping statements

30 Conditional statements Java provides four conditional statements if to choose whether or not to do something if-else to choose one of two alternatives switch a multi-way choice conditional operator ?:

31 The if statement if ( expression Q ) statement A next statement

32 The if-else statement if ( expression Q ) statement A else statement B next statement

33 The switch statement A switch statement is used to select among several small integer values A switch statement consists of an expression and a block The block contains a sequence of statements and a collection of labels, all of which must be distinct [an optional default label matches any unlisted label]

34 A switch example

35 The break statement break is used to force early termination of a switch statement break is used to separate logically distinct cases without the break statement, all statements on the switch are executed from the entry point to the end of the switch

36 float n=1 // input from the user switch(n) { case 1 : System.out.println(“case 1”); case 2: System.out.println(“case 2”); default: System.out.println(“End of the Switch”); break; }

37 The conditional operator The conditional operator ? : is used as a shorthand for simple if-else statements The general form is testExpr ? YesExpr : NoExpr precedence is just above that of the assignment operator maxVal = (x >= y)? x : y ;

38 Looping statements Java provides three looping statements while a top-tested loop do-while a bottom tested loop for used primarily for iteration

39 The while statement while (expression Q) statement A; next statement;

40 The do-while statement do statement A; while (expression Q) next statement;

41 The for statement for (initialization ; test ; update ) statement A; This is equivalent to the following statements initialization; while (test) { statement A; update; }

42 break and continue break can be used to exit the innermost containing loop prematurely continue can be used to give up on the current iteration and proceed to the next break can only appear in the body of a switch or a loop continue can only appear in the body of a loop

43 Use of Break I while (…) { … if (something bad) break;... }

44 1. bk1: 2. for ( int i=0 ; i< 100 ; i++) 3. { 4. System.out.println("index -value = " + i); 5. if ( i== 10 ) break bk1 ; 6. } 7. bk2: 8. System.out.println("End of the loop"); What is the output of executing this code segment? Use of Break II

45 Use of Break III 1. for ( int i=0 ; i< 100 ; i++) 2. for ( int j=0 ; j<100 ;j++) 3. { 4. System.out.println(“ ( " + i+”, “+j+” ) “); 5. if ( i+1==j ) break ; 6. } 7. System.out.println("End of the loop"); What is the output of executing this code segment? You can use a labeled break statement to break out of the above double loop.

46 Use of Continue 1. for (int i = 1: i <= 100; i++) 2. { 3. if ( i % 10 = = 0)continue; 4. System.out.println( i ); 5. }

47 Methods Method header method name parameter list consisting of zero or more parameters return type Method body The actual code for the method Method Declaration header plus body

48 Method Call Note that Java passes all arguments to a method by value. That is, when a method is called, the current values of the arguments are copied into (formal) parameters using normal assignment. Note that when an object is passed to a method, we are actually passing a reference to that object. The value that gets copied is the address of the object. Thus the parameter and the corresponding argument become alias of each other.

49 Parameter Passing I 1. public static void main(String [] args) 2. { 3. int n=1; 4. changeValue(n); 5. System.out.println("n2-value = "+n); 6. } 7. 8. public static void changeValue(int n) 9. { 10. n = n++ ; 11. System.out.println("n1-value = "+n); 12. }

50 Parameter Passing IIa 1. class MyInt 2. { 3. private int n ; 4. public MyInt( int n) 5. { 6. this.n = n ; 7. } 8. public void set( int m) 9. { 10. this.n = m ; 11. } 12. public int get() 13. { 14. return n; 15. } 16. public void show() 17. { 18. System.out.println("My integer value = "+n); 19. } 20. }

51 Parameter Passing IIb 1. public static void main(String [] args) 2. { 3. MyInt n1 = new MyInt(); 4. MyInt n1 = new MyInt(10); 5. n1.show(); 6. increase(n1); 7. n1.show(); 8. } 9. public static void increase(MyInt m) 10. { 11. int n = m.get(); 12. m.set(n+1); 13. }

52 Overloading Method Names Java allows several methods in the same class scope to share the same name, as long as their signatures (parameter lists) differ. The return type is not a part of the method’s signature and thus it is illegal to have two methods in the same class scope whose only difference is the return type

53 public static void main(String [] args) { show("Hello"); show("Hello",2); } public static void show(String s1) { System.out.println("Inside show 1 : "+s1); } public static int show(String s1) { System.out.println("Inside show 1 : "+s1); } public static void show(String s1, int n) { for (int i=0 ; i<n ; i++ ) System.out.println("Inside show 2 : "+s1); }

54 Storage Classes Local variables Declared inside a method body Only accessible in that method body Created when the method body is executed Disappear when the method terminates Variables declared outside any method body Global in the class If static is used, the variable may be accessed by static methods If static and final are used, the entity is constant

55 Graphical User Interface (GUI) JLabel

56 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 1. class MyJLabel extends JFrame 2. { 3. public MyJLabel() 4. { 5. super("Testing JLabel"); 6. Container container = getContentPane(); 7. container.setLayout( new FlowLayout()); 8. container.add(new JLabel("My Simple Label")); 9. setSize(200,200); 10. show(); 11. } 12. } 13. public class TestJLabel 14. { 15. public static void main(String [] args) 16. { 17. MyJLabel mylabel = new MyJLabel(); 18. } 19. }

57 Graphical User Interface (GUI) JButton

58 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 1. class MyJLabel extends JFrame 2. { 3. public MyJLabel() 4. { 5. super("Testing JLabel"); 6. Container container = getContentPane(); 7. container.setLayout( new FlowLayout()); 8. container.add(new JButton("My Simple Label")); 9. setSize(200,200); 10. show(); 11. } 12. } 13. public class TestJLabel 14. { 15. public static void main(String [] args) 16. { 17. MyJLabel mylabel = new MyJLabel(); 18. } 19. }

59 GUI: Multiple Component 1. container.add(new JButton("My Simple Button")); 2. container.add(new JLabel("My Simple Label"));


Download ppt "An introduction to Java Primitive Java– Chapter 1."

Similar presentations


Ads by Google