Java Intro 2 - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

Java Intro 2

Description:

... A set of standard classes (e.g. String) used by most implementations of the ... Includes Integer, String, StringBuffer, System, Runtime, etc. These are ... – PowerPoint PPT presentation

Number of Views:73
Avg rating:3.0/5.0
Slides: 43
Provided by: cstp1
Category:
Tags: intro | java | string

less

Transcript and Presenter's Notes

Title: Java Intro 2


1
Java Intro 2
2
Java Intro 2
  • Outline
  • Java API
  • Packages
  • Access Rules, Class Visibility
  • Strings as Objects
  • Wrapper classes
  • Static Attributes Methods
  • Hello World in detail

3
Class Libraries and the Java API
4
Java API
  • The Java programming language is defined by
  • 1. The essential features of the language
    (syntax)
  • 2. A set of standard classes (e.g. String) used
    by most implementations of the language (Java
    runs in web browsers, on servers, mobile phones,
    etc. Different implementations support different
    classes.)
  • 3. A set of classes provided with an environment
    called the Java API (application programming
    interfaces)

5
Java API
  • Most of the Java API is written in terms of
    primitive language features.
  • Some parts of the Java API are written in terms
    of the native operating system.

6
The following program uses both essential
language features and the API
  • import java.lang.String import
    java.io.FileWriter import java.io.IOException
  • public class test
  • public static void main(String
    args)
  • try
  • FileWriter fw new
    FileWriter("hello.txt")
  • String h "Hello"
    String w "World"
  • fw.write(h " "
    w) fw.close()
  • catch (IOException e)
  • System.out.println("E
    rror writing to file" e)

Qualified names
Essential Language Features
Standard classes
7
The Java API is organized into groups of related
classes and interfaces called packages.
  • Package names are dot-separated sequences of
    identifiers
  • A package defines a name space. The Java API
    (version 1.4.2) includes about 130 packages.
  • To place a class inside a package, you add a
    package statement as the first statement of the
    source file
  • package IT350program1
  • public class Student

8
Java Packages
  • A class without a package statement is in the
    default package with no package name
  • The full name of a class includes the package
    name followed by class name. For example
    java.util.ArrayList
  • javax.swing.JOptionPane

9
Java Packages
  • Most commonly used packages are
  • java.lang
  • Includes Integer, String, StringBuffer, System,
    Runtime, etc. These are fundamental classes. Some
    of the classes even have support in the compiler
    and JVM. It is not necessary to import this
    package into the programs you write. This package
    is included automatically.

10
Common Java Packages
  • java.util
  • Includes miscellaneous utility classes. Also
    includes collection classes such as Vector, Stack
    and LinkedList and other useful classes such as
    StringTokenizer andRandom.
  • java.io
  • Includes input and output classes. Two main
    categories (1) streams (byte oriented I/O), and
    (2) readers and writers (Unicode or character
    I/O).

11
Common Java Packages
  • java.awt
  • Includes original user interface control classes
    such as Button and TextField. Swing components
    have replaced some of the classes in this
    package, but most of the fundamental graphics
    classes in this package are still used.
  • javax.swing
  • The "swing" classes were added in Java 2. The
    swing package includes new classes such as
    JButton, JTextField, JApplet etc.
  • java.applet
  • Includes the Applet class and a few interfaces
    which are used to create applets.

12
Importing Java Packages
  • You can import all the classes in a package by
    using the wildcard character ()
  • import java.util. //comment which class is
    being used
  • The wildcard pertains only to class names
  • for example, import classA.classB. will only
    import classes in the classA.classB package and
    NOT classes in a classA.classB.classC package, if
    there is one
  • Or you can specify individual classes from a
    package
  • import.java.util.Vector
  • import.java.util.Date

This is the recommended style
13
Importing Java Packages
  • If you have several files for an application, you
    can use them all without writing import
    statements if they are in the same directory.
  • Import statements are only needed if we are using
    classes that are not found in package java.lang
    and are not in our own (default) package.

14
Feature Access Rules
  • Access or visibility rules determine whether a
    method or a data variable can be accessed by
    another method in another class or subclass
  • Instance variables methods are contained in
    classes, which are contained in packages.
  • To determine whether a field or method is
    accessible, Java starts by determining whether
    its containing package is accessible and then
    whether its containing class is accessible.

15
Feature Access Rules
  • public
  • feature is accessible to all other classes
  • protected
  • feature is public to subclasses and to other
    classes within the same package and any
    subclasses that are in other packages private to
    classes outside the package
  • private
  • accessible to methods only within the class not
    even subclass methods have access)
  • access type is omitted (default)
  • feature is visible to all classes within same
    package (package visible) not to subclasses
  • same as public for single-package applications

