1 / 66

Introduction to Java

Introduction to Java. Dr. Bay Arinze. What is Java?. Java is an objected-oriented programming language that organizes its code into classes. Each Class defines objects that combine data and methods. Classes feature: encapsulation inheritance (single), and polymorphism. Java Features.

quilla
Download Presentation

Introduction to Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Java Dr. Bay Arinze

  2. What is Java? • Java is an objected-oriented programming language that organizes its code into classes. • Each Class defines objects that combine data and methods. Classes feature: • encapsulation • inheritance (single), and • polymorphism

  3. Java Features • Java Simplicity • Java is simpler than C++, lacking • operator overloading • header and preprocessor files • pointer arithmetic • structures • unions • multidimensional arrays • templates and implicit type conversion

  4. Java Features (ctd.) • Java is Object-Oriented • Code comprises of classes. Classes may: • come from existing libraries, OR • be created by the programmer • Classes can INHERIT from other classes • only single inheritance is supported • Classes contain both data and methods (operators) • Methods can be overriden or overloaded.

  5. Java Features (ctd.) • Java is Statically Typed • object types are defined beforehand • all objects have a dynamic type though, which can be queried • Java is Compiled • compilation is into bytecodes, existing in class files • bytecodes are machine-independent

  6. Java Features (ctd.) • Java is Architecture-Neutral • Simple types do not change, unlike C++ • integers are always 32 bits • longs are always 64 bits • Java is Robust • Java programs are barred from unauthorized access to memory • Exceptions are “thrown” if the unexpected happens

  7. Java Features (ctd.) • Java is Small • Java programs can run on systems with 4MB of RAM, it has a small footprint • The Java interpreter only takes up several hundred KB • Java is Multithreaded • Java apps. will benefit if run on multiprocessor machines

  8. Java Features (ctd.) • Java Performs Garbage Collection • memory used by objects is automatically collected by a “garbage collector” program and freed for future use, avoiding ‘leaks’ • Java is Getting Faster • New code generators and JDKs are making Java faster and more equal to C++

  9. Java Features (ctd.) • Java is Secure • Pointers are not allowed in Java. Java programs can be verified before execution against Java language constraints. • Java is Extensible • Libraries in C++ and C can be interfaced with Java programs, if needed.

  10. Running Java Programs • Java Programs can be run as: • Standalone Programs, • Applets within a web browser (embedded within HTML), OR • Servlets, which are programs that are run on a remote server, with the results returned to the client. • Large programs with significant functionality are either run standalone or as servlets.

  11. Using Java Servlets “Client Side” “Server Side” Client A Java Server PUT Invoke Servlet Java Applet POST Client B Servlet 1 Servlet 2 HTML Form

  12. Creating Java Programs

  13. Features of Java • Java is very similar to C++, but • It uses the class structure exclusively, in contrast to the hybrid C++ • Java disallows the use of pointers, which allow direct access to memory locations. This enhances the client PC’s security. • Java is platform-independent, due to: • being standards-based • the use of the Java Virtual Machine (JVM).

  14. Features of Java - continued • The Java Virtual Machine allows you to “write-once”, “run-anywhere”. Write once Run anywhere JVM JVM JVM JVM

  15. Important Java Web Sites • To Download the Java Development Kit: • http://java.sun.com/j2se/1.3/ • An online Java Tutorial: • http://web2.java.sun.com/docs/books/tutorial/ • A free Java Integrated Development Environment (Netbeans): • http://www.sun.com/forte/ffj/

  16. Running a Java Program • Edit your Java program and save with a java extension e.g., “Myprog.java” • Wintel Tools: Notepad, Word, Wordpad • Go to the MS-DOS command line • using <Start> <Run> <command> • Compile your program • Type: ‘java Myprog.java’

  17. Running a Java Program (ctd.) • Debug your program • Run the standalone program • type: ‘java Myprog’ • If the Java program is an applet, embedded in an HTML file e.g., Mypage.html: • type: ‘appletviewer Mypage.html’

  18. Java Programming Basics • Statements • Control the sequence of execution, • Evaluate expressions, OR • Do nothing (the null statement) • Blocks • These are multiple or compound statements within curly braces.

  19. Expressions and Statements • Arithmetic Operators • Integer Floating Point • + add + • - subtract - • * multiply * • / integer division (quotient) • % integer division(remainder) • / floating point div.

  20. Expressions and Statements(ctd.) • Arithmetic Operators e.g., 9/2 = 4 9%2 = 1 9.0/2 = 4.5 9/2.0 = 4.5 9.0/2.0 = 4.5 • There is no exponentiation operator in Java-you must use an object from the math library.

  21. Expressions and Statements(ctd.) • Order of Expression Evaluation • Multiplication and Division first. e.g., c = 3 * 4 + 5 * 6; // 3*4 and 5*6 done first d = 9 - 3 - 2 - 1; // done left to right (((9-3)-2)-1)

  22. Expressions and Statements(ctd.) • Unary operators are performed first e.g., c = - 3 * 5 + 2 * - 4; // (-3*5) + 2*(-4)

  23. Expressions and Statements(ctd.) • Assignment • e.g., i = j; // i takes on the value of j i = j = 5; // grouped right to left i = (j = 5)

  24. Expressions and Statements(ctd.) • Increment and Decrement • The most common value to add or subtract from a variable is 1. • Can be expressed as; myVar++ //(postfix) and ++myVar //(prefix) • The order matters only if the expression is assigned to another variable.

  25. Expressions and Statements(ctd.) • Compound Assignment Operators • These include: += -= *= /= i.e., a C operator followed by the = sign. Therefore: • m += n implies m = m + n • m-= n implies m = m - n • m *= n implies m = m * n • m /= n implies m = m / n

  26. Expressions and Statements(ctd.) • Compound Assignment Operators • Also: n += 1; implies n = n+1; implies ++n; or n++; n -= 1; implies n = n-1; implies --n; or n--;

  27. Expressions and Statements(ctd.) • Relational Operators • In Java, 0 is regarded as FALSE and non-zero as TRUE (frequently 1) • Relational operators help to compare numbers. • Every relational expression evaluates to either 1 or 0. • e.g., (mySalary > 2000)

  28. Expressions and Statements(ctd.) • Relational Operators (ctd.) • Logical operators are used to compare: == is equal to != is not equal to < less than <= is less than or equal to > greater than >= is greater than or equal to

  29. Expressions and Statements(ctd.) • The IF Statementis the conditional branch operator if (<<expression>>) // there is no then, unlike Pascal { <<statement>> }

  30. Expressions and Statements(ctd.) • The IF Statement if (count > MaxCount) // no semicolon System.out.println (“\n OVERFLOW”);

  31. Expressions and Statements(ctd.) • Also; if (<<expression>>) { <<statement-1>> } else { <<statement-2>> }

  32. Expressions and Statements(ctd.) • Nested IFs if (n < 10) System.out.println (“One digit \n”); else if (n < 100) System.out.println (“Two digits \n”); else if (n < 1000) System.out.println (“Three digits\n”); else System.out.println (“Four of more”);

  33. Expressions and Statements(ctd.) • Iteration, the While construct n = 1; while (n <= 10) { System.out.println (n); n = n+1; // what does this do? }

  34. Expressions and Statements(ctd.) /* * The NumSeries class implements an application that * displays "numbers between 1 and 10. */ class NumSeries { public static void main(String[] args) { int n = 1; while (n <= 10) //evaluated before the loop { System.out.println (n); n = n+1; // what does this do? } } }

  35. Expressions and Statements(ctd.) • DO construct public int inpVar; do { inpVar = EasyInput.getInt(); //library I/O class System.out.println (inpVar); } while (n < 1000); • The expression (n < 1000) is evaluated after the execution of the loop contents.

  36. Expressions and Statements(ctd.) • FOR construct • stopping condition is evaluated before the statement. e.g., for (n =1; n <=10; n = n + 1) System.out.println (n);; // no semicolon • It is equivalent to the while/do construct

  37. Expressions and Statements(ctd.) • SWITCH and CASE Statements • This is the conditional branch operator switch (n) { case 1: System.out.println(“one person visited”); break; // necessary or case 2 etc. will execute case 2: System.out.println(“two people visited”); default: System.out.println(n + “ people visited”); break; //optional }

  38. Expressions and Statements(ctd.) • Logical Operators • && Logical AND • || Logical OR • ! Logical NOT • && true only if both operands are true (non zero) • || true if either or both are true (non zero) • ! true if dissimilar if (a<=10) && (a>=0) System.out.println(a); // 0 to 9

  39. Expressions and Statements(ctd.) • The Conditional Operator • <<expc>>?<<expt>>:<<expf>> • If expc is true the value of expt is returned, otherwise the value expf is returned. n = m >= 0 ? m : - m if m = 2 then n = 2 if m = -1 then n = 1

  40. The “Workers” Example • Create objects to represent an abstract data type, worker with attributes of first and last name. • There are 3 subclasses: managers, hourlyworkers, and commissioned workers. • Bosses get a fixed salary, plus a bonus; • Hourly workers get a “per hour” rate, plus an overtime rate when over 160 hours/month; • Commissioned workers get base pay, plus commission on sales.

  41. The “Workers” Example (ctd.) First name (data) Last Name Worker Manager Hourly Worker Commissioned Worker Salary Bonus Hourly Rate Overtime Rate Base Pay Commission Rate Calculate Manager Pay Calculate Hourly Pay Calculate Commisn. Pay (method)

  42. /* * The Worker class is a Compensation class */ public abstract class Worker { public Worker() { } ; // constructor public void SetFName(String FN) { // set the first name FirstName = FN; } public String GetFName() { // set first name return FirstName;}; public void SetLName(String LN) { // set the last name LastName = LN; } public String GetLName() { // get last name return LastName;}; private String FirstName; protected String LastName; }

  43. /* * The Manager Tax class is a compensation class for managers */ public class Manager extends Worker { // inheritance public Manager () { } ; // constructor public void SetSalary(double Sal) { // set salary Salary = Sal; } public double GetSalary() { // get salary return Salary;}; public void SetBonus(double Bon) { // set bonus Bonus = Bon; } public double GetBonus() { // get bonus return Bonus;}; public double CalcComp() { //method to calculate return (Salary+Bonus);}; // salary protected double Salary, Bonus; }

  44. // The Hourly class is a compensation class for hourly workers public class Hourly extends Worker { public Hourly () { } ; // constructor public void SetHours(double H) {Hours = H;} // set salary (inline) public double GetHours() { // get hours return Hours;}; public void SetRate(double R) { // set bonus Rate = R; } public double GetRate() { // get rate return Rate;}; public double CalcComp() { if (Hours>160) {Excess=Hours-160; Hours =160;} else Excess=0; TotalPay = (Rate*Hours) + (Rate*1.5*Excess); return (TotalPay); }; protected double Hours, Rate, TotalPay, Excess; }

  45. The Main Program (command-line style) // The Comp class computes salary for a manager public class Comp { public static void main (String[] args) { double SL, BO; // Sales Total String FN, LN; // Get User Inputs System.out.println("Enter the First Name:"); FN= EasyInput.getln(); // get first name System.out.println("Enter the Last Name:"); LN= EasyInput.getln(); // get first name System.out.println("Enter Salary: $"); SL= EasyInput.getDouble(); // get salary System.out.println("Enter Bonus: $"); BO= EasyInput.getDouble(); // get bonus

  46. The Main Program (command-line style- Part 2) . . . Manager M; M = new Manager(); //create the instance M.SetFName(FN); M.SetLName(LN); M.SetSalary(SL); M.SetBonus(BO); System.out.println("\n The Salary for " + M.GetFName() +" " + M.GetLName() + " is: $" + M.CalcComp()) ; } }

  47. Main Program Output (command-line style)

  48. The Main Program (GUI style - Part 1) import java.awt.*; // awt classes import java.awt.event.*; import javax.swing.*; // swing classes /* * The Comp3 class computes sales tax for taxable and nontaxable items */ public class Comp3 extends JFrame { Manager M = new Manager(); //create the instance private String s, FN,LN; private JLabel prompt; private JTextField text1, text2, text3, text4; private JTextArea outputArea; double SL, BO; // Sales Total …..

  49. The Main Program (GUI style - Part 2) ….. public Comp3() { super ("Tax Program"); Container container = getContentPane(); container.setLayout( new FlowLayout() ); // Get User Inputs prompt = new JLabel ("Enter the First Name:"); container.add (prompt); text1 = new JTextField (10); container.add(text1); prompt = new JLabel ("Enter the Last Name:"); container.add (prompt); text2 = new JTextField (10); container.add(text2); prompt = new JLabel ("Enter the Salary:"); container.add (prompt); text3 = new JTextField (10); container.add(text3); prompt = new JLabel ("Enter the Bonus:"); container.add (prompt); text4 = new JTextField (10); container.add(text4);

  50. The Main Program (GUI style - Part 3) ….. TextFieldHandler handler = new TextFieldHandler(); text4.addActionListener(handler); setSize( 300, 250 ); // set the window size show(); // show the window } public static void main( String args[] ) { Comp3 application = new Comp3(); application.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); }

More Related