390 likes | 519 Views
Chapter 2. The Java Language. Hello World Application Hello World Applet Java Language Features. Hello Wolrd Application. class HelloWorld { /** * compile first via * javac HelloWorld * the main method is then executed by * java HelloWorld arg */
E N D
Chapter 2 The Java Language • Hello World Application • Hello World Applet • Java Language Features
Hello Wolrd Application • class HelloWorld { • /** • * compile first via • * javac HelloWorld • * the main method is then executed by • * java HelloWorld arg • */ • public static void main(String [] argv) { • System.out.println(“Hello World!”); • } • } • Note that main denotes the function to execute for a given program, with type String -> void.
Compiling and Executing • javac HelloWorld.java • java HelloWorld
Hello World Applet import java.applet.Applet; // import Applet class import java.awt.Graphics; // import Graphics class public class Welcome extends Applet { public void paint(Graphics g) { g.drawString(“Welcome World!”,25,25); } } • Web browser or appletviewer could execute code, but must be embedded in HTML file:
Hello World Applet <html> <head> <title> Sample HTML file for Welcome World</title> </head> <body> <applet code=“Welcome.class” width=275 height=35> </applet> </body> </html>
Java Compilation & Exec. appln.java compiler javac embed appln.class appln.html java appletviewer interpreter WEB browser
Java Language Features • Comments • Data Types • primitive data types • object data types (incl arrays) • Operators • Functions/Methods • Expressions • Control Structures • Libraries
Comments Three forms : /* comment */ // comment to end of line /** documentation comment for javadoc tool */
Primitive Data Types • Signed Integers: • byte (8 bit, default: 0) • short(16 bit, default: 0) • int(32 bit, default: 0) • long(64 bit, default: 0L) • Characters: • char (16 bit Unicode, default: 0) • Floating point: • float (32 bit, default: 0.0f) • double(64 bit, default: 0.0d) • Boolean: • boolean (true/false, default: false)
Arrays • An array is a collection of variables of the same type Card [] deck = new Card[52]; for (int i = 0; i < deck.length; i++) { deck[i] = . . . • arrays are NOT container classes but an array does have some capabilities that appear as if they are objects: • bounds checking, • respond to messages double x[]= new double[12] ; int y = x.length;
Arrays • array indices start at 0; • if a programmer uses an index outside of the range an exception will be thrown. • Programmer is not required to do all array access within a try block.
Arrays Data Types int[]A = new int[5];//allocates 5 items A[0]=11; A[1]=22; A[2]=33; A[4]=44; A[5]=55; • Arrays are generated dynamically with new. int[] intvec = new int[100]; double [][] matrix1 = new doube[10][20]; double [][] matrix2 = new double[10][]; for(int i=0; i < 10; i++) matrix2[i] = new double[20]; • An alternative way to create & initialize the array is: int[] A = {11,22,33,44,55};
Class Types • In Java, all classes are actually subclasses of class Object. • When we define a class: class MyClass { ..... } • we are actually implicitly extending MyClass from class Object. The alternative way is : class MyClass extends Object { ..... }
Operators ==, !=, <, >, <=, >=, +, -, *, /, % (mod), ++, -- ,&& , || <<, >>, >>> (unsigned right shift), ~, &, |, ^ (xor) • All computations performed with at least 32-bits precision.
Type Hierarchy and Casting • Type hierarchy on primitive numeric types: byte<{short,char}<int<long<float<double • Type casting From small to large possible but not necessary. long x = (long) 2 // (long) redundant From large to small necessary, but might lead to loss of precision. byte x = (byte) 257 // x == 1 • No conversion from/to boolean. Use instead:b ? 1 : 0 and (x != 0)
Methods/Functions Functions in Java are written in the form: <type>fname(type1 para1 , .., typen paran ) { body } Consider sum-of-squares: sumSquares(m,n) = m2 + (m+1)2 + … + n2 In Java, can define function recursively as: int sumSquares(int m, int n) { if (m<n) { return m*m+sumSquares(m+1,n);} else {return m*m; } } Alternatively, using conditional expression: int sumSquares(int m, int n) { return ((m<n) ? m*m+sumSquares(m+1,n): m*m ) }
Expressions • Variable and Array access : x, a[I] • Class and instance member access : C.x, obj.x • Method calls : m(x,y), obj.m(x,y) • Object creation : new C() • Assignments : a=b • Type-test : obj instanceof C • Type-casts : (C) obj, (int) 1.0 • Conditional expression : (x>0) ? 1 : -1;
Control Flow & Operators • control statements mostly cloned from C++ • differences: • boolean type requires operands of &&, || etc. to be boolean • while(1) not OK…while(true) is fine • + is string concatenation • I/O is not like C++ • arrays are not like C++
Iteration (While Loop) while (test) { // if test is true statements; // execute statement } // and repeat Example : int sumSquaresA(int m, int n) { int acc=0; while (m<n) { acc = acc+m*m; m++; } return acc; }
For Iterator for (initialize; test; increment) { statements; } Example : int sumSquares(int m, int n) { int acc; for (acc=0; (m<n); m++) { acc = acc+m*m; } return acc; }
Do Loop • It is possible to perform the body of a loop before its test • using a DO-loop: do { statements; } while (condition);
Break & Continue • To provide early exit from loop, we could use break, continue and return. • To provide early exit from loop, we could use break, continue and return. break <label> - to exit from a loop continue <label>- to skip remaining statements and return to loop test return - to return to function’s caller • Labelled breaks are allowed to exit over 2 or more loops.
Other Control Struct. • Blocks • of the form : {s1; s2; … ,sn} • In a given block, local variables can be declared whose scope is visible within the block. • Selections • if - else statement : if (condition) {statements} else {statements} • Multi-way switch : switch (weekday) { case 0 : System.out.println(“Sunday”); break; case 1: case 2: case 3: case 4: case 5 : System.out.println(“Weekday”); break; case 6 : System.out.println(“Saturday”); break; default : System.out.println(“Invalid Days”); }
Libraries Numerical types • The numerical data types all share some common methods, which their inherit from class Number. int intValue(); long longValue(); float floatValue(); double doubleValue(); Integer my_integer = new Integer(256); Long my_long = my_integer.longValue(); Float my_float = new Float(3.14); Double my_double = new Double (my_float.doubleValue()); System.out.println("Double : " + my_double); System.out.println("Integer: " + my_double.intValue() );
Character Type if (Character.isLowerCase( 'H' )) System.out.println ("Lowercase value detected"); else System.out.println("Uppercase value detected"); • The character class offers a wide range of character comparison routines; the most useful are listed below : static boolean isDigit( char c ); static boolean isLetter( char c ); static boolean isLetterOrDigit( char c ); static boolean isLowerCase( char c ); static boolean isUpperCase( char c ); static char toUpperCase( char c ); static char toLowerCase( char c );
String Type • Programmers who are familiar with C will understand a string as being an array of characters. • Though Java has aspects of C/C++, the definition for a string differs strongly. • Under Java, a string is a unique object, which has its own set of methods. • Gone are the days of importing a string library, we simply invoke methods of a string object. • Some of the more useful routines are listed :
String Type // Returns the character at offset index public char charAt(int index); // Compares string with another, returning 0 if there's a match public int compareTo(String anotherString); // Returns a new string equal to anotherString // appended to the current string public String concat(String anotherString); // Returns the length of the current string public int length(); // Returns true if the current string begins with prefix public boolean startsWith(String prefix);
String Type // Returns true if the current string ends in suffix public boolean endsWith(String suffix); // Returns the remainder of the string, starting from offset beginIndex public String substring(int beginIndex); // Returns a substring from offset beginIndex to offset endIndex public String substring(int bIndex, int eIndex); // Returns the current string, converted to lowercase public String toLowerCase(); // Returns the current string, converted to uppercase public String toUpperCase();
StringBuffer Type • While strings are extremely useful, there are some tasks that require a more flexible sequence of characters. • In cases where strings are being constantly modified, and appended to, it is not always efficient to simply recreate a string every time you wish to concatenate it with another. • The StringBuffer class has an append method, which extends the capacity of the StringBuffer when required to accommodate varying lengths. The append method even allows you to add chars, booleans, integers, longs, floats & doubles.
StringBuffer Type // Appends the string version of a boolean public StringBuffer append(boolean b); // Appends a character to the buffer public StringBuffer append(char c); // Appends the string version of a integer public StringBuffer append(int i); // Appends the string version of a long public StringBuffer append(long l); // Appends the string version of a float public StringBuffer append(float f); // Appends the string version of a double public StringBuffer append(double d); // Appends the string version (toString method) of an object to the buffer public StringBuffer append(Object obj);
StringBuffer Type // Appends the string to the buffer public StringBuffer append(String str); // Returns the character at offset index public char charAt(int index); // Returns the current length public int length(); // Reverses the order of characters in the string buffer public StringBuffer reverse(); // Truncates, or pads with null characters, the buffer to a certain length public void setLength(int newLength); // Returns a string, representing the string buffer public String toString();
Class System The System class is perhaps one of the most important classes contained within the java.lang package, as this class provides us with the input and output streams. Without these, it would be very difficult to interact with the user! public static InputStream in; public static PrintStream out; public static PrintStream err;
Class System • The System class also has some interesting methods which are of use to Java programmers. public static void exit(int status) public static String getProperty(String key);
System.exit • Exit allows a Java programmer to immediately terminate execution of the program, and to return a status code. By convention, a non-zero status code indicates an error has occurred, and on PC systems, should set the appropriate DOS errorlevel. • If your Java application has been run from a batch file, you can actually test to see if it has executed correctly.
System.exit class Test { public static void main(String args[]) { System.exit (6); } } @echo off REM Execute Test.class java Test if ERRORLEVEL 6 echo An error has occurred. Please restart
System.getProperty • Another useful method from the System class is getProperty. Via the getProperty method, a Java application can gain information about the operating system under which it is running, the vendor and version of the Java virtual machine, and even the user name and home directory path of the current user under Unix based systems. • Some of the more common system properties are listed in the table below:
System.getProperty java.version - Java version number java.vendor - Java-vendor-specific string java.vendor.url - Java vendor URL java.home - Java installation directory java.class.version - Java class format version number java.class.path - Java classpath os.name - Operating system name os.arch - Operating system architecture os.version - Operating system version
System.getProperty file.separator - File separator ("/" on Unix) path.separator - Path separator (":" on Unix) line.separator - Line separator ("\n" on Unix) user.name - User account name user.home - User home directory user.dir - User's current working directory
System.getProperty • Accessing the system properties is as simple as calling the static getProperty method and passing a key from the table as a parameter. • An example is shown below, which displays the operating system of the computer it is running on. class GetPropertyDemo{ public static void main(String args[]) { // Display value for key os.name System.out.println(System.getProperty("os.name")) } }