Download presentation
Presentation is loading. Please wait.
Published byLaureen Lambert Modified over 8 years ago
1
Introduction to Java
2
2 A Brief History of OOP and Java Early high level languages –FORTRAN, COBOL, LISP More recent languages –BASIC, Pascal, C, Ada, Smalltalk, C++, Java UNIX operating system upgrades prompted the development of the C language Powerful language … but not the best intro to programming –Difficult for beginning programmers –Does not fit modern programming strategies
3
3 A Brief History of OOP and Java Simula-67 was a language which facilitated the modeling of real-world objects –New language feature called the “class” –A class was extendable through “inheritance” This was the foundation needed for Object Oriented Programming, OOP Smalltalk-80 used this concept –This is the first truly object-oriented language
4
4 A Brief History of OOP and Java The C language was extended to include “classes” and in 1983 became C++ The Java language originally conceived to control household devices using the OOP concept –Thus, was meant to be platform (or device) independent Soon this was seen as well suited for running small programs (applets) on Internet web pages –By 1995, Netscape browsers began supporting Java applets –This did much to establish Java as a major language
5
5 A Brief History of OOP and Java Note typical implementation of a program on different platforms Source program Compiler for UNIX platform Compiler for Windows Platform Compiler for Mac OS Platform Executable code for UNIX platform Executable code for Windows platform Executable code for Mac OS platform We need Platform Independence
6
6 A Brief History of OOP and Java Contrast compiler with interpreter –Compiler runs once, translates to machine code for commands of whole program –Interpreter translates one command at a time Java combines these two –Java compiler generates intermediate “bytecode” –An interpreter is developed for each platform to interpret the bytecode –Interpreter called the Java Virtual Machine or JVM This is the platform independence for which we seek
7
7 Phases of Java Programs 1.Edit the source code –filename.java 2.Compile the source code into bytecodes –filename.class 3.Load the.class file into memory –applications: stored and executed from user's own computer –applets: loaded from a computer somewhere into a browser, executed by the browser
8
8 Phases of Java Programs 4.Verify bytecodes –check for validity and potential security restrictions 5.Computer interprets bytecodes –one bytecode at a time
9
9 Program is created in the editor and stored on disk. Compiler creates bytecodes and stores them on disk. Class loader puts bytecodes in memory. Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. Phase 1 Phase 2 Phase 3 Phase 4 Phase 5 Disk Editor Compiler Class Loader Disk Primary Memory............ Primary Memory............ Primary Memory............ Bytecode Verifier Interpreter
10
10 Programming with "Ready to Program" Find the "Ready" option on the program menu or click on the "Ready" icon
11
11 Programming with "Ready to Program" An empty editor window appears
12
12 Java Programs A Java program consists of one or more classes The name of the file and the name of the class must, that is MUST have the same name Classes consist of a collection of Data items Methods Classes consist of a collection of Data items Methods A Java class with a method called main() is a Java application.
13
13 Creating a Java Application The "Ready" environment will give you skeleton or boilerplate format for programs Click on File, New, and HSA Console option A dialog box asks for the name of the class
14
14 Creating a Java Application The appropriate boilerplate text appears in the edit window – note the color coding Bold Face Java keywords Black Identifiers in Java Class library Blue Identifiers in your program Green Comments Red Quoted Strings
15
15 Creating a Java Application Fill in the necessary commands Save the program Note that a dialog box will ask you for the name Be sure to give it exactly the same name as the class Note that a dialog box will ask you for the name Be sure to give it exactly the same name as the class
16
16 Creating a Java Application To run a Java program –Press the Run button or –Press Ctrl+R or –Press F1 The console program shows a console window
17
17 Creating a Java Application Make sure to save the program before quitting –The "Ready" environment will remind you To exit the "Ready" environment –Click the X close or –Choose File, Exit or –Use Ctrl-Q
18
18 Creating a Java Application Errors in the program –Syntax errors are found for you by the compiler Dialog box shows how many errors Error line(s) highlighted Description of error given in the status bar
19
19 Introduction to Java Application Programs Java is an object oriented programming language –Uses objects to carry out the tasks –Sends messages to the objects to perform the tasks –Objects interact with each other to do the tasks –An actual object is called an instance of a class The class is the declaration of or blueprint for the object
20
20 Introduction to Java Application Programs Object oriented programs: –A collection of object interactions that solve a problem Note the similarity of this definition to the definition for a program
21
// Welcome1.java // A first program in Java import hsa.*; public class Welcome1 { public static void main (String args[]) { Stdout.println("Welcome to Java Programming"); } // end method main } // end class Welcome1 // Welcome1.java // A first program in Java import hsa.*; public class Welcome1 { public static void main (String args[]) { Stdout.println("Welcome to Java Programming"); } // end method main } // end class Welcome1 Java program Program Output Welcome to Java Programming! Comments Begins class definition for class Welcome1 Every Java program has at least one user-defined class Begins class definition for class Welcome1 Every Java program has at least one user-defined class
22
22 // Welcome1.java // A first program in Java import hsa.*; public class Welcome1 { public static void main (String args[]) { Stdout.println("Welcome to Java Programming"); } // end method main } // end class Welcome1 // Welcome1.java // A first program in Java import hsa.*; public class Welcome1 { public static void main (String args[]) { Stdout.println("Welcome to Java Programming"); } // end method main } // end class Welcome1 Java program Part of every Java application Applications begin executing at main Part of every Java application Applications begin executing at main Saving files File name is class name and.java extension Welcome1.java Saving files File name is class name and.java extension Welcome1.java Parenthesis indicate main is a method Java applications contain one or more methods Parenthesis indicate main is a method Java applications contain one or more methods
23
23 Class Declaration Syntax: class ClassName extends Object { Declarations of class members } Note the extends clause –specifies that the ClassName inherits attributes and behaviors of Object –also it will add new attributes and behaviors –ClassName is the subclass or derived class –Object is the superclass or base class
24
24 Class Members Specified between outermost set of curly braces { … } Members can be –variables that store values –methods which perform operations on the variables The main method’s declaration public static void main (String [ ] args) { a list of Java statements } First statement of the program executed is first of these statements Program terminates at last of these statements First statement of the program executed is first of these statements Program terminates at last of these statements
25
25 Java program Exactly one method must be called main Methods can perform tasks and return information –void means main returns no information –For now, mimic main 's first line public static void main( String args[] )
26
26 Declarations Example Class specification variable name for a Console object Actually creates the Console object
27
27 Calling an Object Method Example Object name Parameters Method name
28
28 Java Program Instructs computer to perform an action –Prints string of characters Object Stdout –Output object –Print to output window Method Stdout.println –Object calls method to display line of text –Argument inside parenthesis Statements must end with semicolon ; Stdout.println( "Welcome to Java Programming!" );
29
29 Java Program Java program using dialog box Note –JOptionPane object –Method call –Output dialog box Program Output
30
30 A Simple Program: Printing a Line of Text import statements –Locate the classes we use –Tells compiler to load JOptionPane from javax.swing package import javax.swing.JOptionPane; // import class JOptionPane
31
31 A Simple Program: Printing a Line of Text Call method showMessageDialog of class JOptionPane –Requires two arguments –For now, first argument always null –Second argument is string to display showMessageDialog is a static method of class JOptionPane –static methods called using class name, dot (. ) then method name JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" );
32
32 A Simple Program: Printing a Line of Text Executing these lines displays the dialog box –Automatically includes an OK button Hides or dismisses dialog box –Title bar has string Message JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" );
33
33 A Simple Program: Printing a Line of Text Calls static method exit of class System –Terminates application Use with any application displaying a GUI –Because method is static, needs class name and dot (. ) –Identifiers starting with capital letters usually class names Argument of 0 means application ended successfully –Non-zero usually means an error occurred Class System part of package java.lang –No import statement needed –java.lang automatically imported in every Java program System.exit( 0 ); // terminate the program
34
34 Sample Program Program 2.9 from textProgram 2.9 Note the features –Use of javax.swing routines –JOptionPane objects used Input dialog boxes Output message boxes –Conversion of string to integer
35
35 Sample Program Program 2.9 from textProgram 2.9 Program Output
36
36 Reads String from the user, representing the numbers to be added –Method JOptionPane.showInputDialog displays Message called a prompt - directs user to perform an action Argument appears as prompt text Then strings are converted to integers. Another Java Application: Adding Integers // read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );
37
37 Use showMessageDialog to display results "The sum is " + sum –Uses the operator + to concatenate the string literal "The sum is" and sum –Concatenation of a String and another data type Results in a new string Another Java Application: Adding Integers // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );
38
38 Different version of showMessageDialog –Requires four arguments (instead of two as before) –First argument: null for now –Second: string to display –Third: string in title bar –Fourth: type of message dialog Another Java Application: Adding Integers // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); JOptionPane.PLAIN_MESSAGE - no icon JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE
39
39 Values Held by Variables Primitive-type variables –store a value of the specified type (int, double) Reference-type variables –store an address of memory location where value is stored –thought of as a handle for the object that actually stores the values
40
40 Variable Declaration Syntax Syntax: type variable_name; or type variable_name = expression; Note –type must be known to the compiler –variable_name must be a valid identifier –expression is evaluated and assigned to variable_name location –In the first form, a default value is given (0, false, or null, depending on type )
41
41 Constants Value of object cannot be changed –for oft used math values such as PI –for values which will not change for a given program –improve readability of program –facilitate program maintenance Declaration syntax: final type CONSTANT_NAME = expression; –final is a Java keyword, makes a constant –type must be known by compiler –CONSTANT_NAME must be valid identifier –expression evaluated –should be placed at beginning of class or method
42
42 Primitive Types Also known as "simple types" –int, byte, short, and long for integer values –float and double for real/fractional values –char for letters, digits, symbols, punctuation –boolean for true and false Literals: –values of one of these types –'A', -7, 3.5, true
43
43 Reference Types Needed to represent windows, buttons, inventory, students, etc. –objects more complicated than can be represented with simple types Create a class and you have created a new type whose name is the name of the class Types created from classes are called reference types
44
44 Java Provided Reference Types Over 1600 classes already available in Java Examples: –String – for constant sequences of characters –StringBuffer – for variable sequences of characters –BigInteger – for integers of "unlimited" size –BigDecimal – for fractional numbers of "unlimited" size
45
45 Creating Reference Type Values: Constructors Primitive types use literals for their values –Meanings of literals built into compiler Reference types have no pre-existent values –Values must be created with the new operator –Example: Integer integerValue = new Integer(321); type identifier name new operator call to initializing constructor
46
46 Default Value: null Default value for reference types Screen theScreen = null; //or Screen theScreen; –value used if none is specified in declaration –indicates variable does not yet refer to a value of that type –can later be assigned values created with new
47
47 Constructing an Object Use of new to create a reference type Class provides one or more methods –called constructors Syntax: new ClassName (arguments, …) –ClassName is name of a reference type –arguments is a sequence of values separated by commas –types of arguments match those permitted by ClassName
48
48 Ready to Program I/O Classes Stdin –A non-instantiated class –Read all Java primitive data types from standard input –Possible to read several primitives from one line Stdout –This is a non-instantiated class –Output formatted data to standard output –Write data to fixed length fields and with a fixed number of decimal places.
49
49 Stdin static byte readByte () static short readShort () static int readInt () static long readLong () static float readFloat () static double readDouble () static boolean readBoolean () static char readChar () static String readString () static String readLine () –Returns the entire line of input read from the keyboard without the Return.
50
50 Stdout static void print (byte b) static void print (short s) static void print (int i) static void print (long l) static void print (float f) static void print (double d) static void print (boolean b) static void print (char c) static void print (String s) static void println (byte b) static void println (short s) static void println (int i) static void println (long l) static void println (float f) static void println (double d) static void println (boolean b) static void println (char c) static void println (String s)
51
51 Ready to Program I/O Classes View sample program which uses hsa.* classessample program Note –Primitive type objects –Import statement for hsa.* routines –Use of static functions from non-instantiated classes
52
52 Sample Problem Write a program to compute a sprinter’s average speed in kilometers per hour, given distance (meters) and time elapsed (seconds)
53
53 Program Tasks Display prompt for distance in meters Receive input from keyboard Display prompt for time in seconds Receive input from keyboard Compute kph Display titled results
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.