130 likes | 144 Views
CIS3931 – Intro to JAVA. Lecture Note Set 1 Thursday 12-May-05. A basic JAVA program. // Class declaration public class Welcome1 { public static void main( String args[] ) { System.out.println(“Welcome to Java”); } //end of main method } //end of class.
E N D
CIS3931 – Intro to JAVA Lecture Note Set 1 Thursday 12-May-05
A basic JAVA program // Class declaration public class Welcome1 { public static void main( String args[] ) { System.out.println(“Welcome to Java”); } //end of main method } //end of class
Compiling a JAVA program • Command = javac <filename.java> • Compiler will potentially return with error messages • Error messages = time to debug your code • Debugging = Correcting syntax errors in your code • No errors = runtime testing
Running a JAVA program • java <filename> • Example to run the class file “example.java” you would type java example • Runtime testing = Making sure your program performs as expected
Variables • A place to store values in memory • Many different types • int = integer – A whole number value (ex : 12) • char = character – A single character (ex: c) • String = characters (ex: hello) • float = floating point number (ex : 3.14)
Variable examples (declarations) int a = 1; //assigns the value 1 to a int b = 1 + 1 //assigns the result of 1 + 1 to b int c = a + b //assigns the result of a + b to c a+ = 1; //assigns the result of a + 1 to a String cup = new String(“cup of Java”); // assigns the literal “cup ofJava” to cup
Variable Casting • It is possible to cast one variable type to another • Example : A character is actually just a special case of an integer … • The character “A” has the integer value 65
Text Formatting • Text is printed to the screen with either of the following commands • System.out.println(“Insert Text Here”); • System.out.print(“Insert Text Here”); • System.out.print(“hello\n”); is equivalent to System.out.println(“hello”);
Text formatting • Column formatting can be accomplised with the /t escape character • Example : System.out.println(“a\tb\tc\td”);
Comments • There are two types of comments in JAVA • Single line comments //This is a single line comment • Block comments /* This is a block comment*/
The JAVA API • http://java.sun.com/j2se/1.5.0/docs/api/ • The most useful tool when programming in JAVA • Many algorithms and functions are already written for you
Using the API • You have to “import” the class that contains the functions you want to use • Example : • Import java.io.* will allow you to use anything in the java.io class
User Input • Use BufferedReaders. • BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); • String input = br.readLine(); • int num1 = Integer.parseInt(input); • BufferedReader is in java.io.*