Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Primitive Java– Chapter 1 An introduction to Java The General Environment Source Code Object Code - compiled code resides in a text file with the extension .java Java byte-code, or j-code in a file whose extension is .class The Java interpreter, java interprets and runs the j-code Input Java programs can get input from several different places…. For example, The terminal -- standard input command-line arguments A file A Web resource Input from the terminal I 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. public class FirstProgram { public static void main(String [] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; try { String str1=in.readLine(); double n = Double.parseDouble(str1); System.out.println(“Input Number = “+ number); } catch(IOException e) { System.out.println("Exception : "+e.toString()); } } } Input from the terminal II 1. import javax.swing.JOptionPane; 2. 3. public class FirstProgram { public static void main(String [] args) { String fnumber = JOptionPane.showInputDialog(“Enter a Number : “); int number = Integer.parseInt(fnumber); } } 4. 5. 6. 7. 8. 9. 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 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”); } } 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? The eight primitive types 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, 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” Importance of Type 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); } 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 ?. 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” ; 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 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 Golden Rule of OOP Always initialize variables 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”); 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 x++ // preincremental operator // add 1 before the value of x is used // postincremental operator 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); } } Magic of Unary Operators II 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 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 } } 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); } } 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 ; 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 Relational and Equality Operators The equality operators == != is equal to is not equal to The relational operators < <= > >= less than less than or equal to greater than greater than or equal to 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 Figure 1.4 Result of logical operators Programming Constructs There are three basic constructs used for flow of control in good programs sequential selection repetition blocks of statements conditional statements looping statements Conditional statements Java provides four conditional statements if if-else to choose one of two alternatives switch to choose whether or not to do something a multi-way choice conditional operator ?: The if statement if ( expression Q ) statement A next statement The if-else statement if ( expression Q ) statement A else statement B next statement 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] A switch example 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 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; } 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 ; Looping statements Java provides three looping statements while do-while a top-tested loop a bottom tested loop for used primarily for iteration The while statement while (expression Q) statement A; next statement; The do-while statement do statement A; while (expression Q) next statement; The for statement for (initialization ; test ; update ) statement A; This is equivalent to the following statements initialization; while (test) { statement A; update; } 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 Use of Break I while (…) { … if (something bad) break; ... } Use of Break II 1. 2. 3. 4. 5. 6. 7. 8. bk1: for ( int i=0 ; i< 100 ; i++) { System.out.println("index -value = " + i); if ( i== 10 ) break bk1 ; } bk2: System.out.println("End of the loop"); What is the output of executing this code segment? Use of Break III 1. 2. 3. 4. 5. 6. 7. for ( int i=0 ; i< 100 ; i++) for ( int j=0 ; j<100 ;j++) { System.out.println(“ ( " + i+” , “+j+” ) “); if ( i+1==j ) break ; } 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. Use of Continue 1. 2. 3. 4. 5. for (int i = 1: i <= 100; i++) { if ( i % 10 = = 0) continue; System.out.println( i ); } Methods Method header Method body method name parameter list consisting of zero or more parameters return type The actual code for the method Method Declaration header plus body 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. Parameter Passing I 1. 2. 3. public static void main(String [] args) { int n=1; changeValue(n); System.out.println("n2-value = "+n); 4. 5. 6. } 7. 8. 9. 10. 11. 12. public static void changeValue(int n) { n = n++ ; System.out.println("n1-value = "+n); } Parameter Passing IIa 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. class MyInt { private int n ; public MyInt( int n) { this.n = n ; } public void set( int m) { this.n = m ; } public int get() { return n; } public void show() { System.out.println("My integer value = "+n); } } Parameter Passing IIb 2. 3. 4. 5. 6. 7. 8. public static void main(String [] args) { MyInt n1 = new MyInt(); MyInt n1 = new MyInt(10); n1.show(); increase(n1); n1.show(); } 9. 10. 11. 12. 13. public static void increase(MyInt m) { int n = m.get(); m.set(n+1); } 1. 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 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); } 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 Graphical User Interface (GUI) JLabel 1. 2. 3. import java.awt.*; import javax.swing.*; import java.awt.event.*; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. class MyJLabel extends JFrame { public MyJLabel() { super("Testing JLabel"); Container container = getContentPane(); container.setLayout( new FlowLayout()); container.add(new JLabel("My Simple Label")); setSize(200,200); show(); } } public class TestJLabel { public static void main(String [] args) { MyJLabel mylabel = new MyJLabel(); } } Graphical User Interface (GUI) JButton 1. 2. 3. import java.awt.*; import javax.swing.*; import java.awt.event.*; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. class MyJLabel extends JFrame { public MyJLabel() { super("Testing JLabel"); Container container = getContentPane(); container.setLayout( new FlowLayout()); container.add(new JButton("My Simple Label")); setSize(200,200); show(); } } public class TestJLabel { public static void main(String [] args) { MyJLabel mylabel = new MyJLabel(); } } GUI: Multiple Component 1. container.add(new JButton("My Simple Button")); 2. container.add(new JLabel("My Simple Label"));