16
Access Example
  • public class Person
  • private String ssn //the only really private
    feature
  • //the following attributes are public from the
  • //perspective of other classes in the same
    package
  • public String name
  • protected String address
  • int age

17
Visibility
  • Making a class public does not have any effect on
    the visibility of its features.
  • Private features are still private
  • protected features are still protected

18
Class Visibility
  • Class access is public by default accessible if
    its package is accessible accessible only within
    its package.
  • Declaring a class public means if the package
    the class belongs to is imported into code
    belonging to some other package, then all public
    attributes and methods are public in the other
    package. (e.g. public class Vector in java.util)
  • Features of a public class still have the same
    meaning. Private feature is still private , etc.

19
Class Visibility
  • If access designation is omitted from the class
    declaration, the class is package visible. The
    class is not visible from outside the package and
    cannot be referenced or instantiated from client
    code within another package.
  • Class visibility is a form of encapsulation at
    the package level.
  • Two or more classes can be placed in a single
    .java file (not recommended), but only one of the
    classes can be public. The public classs name
    must match the name of the file.

20
Revisiting Strings as Objects
  • Strings are created in two ways
  • String name Judy
  • String name new String(Judy)
  • in the first example, the string is stored in a
    literal pool which is shared if you use the
    same String literal in different places in the
    code.
  • in the second case, a different instance of the
    string is created with every call to new, even if
    there is already a string with the same literal
    value in the application.

