Java_Tutorial

Java_Tutorial - Java Linux Emacs Tutorial COSI 31A Outline...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Java, Linux, Emacs Tutorial COSI 31A 01/24/2008 Outline Simple java program Loops and statements Classes and objects Strings, Arrays, Vectors Inheritance Interfaces and Abstract classes Exceptions Linux commands Emacs 1 Java First Java Program /* My very first java program. */ public class HelloWorld { public static void main(String args) { // print message on screen System.out.println("Hello World"); System.out.println(" World" } } save this code in file named HelloWorld.java Compile: $ javac HelloWorld.java => creates HelloWorld.class file Run: $ java HelloWorld 2 First Java Program /* My very first java program. */ public class HelloWorld { public static void main(String args) { // print message on screen System.out.println("Hello World"); System.out.println(" World" } } Comments: multi-line and single-line Comments: multisinglemain method Called when "java HelloWord" is run Argument: Array args hold command-line arguments $ java HelloWord first program args[0] = first args[1] = program Methods public class HelloWorld { public static void printToScreen(String message) { System.out.println(message); } public static void main(String args) { printToScreen("My First Java Program"); printToScreen(" Program" printToScreen("Hello World"); printToScreen(" World" } } public : method can be called from outside this class static : method can be called without creating an instance void : return type (what the method returns) printToScreen : name of method String message : type and name of arguments passed into method 3 Learning Through Errors Four kinds of errors Insignificant errors Compile-time errors (syntax) Run-time errors (syntax) Semantic errors (bugs) Errors 1 public class HelloWorld { public static void main(String args) { main(String // print message on screen System.out.println("Hello World"); System.out.println( World" } } Insignificant Errors Misspell or leave out words in green Program works the same Compilation Errors Misspell or leave out words in yellow Program won't compile won' 4 Errors 2 public class HelloWorld { public static void main(String args) { main(String // print message on screen System.out.println("Hello World"); System.out.println(" World" } } Runtime Errors Misspell or leave out words in green Program will compile, but won't run won' Semantic Errors Misspell or leave out words in yellow Program works, but differently Operators Arithmetic operators +, -, *, /, %(mod) i = i + 5 => i += 5 i = i + 1 => ++i or i++ i = i - 1 => --i or i---i i-+ can also be used to concatenate strings String s = "Hello" + "World " + "!"; Hello" Relational operators ==, !=, <, <=, =>, > && (AND), || (OR), ! (NOT) 5 Data Types Primitive Reference boolean (true, false) char (`a', `z') (` int (1, 100, -8) float[32bit] (3.1415) double[64bit] (3.1415) Others: byte, objects arrays String (very basic) short, long for statement for (initialization; test; increment) { // body of loop } for (int i = 0; i < 5; i++) System.out.println("loop no. = " + i); System.out.println(" 6 while / do-while statement while (condition) { // body of loop do } { // body of loop } while (condition); int i = 0; while (i < 5) { System.out.println("loop no. = " + i); i++; } if statement if (condition) { // statements } else if (condition) { // more statements } else { // else statements } int x; if (x == 1) System.out.println("x = 1"); System.out.println(" 1" else if (x == 2) { System.out.println("x = 2"); System.out.println(" 2" } else System.out.println("x > 2"); System.out.println(" 2" 7 switch statement switch (variable) { case value1: // body of value1 break; case value2: // body of value2 break; ... default: // body of default } int month; switch (month) { case 1: System.out.println("Jan"); System.out.println(" Jan" break; case 2: System.out.println("Feb"); System.out.println(" Feb" break; ... default: System.out.println("N/A"); System.out.println(" N/A" } Outline Simple java program Loops and statements Classes and objects Strings, Arrays, Vectors Inheritance Interfaces and Abstract classes Exceptions Linux commands Emacs 8 Object-Oriented language In C, sub-problems solved by functions. subIn Java, solve sub-problems by sending messages to subobjects Object has a private state and a public message protocol. protocol. Example: A Stack State: A pile of objects Protocol: Push: Pop: "add an object to the stack" stack" "remove top object and return it" it" Classes and Objects public class Rectangle { // member variables private int length; private int width; // constructor special method // initializes variables when instance is created public Rectangle (int x, int y) { length = x; width = y; } // method area() calculates the area of this rectangle public int area() { int area = length * width; return area; } } 9 Classes and Objects public static void main(String args) { Rectangle r = new Rectangle (5,2); int area = r.area(); System.out.println("area = " + area); System.out.println(" } Method Overloading public double area(int x, int y) { ... } public double area(double x, double y) { ... } => calls the first method r.area(2.5,3.5); => calls the second method r.area(2,3); Overloading constructors public Rectangle (int length, int width) { ... } public Rectangle () { ... } 10 Static and Non-Static methods Static methods No need to create an instance to call the method System.out.println("a"); System.out.println(" Math.random(); Non-Static methods (instance methods) Create an instance of the class and then call the method r.area(2,3); Static and Non-Static variables Static variables Only one copy for all instances of that class Math.PI System.out Non-Static height width variables (instance variables) Each instance has its own copy 11 Objects as reference public class Rectangle { ... /* more methods in this class */ public void print() { System.out.print("l = " + length + "; "); System.out.print(" System.out.println("w = " + width); System.out.println(" } public void swap() { int temp = length; length = width; width = temp; } } Objects as reference Output Screen rect1 length = 5 width = 2 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); 12 Objects as reference Output Screen rect1 rect2 length = 5 width = 2 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); Objects as reference Output Screen l = 5; w = 2 rect1 rect2 length = 5 width = 2 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); 13 Objects as reference Output Screen rect1 rect2 l = 5; w = 2 l = 5; w = 2 length = 5 width = 2 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); Objects as reference Output Screen rect1 rect2 l = 5; w = 2 l = 5; w = 2 length = 2 width = 5 public void swap() { int temp = length; length = width; width = temp; } Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); 14 Objects as reference Output Screen rect1 rect2 l = 5; w = 2 l = 5; w = 2 l = 2; w = 5 length = 2 width = 5 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); Objects as reference Output Screen rect1 rect2 l = 5; w = 2 l = 5; w = 2 l = 2; w = 5 l = 2; w = 5 length = 2 width = 5 Rectangle rect1 = new Rectangle (5,2); Rectangle rect2 = rect1; rect1.print(); rect2.print(); rect2.swap(); rect1.print(); rect2.print(); 15 Strings Not a primitive type, but very basic String s1 = "hello"; hello" String s2 = s1.substring(1,4); System.out.println(s2); // "ell" ell" System.out.println(s1.length()); // 5 // to check equality of strings if (s1.equals(s2)) // true statements else // false statements Other String methods at http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html Arrays Contains type a fixed number of objects of the same Usually created as any other object int digits = new int[10]; int digits = new int[10]; Can time also be created and initialized at the same int digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; No need to specify size or say "new" new" 16 Array of Objects When creating an array of objects, you must allocate the array using new allocate each object using new Rectangle rectangles = new Rectangle[5]; for (int i = 0; i < 5; i++) { rectangles[i] = new Rectangle (i,i); } By default primitive numeric: initialized to 0 Objects: initialized to null Some Array Operations To find number of elements access nth element array methods at rectangles.length To rectangles[n-1] rectangles[n- Other http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html 17 Vectors Vector contains a variable number of objects of different types is a class, so create an instance first Vector Vector v = new Vector(); v.add(new Rectangle (2,3)); v.add(new Rectangle (8,6)); System.out.println("vector size = " + v.size()); System.out.println(" Some Vector Operations To find number of elements v.size() To access nth element v.get(n-1) OR v.elementAt(n-1) v.get(nv.elementAt(n- To add elements v.add(Object o) OR v.addElement(Object o) Other vector methods at http://java.sun.com/j2se/1.5.0/docs/api/java/util/Vector.html 18 Using Java Packages To use Vector class, you need to refer to it with its full name java.util.Vector v = new java.util.Vector(); OR import the class at the very top of the file import java.util.Vector; Can also import the entire package containing it import java.util.*; Generally import java.<package name>.* // import all classes import java.<package name>.<file name> // import 1 class Package java.lang is imported by default e.g. String, Thread Outline Simple java program Loops and statements Classes and objects Strings, Arrays, Vectors Inheritance Interfaces and Abstract classes Exceptions Linux commands Emacs 19 Inheritance Important Allows and useful concept of Java to reuse code when dealing with similar objects ways Three Extending existing classes Implementing interfaces Extending existing abstract classes Base/Parent class /* base class */ public class Person { // properties of a Person private String name, ssn; private int age; public Person(String n, int a, String s) { name = n; age = a; ssn = s; } public void printPerson() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("SSN: " + ssn); } } 20 Extending a class to create Student object Student is a Person that has a major and a GPA Class Want construction to call constructor of base class <derived class> extends <base class> Use super(...) super(... Sub-class /* sub-class */ subpublic class Student extends Person { // properties for a Student only private String major; private double GPA; public Student(String n, int a, String s, String m, double g) { super(n, a, s); // call the constructor in the Person class major = m; GPA = g; } public void studentInfo() { printPerson(); // call this method in the Person class System.out.println("Major: " + major); System.out.println("GPA: " + GPA); } } 21 Modifiers public, private, protected Can pertain to class variables or methods private Can be accessed from within the class only Member variables are usually declared private and accessed by get() and set() methods public void set(String major); public String get(); protected Can be accessed from within the class and any of its subclasses public Can be accessed from outside the class Type-casting Example Vector v = new Vector (); Person p = new Person ("James", 45, 012345678); (" James" Student s = new Student("Mary", 21, 098765432, "cs", 3.8); Student(" Mary" cs" v.add(p); v.add(s); Person p1 = (Person)v.get(0); Student s1 = (Student)v.get(1); Person p2 = (Person)v.get(1); // can cast to Person too! 22 Interfaces Are used to define behavior of an object Contains signatures of methods that must be defined in the class implementing the interface Class construction <class> implements <interface> Example public interface Shape { public static final double PI = 3.14159; public double area(); } Implementing Interfaces public class Circle implements Shape { private double radius; // properties of Circle public Circle (double r) { radius = r; } public double area() { // calculate the area of a circle return PI * radius * radius; } } ----------------------------------------------public class Rectangle implements Shape { private double height, width; // properties of Rectangle public Rectangle (double h, double w) { height = h; width = w; } public double area() { // calculate the area of a rectangle return height * width; } } 23 Interfaces A class that implements an interface must implement all the methods of that interface be instantiated Cannot Shape s = new Shape (); // NOT ALLOWED!!! Can have only static member variables Abstract Classes Similar to interface, but some methods can be implemented can have member variables Methods that are not implemented should be declared abstract must be implemented in classes that extend that abstract class Abstract classes cannot be instantiated 24 Abstract Class /* abstract class */ public abstract class Employee { private String name, title; protected double salary; public Employee(String n, String t, double s) { name = n; title = t; salary = s; } public void printInfo() { // System.out.println("Name: " System.out.println("Salary: } implemented + name + ", title" + title); title" $ " + salary); public abstract void computeRaise(); } // not implemented Extending Abstract Classes public class Manager extends Employee { private static final double BONUS = 2500; public Manager(String n, String t, double s) { super(n, t, s); } public void computeRaise() { salary += salary * .05 + BONUS; } } --------------------------------------------public class Developer extends Employee { private int numOfPrograms; public Developer(String n, String t, double s, int np) { super(n, t, s); numOfPrograms = np; } public void computeRaise() { salary += salary * .05 + numOfPrograms * 25; } } 25 Outline Simple java program Loops and statements Classes and objects Strings, Arrays, Vectors Inheritance Interfaces and Abstract classes Exceptions Linux commands Emacs Exceptions A way to nicely handle an unexpected event or error a program can catch an exception can handle it as programmer wants can pass it further (method can throw an exception) Method throws exception public final void wait() throws InterruptedException; 26 try-catch Exceptions Try-catch statement try { //some methods or statements that can //result in an exception } catch(<Exception class> e) { catch(<Exception // do something to handle the exception } finally { // actions to do whether exception // occurred or not } Exceptions Only exception of type specified in catch statement gets caught and handled. exception is not caught, it propagates up the call stack to the calling method. If If it propagates up to the original call to main() and is still not caught, the program terminates with an error. 27 Exception example public class TestException { public static void main(String args) { int num, recip; // generate a random number 0 or 1 // random() returns a double, cast to int num = (int) Math.random() * 2); try { recip = 1 / num; System.out.println("The reciprocal is " + recip); } catch (ArithmeticException e) { // output the exception message System.out.println(e); } finally { System.out.println("The number was " + num); } } } Java References Java API specification http://java.sun.com/j2se/1.5.0/docs/api/index.html Java Tutorials http://java.sun.com/docs/books/tutorial/index.html 28 Some Linux Commands Linux Commands Just very few basic things that you might need Change current working directory $cd $cd [DIRECTORY] cs31a/PA1 $cd .. $cd ../../.. List the contents of a directory $ls $ls $ls [options] [FILE] cs31a 29 More Linux Commands Make directories $mkdir [options] DIRECTORY Remove files or directories $rm [options] FILENAME (irreversible! Use option -i for confirmation) Copy files and directories $cp [options] SOURCE DEST Move (rename) file and directories $mv [options] SOURCE DEST Display manual pages (very helpful) (very helpful) $man COMMAND File permissions Each file has permissions Operations: read (r), write (w), execute (x) Groups: owner, group, others To check permissions get long listing of file $ls l -rw-r-xr-rw- xr-- 1 cs31a guest 535 Sep 9 18:00 HelloWorld.java Interpreting the listing Permissions: {-} {r w -} {r - x} {r - -} => {d/-} {owner} {group} {others} {- {r {r {r {d Owner: cs31a (read & write) Group: guest (read & execute) Others: read Size: 535 bytes Last modified: Sep 9 18:00 Filename: HelloWorld.java 30 File permissions Permissions can be changed $chmod {a,u,g,o} {+,-} {r,w,x} FILENAME {+,- Example Initial permissions for file HelloWorld.java -r-xr-xr-- xr- xr-- Issue command: $chmod go-r HelloWorld.java go- Result: -r-x--x----x Other Linux commands A listing of Linux commands http://www.oreillynet.com/linux/cmd/ 31 Emacs Emacs Public domain text editor (GNU Emacs and XEmacs) Easy to use Easy text entry Cut and paste or search and replace using simple commands Creation of multiple screens Run unix shell in a window Special modes for C, Java, and other code files Allows coloring of code and automatic indentation 32 Using Emacs Start emacs typing buffer to file $emacs [FILENAME] Start Save <Ctrl-x><Ctrl-s> Ctrl- ><Ctrl Quit <Ctrl-x><Ctrl-c> Ctrl- ><Ctrl- emacs Most useful emacs commands <Ctrl-p> Ctrl<Ctrl-n> Ctrl<Ctrl-b> Ctrl<Ctrl-f> Ctrl<Ctrl-a> Ctrl<Ctrl-e> CtrlEsc 4 <Ctrl-p> Ctrl<Ctrl-d> Ctrl<Ctrl-k> Ctrl<Ctrl-y> Ctrl- move cursor to previous line move cursor to next line move cursor to backward move cursor to forward move cursor to beginning of line move cursor to end of line move cursor 4 lines up delete character at cursor cut from the cursor to end of line paste from clipboard 33 Learn More Emacs Basic emacs commands http://www.cs.colostate.edu/helpdocs/emacs.html 34 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online