21
String class methods
  • Besides length(), there are other useful methods
    in the String class
  • String s banana split
  • if(s.startsWith(ba)) //evaluates to true
  • if(s.endsWith(it)) //evaluates to true
  • int i s.indexOf(nan) //i will equal 2
  • String j it
  • int k s.indexOf(j) //k will equal 10
  • System.out.println(s.indexOf(spil)
    //prints -1

22
String class methods
  • String replace(char old, char new)
  • String s x1 x2 x3
  • String y s.replace(x, y)
  • String s is unchanged String y is y1 y2 y3
  • String substring(int)
  • String s banana split
  • String t s.substring(7) //t is now
    reference to split
  • String substring(int, int)
  • String s banana split
  • String t s.substring(9,12) //t is reference to
    lit

23
String objects
  • Strings are immutable. When you think you are
    modifying a String object by concatenating
    another String object to it, you are actually
    creating a new string object -- making the old
    String object inaccessible by reference.
  • String s banana
  • s s split
  • s
  • no longer
    accessible
  • s

banana
bananasplit
24
Wrapper Classes
  • A wrapper class is provided for each primitive
    data type.
  • Wrappers encapsulate methods that can be used to
    perform certain data conversions.
  • The wrapper class integer has a method parseInt()
    that converts a String into an int
  • int x parseInt(350)
  • parseInt() is used to handle numeric input
  • Wrapper classes include Boolean, Character, Byte,
    Short, integer,Long, Float and Double

25
Wrapper Classes Storing integers in a Vector
object
  • Simple data types cannot be stored in a container
    object because containers hold Object type
    elements, and simple data types are not Object
    types.
  • To store integers in a Vector object, we build an
    object wrapper around each int value and add the
    object wrapper to the vector instead of the int
    itself.

26
Wrapper Classes Storing integers in a Vector
object
  • //code by Jacquie Barker, modified by Judy
    Mullins
  • import java.util. //for Vector
  • public class VectorTest
  • public static void main(String args)
  • Vector v new Vector() //container of
    integers
  • for (int i 0 i
  • Integer intWrapper new Integer(i)
  • v.add(intWrapper)
  • for (int i 0 i
  • Integer intWrapper (Integer) v.elementAt(i)
  • Sysem.out.println ( intWrapper.intValue() )

27
Wrapper Classes
  • int Integer.parseInt(String) converts the String
    argument to an int if the argument is a valid
    integer, else a NumberFormatException is thrown
  • public class integerTest
  • public static void main(String args)
  • String ints 123, 456,hello
  • try
  • for (int i0 i
  • int test Integer.parseInt(intsi)
  • System.out.println(test converted
    ok)
  • catch (NumberFormatException e)
  • System.out.println(intsI is invalid
    integer)

28
Wrapper Classes
  • String Integer.toString(int) turns an integer
    into a String
  • int j 9
  • String s Integer.toString(j) //s equals 9
  • Easier way to do the same thing
  • int j 9
  • String s j //concatenate empty string
    with int.
  • //The int will automatically be
  • // changed to a String

29
Static Attributes
  • A static attribute is shared by all instances of
    a class. It does not belong to any one instance
    or object of the class for which it is declared.
  • Counters are often declared static
  • public class Student
  • public static int totalStudentCount 0 //opt.
    Initialization
  • When any object of the class modifies a static
    attribute, the new value applies to all objects
  • Student s1 new Student()
  • Student s2 new Student()
  • s1.totalStudentCount // 1 student for the
    class
  • s2.totalStudentCount // now 2 students

30
Static Attributes
  • The value of the static attribute can be accessed
    by the class using the dot notation
  • Student.totalStudentCount
  • System.out.println(Student.totalStudentCount)

Class name
Class name
31
Static Attributes
  • Static attributes are also called class
    variables
  • Common usage to make data globally available to
    an application
  • Class variables are uncommon more common is to
    define constants
  • public static final double PI
    3.14159265358979323846

32
Static Methods
  • A static method (class method) can be invoked on
    either an instance or a class as a whole.
  • public class Student
  • public static int totalStudentCount
  • public static void incrementTotalCount()
  • totalStudentCount)
  • //in main program
  • Student.incrementTotalCount()
  • Student s1new Student()
  • s1.incrementTotalCount()

33
Static Methods
  • A static method can only access static attributes
  • The this keyword has no meaning within a static
    method
  • we cant know for sure that there will be an
    instance of an object to self-reference

34
Hello World Revisited
  • Details about this little program

35
Hello World Revisited
  • / 1 / // My first Java program
  • / 2 / import java.lang. //optional import
  • / 3 / public class HelloWorld
  • / 4 /    public static void main(String
    args)
  • / 5 /         System.out.println("Hello
    World!")
  • / 6 /   
  • / 7 /
  • Note Line numbers are NOT part of the java
    program.

36
Revisiting Hello World
  • There can be only one public class (with main)
    per source file.
  • The name of the source file must match the public
    class declared in the source file.
  • You can declare multiple classes in a single file
    but only one can be public. The other classes are
    not visible outside of the current package.
  • Packages are units of organization for classes.

37
Revisiting Hello World
  • The program fragment above declares the class
    HelloWorld. All data structures and algorithms
    must live inside a class. (Some statements such
    as import can, of course, be used outside of a
    class declaration.)
  • In Java everything must be defined and declared
    within a class
  • import  java.io. ... public class Misc
      private static int x  public
    static void f() ...

38
Revisiting Hello World
  • Line 4 declares an entry point for the class. The
    signature of the entry point must follow the
    prototype
  • public static void main(String args)
  • Typing java at a command line starts the
    interpreter. When you pass the name of a class to
    the interpreter it automatically calls the entry
    point function defined in the class.

39
Revisiting Hello World
  • The class containing the main() method is
    considered the application driver. The class
    name must match exactly (i.e. case) the name of
    the external file containing the source code of
    the class.
  • The main() method has two responsibilities
  • 1. Instantiate the core objects needed for the
    program
  • 2. Display the start-up window of the GUI of an
    application, if it has one

40
Revisiting Hello World
  • Why is the main() method declared static?
  • A static method can be invoked on a class even if
    no instance of the class has been created.
  • When the JVM loads the class with the main
    method, no objects exist yet because the main()
    method, which starts the instantiation process,
    hasnt been executed yet! After executing main(),
    the JVM loads additional classes as needed when
    referenced by the application.

41
Revisiting Hello World
  • The statement
  • System.out.println("Hello World!")
  • prints Hello World! to the standard output.
    More formally, it calls the method println() on
    the object out declared in the class System.
    System is a class in the Java API-- in the
    java.lang package.
  • The method println() generates a carriage return
    after the argument is displayed on the screen.
    The method print() does not.

42
Resources for further reading
  • About Java language features
  • http//java.sun.com/docs/white/langenv/
  • About Java technology
  • http//java.sun.com/docs/books/tutorial/getStarted
    /intro/definition.html
  • Quick introduction to Java programming
  • http//java.sun.com/docs/books/tutorial/getStarted
    /index.html
  • All the language fundamentals
  • http//java.sun.com/docs/books/tutorial/java/index
    .html
  • Many more links on the course web page
Write a Comment
User Comments (0)
About PowerShow.com