SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
Lesson 2 – Basic Java Concepts                                                                           Java™ Programming




                      2
                      0
                                                                               Basic Java Concepts




                 JPROG2-1          Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Schedule:                     Timing                 Topic
                              45 minutes Lecture
                              15 minutes Lab
                              60 minutes Total




Copyright © 2003 Jeremy Russell & Associates                                                                Lesson 2 - Page 1 of 18
Java™ Programming                                                                               Lesson 2 – Basic Java Concepts



                                                                                                           Objectives


                  • After completing this lesson, you will have
                    an understanding of:
                          – Important elements of a Java program
                          – Basic Java language syntax
                          – .java and .class file structures
                          – How to run a Java application




                  JPROG2-2       Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Objectives
Lesson 2 introduces key elements of the language for Java class creation.
Basic syntax is also demonstrated, together with coding and documentation standards.
The JDK is described in more detail to allow creation, compilation and running of simple Java
programs.




Page 2 of 18 – Lesson 2                                                                        Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                            Java™ Programming



                                                                                                         Sun’s JDK


                 • The Sun JDK includes "standard" classes
                 • The language package is in classes.zip
                 • Other packages included are:
                      – Windowing                                     (java.swing)
                      – Applet                                        (java.applet)
                      – Streams I/O                                   (java.io)
                      – Network comms                                 (java.net)



                 JPROG2-3          Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Sun’s JDK
The Java Developers Kit (JDK) (introduced in Lesson 1) includes a standard set of classes that
provide the core functions of Java. The language package (java.lang) contains the lowest level of
required classes. For example, java.lang includes the Object class, the foundation of all user
defined (and many Java defined) classes.
The JDK includes several packages (groups of classes) that share common definitions. Packages also
share a name space, the scope of internal definitions within the package. Different packages can
contain objects of the same name – the fully qualified object name includes the package name for
uniqueness. To simplify coding, a package can be imported into a class (discussed later), which
removes the requirement to fully name packaged objects.

Included packages
Some examples of included packages are:
    ƒ    java.lang            Object, String, Thread, System, Math
    ƒ    javax.swing          Window, Button, Menu, Font, Border
    ƒ    java.applet          Applet, AudioClip,
    ƒ    java.io              InputStream, OutputStream, File, StreamTokenizer
    ƒ    java.net             Socket, URL, ContentHandler


Further information should be obtained from the JavaSoft website, from where the documentation can
be browsed or downloaded. The download is an (approximately) 21.5mb ZIP file, which can then be
unzipped into a set of HTML pages for use in any browser.
Alternatively, if you have access to a permanent Internet connection, the latest documentation can be
browsed online.
The URL for documentation is http://java.sun.com/j2se/1.3/docs.html.



Copyright © 2003 Jeremy Russell & Associates                                                                 Lesson 2 - Page 3 of 18
Java™ Programming                                                                             Lesson 2 – Basic Java Concepts



                                                                  Java naming conventions


                  •    Files                     HelloWorld.java
                  •    Classes                   HelloWorld.class
                  •    Methods                   main, showMessage
                  •    Variables                 employeeName, birthDate
                  •    Constants                 RETIREMENT_AGE


                      !! Everything in Java is case sensitive !!


                  JPROG2-4     Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Java naming conventions
All names and keywords in Java are case-sensitive.

Files
Source code are stored in files with the .java extension and must use the class name within the file as
the prefix of the file name itself. The compiled classes are stored in a file with a .class suffix – the
prefix must again be the same as the name of the initial class held within the file.

Classes
Class names should be nouns. The first letter of each word in the class name should be capitalised.
For example, OrderLine.

Methods
The name of each method is typically a verb. The first letter of the method name should be
lowercase; the first letter of subsequent words should be capitalised.
For example, getClientName().

Variables
A variable name should be short but descriptive, avoiding where possible the common variable names
like i and j etc.. Use the same mixed case as for method names.
For example, employeeTaxCode.

Constants
A constant should be declared with an all upper-case name, using underscores to separate internal
words.
For example, STANDARD_VAT_RATE.




Page 4 of 18 – Lesson 2                                                                      Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                                Java™ Programming



                                                                                       Java class definition
                                                                                               package myPackage;
                                                                                               public class Employee {
                 •   Package Name                                                                private String employeeName;
                                                                                                 private float salary;
                 •   Access modifier                                                             public Employee() {
                                                                                                   employeeName = "Unknown";
                 •   Class keyword                                                             }
                                                                                                   salary = 0;


                 •   Variables
                                                                                                     public class Employee {
                      – Instance, Class, Local variables                                       ...
                                                                                               Employee e1 = new Employee();
                 • Methods                                                                     Employee e2 = new Employee();
                                                                                               ...
                      – Instance methods
                      – Class methods
                 • Constructors                                                                          e1      e2

                 JPROG2-5          Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Java class definition
Classes are the encapsulated definition of properties (variables) and subroutines (methods) to operate
on those properties. The class definition can be used as a model or blueprint for creating
(instantiating) actual examples of the class.
The behaviour of the class is defined as methods that operate on the attributes of the class. Attribute
values are stored as variables, either for a specific instance of the class (instance variables) or as
variables shared by all instances of the class (class variables).
The class definition includes the following components:
ƒ Package name                Name of the package where this class belongs – discussed later.
ƒ Access modifier             Keyword to specify how external access to this class is managed. Options
                              include public or private.
ƒ Class keyword               A mandatory keyword.
ƒ Instance variables          Variables (constants) defined outside of a method and available to all
                              methods in the class.
ƒ Class variables             Variables (constants) defined with the static keyword – a single instance
                              of the variable is created which is shared by all instances of the class.
                              Instance variables are created when the class is loaded initially and can be
                              set and accessed even before new instances of the class are created.
ƒ Local variables             Variables (constants) defined inside a method. The variable scope is
                              inside the method where it is declared.
ƒ Instance methods            Functions (subroutines) that operate on instances of the class.
ƒ Class methods               Functions (subroutines) that operate on class variables of the class.
ƒ Constructors                Methods that have the same name as the class and are automatically called
                              to create new instances of the class (initialise instance variables).




Copyright © 2003 Jeremy Russell & Associates                                                                        Lesson 2 - Page 5 of 18
Java™ Programming                                                                                Lesson 2 – Basic Java Concepts



                                                                                                              Packages
                                                                                                   package com.JeremyRussell;
                                                                                                   public class Employee {
                  • Java uses packages                                                               ...
                                                                                                                .
                          – to group related classes                                                            .

                          – to reduce namespace                                                         ROOT Directory
                            conflicts
                  • Package conventions                                                                       com

                          – reverse domain name
                                                                                                        JeremyRussell
                          – runtime directories follow
                            package names                                                                source.java



                  JPROG2-6        Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Packages
Java uses “packages” to both group related classes and ensure that potential namespace conflicts are
minimised.
Each class resides in a package – if the class does not include a package specifier, the class is a
member of the default package. Each Java class is fully qualified by the fully qualified class name,
which consists of the package name and the class name, concatenated with dot notation. For example,
java.lang.Object class is the fully qualified name of the Object class. The java.lang package is
included in every java class by default.
One generally accepted convention for package naming is to use the author’s internet domain name as
the initial components of the package name. Furthermore, the initial portion of the package name is
often uppercased.
For example, packages created for use by Microsoft, with their domain name of ‘microsoft.com’,
would typically have a package name of “COM.microsoft”. If Microsoft were to create a class called
“Customer” for their “licence” subsystem, the fully qualified class name would be
“com.Microsoft.licence.Customer”.
Package names of “java”, “javax” and “sun” are reserved for use by Sun.




Page 6 of 18 – Lesson 2                                                                         Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                Java™ Programming


Class files at runtime
The root directory for the class hierarchy must also be identified in the environment variable
CLASSPATH    for both Windows and UNIX systems. This environment variable can contain a list of
directories to be searched at runtime (by java) for the initial directory containing the class hierarchy.
At runtime, compiled Java classes must appear in a directory tree structure that corresponds to their
package name. The compiler can be instructed to create the directory hierarchy by using the
command line option –d, as below
    SET CLASSPATH=C:Course
    javac –d . Source.java

If Source.java contains the following code:
    package practice;
    public class Question1 {
    ...

the compiled Source.class file must appear in the file C:CoursepracticeQuestion1.class.
Compiled class files must be placed in a directory that matches their package name.
Microsoft’ s licence system, customer class must be stored for a Windows operating system, in
“ ..commicrosoftlicenceCustomer.class” or, for a UNIX system, the directory
“ ../com/microsoft/licence/Customer.class”
To execute this class, use this command:
    java practice.Question1

Note that since CLASSPATH has been set already, this command can be invoked from any directory
on your system.




Copyright © 2003 Jeremy Russell & Associates                                        Lesson 2 - Page 7 of 18
Java™ Programming                                                                               Lesson 2 – Basic Java Concepts



              Access modifier                                                                          Example class
                                                     Class declaration
              public class HelloWorld {
                                                            Instance
                   private String employeeName;
                   public static void main(String[] args) { Variable
                       System.out.println("Hello, World");
           Class       employeeName = "Jeremy";
           Method      showMessage("Employee:");
                   }
                               Instance Method
                          static void showMessage(String msg) {
                              int i;
                                                                                                             Instance
                              System.out.println(msg + " " +                                                 Variable
                                employeeName);
                          }
                 }
                  JPROG2-6       Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Java class definition
Classes are the encapsulated definition of properties (variables) and subroutines (methods) to operate
on those properties. The class definition can be used as a model or blueprint for creating
(instantiating) actual examples of the class.
The behaviour of the class is defined as methods that operate on the attributes of the class. Attribute
values are stored as variables, either for a specific instance of the class (instance variables) or as
variables shared by all instances of the class (class variables).
The class definition includes the following components:
ƒ Access modifier             Keyword to specify how external access to this class is managed. Options
                              include public or private.
ƒ Class keyword               A mandatory keyword.
ƒ Instance variables          Variables (constants) defined outside of a method and available to all
                              methods in the class.
ƒ Class variables             Variables (constants) defined with the static keyword – a single instance
                              of the variable is created which is shared by all instances of the class.
                              Instance variables are created when the class is loaded initially and can be
                              set and accessed even before new instances of the class are created.
ƒ Local variables             Variables (constants) defined inside a method. The variable scope is
                              inside the method where it is declared.
ƒ Instance methods            Functions (subroutines) that operate on instances of the class.
ƒ Class methods               Functions (subroutines) that operate on class variables of the class.
ƒ Constructors                Methods that have the same name as the class and are automatically called
                              to create new instances of the class (initialise instance variables).




Page 8 of 18 – Lesson 2                                                                        Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                           Java™ Programming



                                                                                                         Methods


                 • Methods are defined within a class
                 • Method signature includes
                      – Access modifier
                      – Static keyword
                      – Arguments
                      – Return type
                 • Method body includes statements
                   public static int getAge(int customer)
                   { ... }

                 JPROG2-7          Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Methods
Each method is defined within a class, and can be equivalent to a subroutine, a procedure or a
function in other programming languages.
For each method, the following forms part of the definition:
ƒ Access modifier             Keyword to specify how external access to this method is managed.
                              Options include:
                              ƒ public        - accessible from other classes
                              ƒ private       - not accessible outside this class
                              ƒ protected - accessible from sub-classes of this class
                              ƒ default       - accessible from other classes in the same package
                                              (the default keyword does not appear but is assumed).
ƒ Static keyword              A mandatory keyword for class methods.
ƒ Return type                 The data type returned by this method. If the method does not return a
                              value, the data type void must be used.
ƒ Method name                 The name of the method.
ƒ Arguments                   A comma separated list of datatypes and names passed as parameters to
                              this method.
ƒ Method body                 Java statements that provide the functionality of this method.
Unless a method does not return a value (and has a signature specifying a void return type), the
method must end with a ‘return’ statement to provide the value to the calling method. A method
may have several exit points (return statements) – each statement must return the same type.

main method
Executable classes (applications) must have a “ main” method defined. This method is the entry point
to the application. Other classes do not need a main method but may have one defined for use as a
testing entry point. The main method signature is always:
    public static void main(String[] args){ ... }


Copyright © 2003 Jeremy Russell & Associates                                                                Lesson 2 - Page 9 of 18
Java™ Programming                                                                            Lesson 2 – Basic Java Concepts



                                                                                                    Code blocks


                  •   Method body consists of a code block
                  •   Code blocks are enclosed in braces { }
                  •   Code blocks can be nested
                  •   Use code blocks for {
                       – Class declarations                                         // Get cust, return age
                                                                                    Customer c =
                       – Method declarations                                              getCust(customer);
                       – Nesting other blocks                                       return c.getAge();
                                                                               }


                  JPROG2-8    Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Code blocks
The body of a method appears as a code block, a set of Java statements enclosed within brace
characters ({ and }).
Code blocks can be nested to form compound statements, often within conditional or loop constructs.
Variables defined within a code block have a scope of that code block only (temporary variables).
A temporary variable that is defined with the same name as a variable with a higher scope will mask
the definition of the higher scoped variable – this is not good practice for code clarity.




Page 10 of 18 – Lesson 2                                                                    Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                                    Java™ Programming



                                                                                                               Statements


                • Statements are terminated                                                        {
                  with semicolon                                                                         if (age > 65)
                                                                                                             pension = true;
                • Compound statements                                                                    else {
                  contained within a code                                                                  pension = false;
                  block                                                                                      calculateTax();
                                                                                                         }
                • Braces used for control                                                                createPaySlip();
                  flow blocks                                                                            ...
                                                                                                   }



                 JPROG2-9          Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Statements
Java statements are always terminated with a semi-colon.
Statements may be Java statements (variable declaration, assignment, logic statements) or references
to methods within the same or another class.
Compound statements are contained within a code block, delimited by braces.
Multiple statements can appear on a single line of source code, provided that each statement is
delimited with a semi-colon. This is not good practice for coding clarity reasons and should be
avoided whenever possible.




Copyright © 2003 Jeremy Russell & Associates                                                                          Lesson 2 - Page 11 of 18
Java™ Programming                                                                             Lesson 2 – Basic Java Concepts



                                                                                                           Variables


                  •   Must be defined before use
                  •   Variables can be primitives or objects
                  •   Variable declarations appear one per line
                  •   Should be initialised wherever possible
                  •   Can be declared as :
                       – Instance variables (start of class)
                       – Method variables (start of code block)
                       – Temporary (within a code block)

                  JPROG2-10    Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Variables
The Java language is strongly typed, meaning that variables must be defined before they are
referenced.
For code clarity, a declaration should appear on a separate line in the source file. Multiple variables
of the same type can be declared (and initialised) using a single statement.
Declarations can appear at the beginning of a code block or within a code block (for temporary
variables).
Each variable should be initialised on declaration wherever possible. Primitive (built-in) variables
and class variables are automatically initialised to an appropriate value (as described later). Object
variables (user-defined) may be declared without initialisation values.




Page 12 of 18 – Lesson 2                                                                     Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                            Java™ Programming



                                                                                                         Comments

                public class HelloWorld { // comment to end of line
                     private static String employeeName;
                     /* multiline
                        comment */
                     public static void main(String[] args) {
                         System.out.println("Hello, World");
                         employeeName = "Jeremy";
                         showMessage("Employee:");
                     }
                     /** Documentation comment */
                     static void showMessage(String msg) {
                         System.out.println(msg + " " +
                     employeeName);
                     }
                }
                 JPROG2-11         Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Comments
Code should be commented wherever possible, to ensure clarity for the original developer and for
developers that may subsequently work on or use the class.
Comments can be specified in several ways:
ƒ   Using //                  All characters after // are treated as comments by the compiler.
ƒ   Using /* and */           A multi-line comment is enclosed between a /* and */ pair
ƒ   Using /** and */          The /** prefix is used by the Javadoc utility for generating standardised
                              documentation in HTML format (discussed later).




Copyright © 2003 Jeremy Russell & Associates                                                                 Lesson 2 - Page 13 of 18
Java™ Programming                                                                               Lesson 2 – Basic Java Concepts



                                                                      Compiling an application


                     $ javac HelloWorld.java
                     $ HelloWorld.java:12: ’}’ expected
                     }
                         ^
                     1 error
                     $ vi HelloWorld.java
                     $ javac HelloWorld.java
                     $ _

                  JPROG2-12      Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Compiling an application
To compile a Java source file, use the JDK Java compiler “ javac.exe” .
Change to the directory containing the “ .java” file to be compiled, and run the compiler as shown
above. Remember that the name of the source file is case-sensitive for the compiler, whichever
operating sytem you are using for the compilation.
Errors in the code that prevent compilation will be reported by the compiler immediately.
If there are no errors, the compiler will create a class file in the same directory as the source file.




Page 14 of 18 – Lesson 2                                                                       Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                                                           Java™ Programming



                                                                              Running an application


                    $ java HelloWorld
                    Hello, World
                    Employee: Jeremy                                             JVM                     HelloWorld


                                                                                         HelloWorld
                    $ _

                                                                                          java.lang



                                                                                                          java.lang




                 JPROG2-13         Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Running an application
To compile a Java source file, use the JDK Java runtime “ java.exe” .
Change to the directory containing the “ .class” file to be execute, and invoke the Java runtime as
shown above. Remember that the name of the class file is case-sensitive for the runtime, whichever
operating sytem you are using for execution.
The java.exe program loads the class and verifies the integrity of the bytecodes before converting the
bytecodes into machine code and executing the main() method. The JVM is started to manage the
processing. Any other classes referenced in the application will be loaded into the JVM’ s memory
space as required.




Copyright © 2003 Jeremy Russell & Associates                                                                 Lesson 2 - Page 15 of 18
Java™ Programming                                                                            Lesson 2 – Basic Java Concepts



                                                                                           Lesson Summary


                  • In this lesson, you learnt:
                       – Important elements of a Java program
                       – Basic Java language syntax
                       – .java and .class file structures
                       – How to run a Java application




                  JPROG2-14   Copyright © Jeremy Russell & Associates, 2003. All rights reserved.




Page 16 of 18 – Lesson 2                                                                    Copyright © 2003 Jeremy Russell & Associates
Lesson 2 – Basic Java Concepts                                              Java™ Programming


Practice 2
1) Using the notes in this lesson as a guide, define the following terms:
    a) Class:


    b) Instance variable:


    c) Instance method:


    d) Temporary variable:


2) Examine the following code example and answer the questions below:
    public class HelloWorld {
       private String employeeName;
       private int age;
       private float salary;

         public static void main(String[] args) {
            System.out.println("Hello, World");
            employeeName = "Jeremy";
            showMessage("Hello, from a method");
         }

         static void showMessage(String msg) {
            int messageCode = 0;
            int messagePriority = 0;
            System.out.println(msg + " " +    employeeName);
         }
    }

    a) What is the class name?
    b) What are the method names?
    c) What are the names of the instance variables?
    d) What are the names of the method variables?




3) List four components of the JDK.
    a)
    b)
    c)
    d)




Copyright © 2003 Jeremy Russell & Associates                                   Lesson 2 - Page 17 of 18
Java™ Programming                                       Lesson 2 – Basic Java Concepts




                           This page intentionally left blank




Page 18 of 18 – Lesson 2                                Copyright © 2003 Jeremy Russell & Associates

Weitere ähnliche Inhalte

Was ist angesagt?

Java session02
Java session02Java session02
Java session02Niit Care
 
Mechanical Designing 6 Months
Mechanical Designing 6 MonthsMechanical Designing 6 Months
Mechanical Designing 6 MonthsPratima Parida
 
GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)HarshithaAllu
 
Presenter manual core java (specially for summer interns)
Presenter manual  core java (specially for summer interns)Presenter manual  core java (specially for summer interns)
Presenter manual core java (specially for summer interns)XPERT INFOTECH
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with javaMohamed Fathy
 
LearnSQL: Online Learning and Evaluation System for Databases Courses
LearnSQL: Online Learning and Evaluation System for Databases CoursesLearnSQL: Online Learning and Evaluation System for Databases Courses
LearnSQL: Online Learning and Evaluation System for Databases CoursesCarme Quer
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Hitesh-Java
 
Xm Lquickref
Xm LquickrefXm Lquickref
Xm LquickrefLiquidHub
 
Xml Syntax Quick Reference
Xml Syntax Quick ReferenceXml Syntax Quick Reference
Xml Syntax Quick ReferenceLiquidHub
 
Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)XPERT INFOTECH
 
Object oriented concepts with java
Object oriented concepts with javaObject oriented concepts with java
Object oriented concepts with javaishmecse13
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Hitesh-Java
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructorsRavi_Kant_Sahu
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
10 generics a-4_in_1
10 generics a-4_in_110 generics a-4_in_1
10 generics a-4_in_1arasforever
 

Was ist angesagt? (20)

Java session02
Java session02Java session02
Java session02
 
Mechanical Designing 6 Months
Mechanical Designing 6 MonthsMechanical Designing 6 Months
Mechanical Designing 6 Months
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)
 
Presenter manual core java (specially for summer interns)
Presenter manual  core java (specially for summer interns)Presenter manual  core java (specially for summer interns)
Presenter manual core java (specially for summer interns)
 
Php
PhpPhp
Php
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with java
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
LearnSQL: Online Learning and Evaluation System for Databases Courses
LearnSQL: Online Learning and Evaluation System for Databases CoursesLearnSQL: Online Learning and Evaluation System for Databases Courses
LearnSQL: Online Learning and Evaluation System for Databases Courses
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Xm Lquickref
Xm LquickrefXm Lquickref
Xm Lquickref
 
Xml Syntax Quick Reference
Xml Syntax Quick ReferenceXml Syntax Quick Reference
Xml Syntax Quick Reference
 
Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)
 
What is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK TechnologiesWhat is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK Technologies
 
Object oriented concepts with java
Object oriented concepts with javaObject oriented concepts with java
Object oriented concepts with java
 
Obj c
Obj cObj c
Obj c
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
10 generics a-4_in_1
10 generics a-4_in_110 generics a-4_in_1
10 generics a-4_in_1
 

Andere mochten auch

Andere mochten auch (20)

Brand design HQ, dal logo al coordinato
Brand design HQ, dal logo al coordinatoBrand design HQ, dal logo al coordinato
Brand design HQ, dal logo al coordinato
 
Paws Communications Final Very
Paws Communications Final VeryPaws Communications Final Very
Paws Communications Final Very
 
In-House Tips and Tricks: Pubcon 2015
In-House Tips and Tricks: Pubcon 2015In-House Tips and Tricks: Pubcon 2015
In-House Tips and Tricks: Pubcon 2015
 
Intro Ppt
Intro PptIntro Ppt
Intro Ppt
 
Smart Networking
Smart NetworkingSmart Networking
Smart Networking
 
Natjecaj Za Naj Pijanca 2008
Natjecaj Za Naj Pijanca 2008Natjecaj Za Naj Pijanca 2008
Natjecaj Za Naj Pijanca 2008
 
R E S U M E W R I T I N G
R E S U M E  W R I T I N GR E S U M E  W R I T I N G
R E S U M E W R I T I N G
 
Lesson Plan Ict Course Anita G.
Lesson Plan Ict Course  Anita G.Lesson Plan Ict Course  Anita G.
Lesson Plan Ict Course Anita G.
 
SMiB09 Neville Hobson
SMiB09 Neville HobsonSMiB09 Neville Hobson
SMiB09 Neville Hobson
 
The Earth
The EarthThe Earth
The Earth
 
Chimps Are Us
Chimps Are UsChimps Are Us
Chimps Are Us
 
NRK Mobilapps At RDE March 2010
NRK Mobilapps At RDE March 2010NRK Mobilapps At RDE March 2010
NRK Mobilapps At RDE March 2010
 
Clearwater Analytics SEC Comment Letter
Clearwater Analytics SEC Comment LetterClearwater Analytics SEC Comment Letter
Clearwater Analytics SEC Comment Letter
 
Teens' Top Ten
Teens' Top TenTeens' Top Ten
Teens' Top Ten
 
Top 10 Power Point Answers
Top 10 Power Point AnswersTop 10 Power Point Answers
Top 10 Power Point Answers
 
I Business Promoter
I Business PromoterI Business Promoter
I Business Promoter
 
quarto stato
quarto statoquarto stato
quarto stato
 
Design considerations for the 25m Nigeria radio telescope by Edward Omowa.
Design considerations for the 25m Nigeria radio telescope by Edward Omowa.Design considerations for the 25m Nigeria radio telescope by Edward Omowa.
Design considerations for the 25m Nigeria radio telescope by Edward Omowa.
 
School Of Violence
School Of ViolenceSchool Of Violence
School Of Violence
 
Yiftah
YiftahYiftah
Yiftah
 

Ähnlich wie 0 E158 C10d01

Ähnlich wie 0 E158 C10d01 (20)

Java 7
Java 7Java 7
Java 7
 
cs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxcs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptx
 
core java syllabus
core java syllabuscore java syllabus
core java syllabus
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
 
Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8Java syntax-and-grammars-oct8
Java syntax-and-grammars-oct8
 
Core Java
Core JavaCore Java
Core Java
 
Java basics
Java basicsJava basics
Java basics
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
 
Features of java technology
Features of java technologyFeatures of java technology
Features of java technology
 
Java
JavaJava
Java
 
4장. Class Loader
4장. Class Loader4장. Class Loader
4장. Class Loader
 
Basic Object Oriented Programming in JAVA.pptx
Basic Object Oriented Programming in JAVA.pptxBasic Object Oriented Programming in JAVA.pptx
Basic Object Oriented Programming in JAVA.pptx
 
Basic syntax
Basic syntaxBasic syntax
Basic syntax
 
5 the final_hard_part
5 the final_hard_part5 the final_hard_part
5 the final_hard_part
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
OOP with Java
OOP with JavaOOP with Java
OOP with Java
 
Core java
Core java Core java
Core java
 
Core java &collections
Core java &collectionsCore java &collections
Core java &collections
 
Core java1
Core java1Core java1
Core java1
 

Kürzlich hochgeladen

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Kürzlich hochgeladen (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

0 E158 C10d01

  • 1. Lesson 2 – Basic Java Concepts Java™ Programming 2 0 Basic Java Concepts JPROG2-1 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Schedule: Timing Topic 45 minutes Lecture 15 minutes Lab 60 minutes Total Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 1 of 18
  • 2. Java™ Programming Lesson 2 – Basic Java Concepts Objectives • After completing this lesson, you will have an understanding of: – Important elements of a Java program – Basic Java language syntax – .java and .class file structures – How to run a Java application JPROG2-2 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Objectives Lesson 2 introduces key elements of the language for Java class creation. Basic syntax is also demonstrated, together with coding and documentation standards. The JDK is described in more detail to allow creation, compilation and running of simple Java programs. Page 2 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 3. Lesson 2 – Basic Java Concepts Java™ Programming Sun’s JDK • The Sun JDK includes "standard" classes • The language package is in classes.zip • Other packages included are: – Windowing (java.swing) – Applet (java.applet) – Streams I/O (java.io) – Network comms (java.net) JPROG2-3 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Sun’s JDK The Java Developers Kit (JDK) (introduced in Lesson 1) includes a standard set of classes that provide the core functions of Java. The language package (java.lang) contains the lowest level of required classes. For example, java.lang includes the Object class, the foundation of all user defined (and many Java defined) classes. The JDK includes several packages (groups of classes) that share common definitions. Packages also share a name space, the scope of internal definitions within the package. Different packages can contain objects of the same name – the fully qualified object name includes the package name for uniqueness. To simplify coding, a package can be imported into a class (discussed later), which removes the requirement to fully name packaged objects. Included packages Some examples of included packages are: ƒ java.lang Object, String, Thread, System, Math ƒ javax.swing Window, Button, Menu, Font, Border ƒ java.applet Applet, AudioClip, ƒ java.io InputStream, OutputStream, File, StreamTokenizer ƒ java.net Socket, URL, ContentHandler Further information should be obtained from the JavaSoft website, from where the documentation can be browsed or downloaded. The download is an (approximately) 21.5mb ZIP file, which can then be unzipped into a set of HTML pages for use in any browser. Alternatively, if you have access to a permanent Internet connection, the latest documentation can be browsed online. The URL for documentation is http://java.sun.com/j2se/1.3/docs.html. Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 3 of 18
  • 4. Java™ Programming Lesson 2 – Basic Java Concepts Java naming conventions • Files HelloWorld.java • Classes HelloWorld.class • Methods main, showMessage • Variables employeeName, birthDate • Constants RETIREMENT_AGE !! Everything in Java is case sensitive !! JPROG2-4 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Java naming conventions All names and keywords in Java are case-sensitive. Files Source code are stored in files with the .java extension and must use the class name within the file as the prefix of the file name itself. The compiled classes are stored in a file with a .class suffix – the prefix must again be the same as the name of the initial class held within the file. Classes Class names should be nouns. The first letter of each word in the class name should be capitalised. For example, OrderLine. Methods The name of each method is typically a verb. The first letter of the method name should be lowercase; the first letter of subsequent words should be capitalised. For example, getClientName(). Variables A variable name should be short but descriptive, avoiding where possible the common variable names like i and j etc.. Use the same mixed case as for method names. For example, employeeTaxCode. Constants A constant should be declared with an all upper-case name, using underscores to separate internal words. For example, STANDARD_VAT_RATE. Page 4 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 5. Lesson 2 – Basic Java Concepts Java™ Programming Java class definition package myPackage; public class Employee { • Package Name private String employeeName; private float salary; • Access modifier public Employee() { employeeName = "Unknown"; • Class keyword } salary = 0; • Variables public class Employee { – Instance, Class, Local variables ... Employee e1 = new Employee(); • Methods Employee e2 = new Employee(); ... – Instance methods – Class methods • Constructors e1 e2 JPROG2-5 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Java class definition Classes are the encapsulated definition of properties (variables) and subroutines (methods) to operate on those properties. The class definition can be used as a model or blueprint for creating (instantiating) actual examples of the class. The behaviour of the class is defined as methods that operate on the attributes of the class. Attribute values are stored as variables, either for a specific instance of the class (instance variables) or as variables shared by all instances of the class (class variables). The class definition includes the following components: ƒ Package name Name of the package where this class belongs – discussed later. ƒ Access modifier Keyword to specify how external access to this class is managed. Options include public or private. ƒ Class keyword A mandatory keyword. ƒ Instance variables Variables (constants) defined outside of a method and available to all methods in the class. ƒ Class variables Variables (constants) defined with the static keyword – a single instance of the variable is created which is shared by all instances of the class. Instance variables are created when the class is loaded initially and can be set and accessed even before new instances of the class are created. ƒ Local variables Variables (constants) defined inside a method. The variable scope is inside the method where it is declared. ƒ Instance methods Functions (subroutines) that operate on instances of the class. ƒ Class methods Functions (subroutines) that operate on class variables of the class. ƒ Constructors Methods that have the same name as the class and are automatically called to create new instances of the class (initialise instance variables). Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 5 of 18
  • 6. Java™ Programming Lesson 2 – Basic Java Concepts Packages package com.JeremyRussell; public class Employee { • Java uses packages ... . – to group related classes . – to reduce namespace ROOT Directory conflicts • Package conventions com – reverse domain name JeremyRussell – runtime directories follow package names source.java JPROG2-6 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Packages Java uses “packages” to both group related classes and ensure that potential namespace conflicts are minimised. Each class resides in a package – if the class does not include a package specifier, the class is a member of the default package. Each Java class is fully qualified by the fully qualified class name, which consists of the package name and the class name, concatenated with dot notation. For example, java.lang.Object class is the fully qualified name of the Object class. The java.lang package is included in every java class by default. One generally accepted convention for package naming is to use the author’s internet domain name as the initial components of the package name. Furthermore, the initial portion of the package name is often uppercased. For example, packages created for use by Microsoft, with their domain name of ‘microsoft.com’, would typically have a package name of “COM.microsoft”. If Microsoft were to create a class called “Customer” for their “licence” subsystem, the fully qualified class name would be “com.Microsoft.licence.Customer”. Package names of “java”, “javax” and “sun” are reserved for use by Sun. Page 6 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 7. Lesson 2 – Basic Java Concepts Java™ Programming Class files at runtime The root directory for the class hierarchy must also be identified in the environment variable CLASSPATH for both Windows and UNIX systems. This environment variable can contain a list of directories to be searched at runtime (by java) for the initial directory containing the class hierarchy. At runtime, compiled Java classes must appear in a directory tree structure that corresponds to their package name. The compiler can be instructed to create the directory hierarchy by using the command line option –d, as below SET CLASSPATH=C:Course javac –d . Source.java If Source.java contains the following code: package practice; public class Question1 { ... the compiled Source.class file must appear in the file C:CoursepracticeQuestion1.class. Compiled class files must be placed in a directory that matches their package name. Microsoft’ s licence system, customer class must be stored for a Windows operating system, in “ ..commicrosoftlicenceCustomer.class” or, for a UNIX system, the directory “ ../com/microsoft/licence/Customer.class” To execute this class, use this command: java practice.Question1 Note that since CLASSPATH has been set already, this command can be invoked from any directory on your system. Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 7 of 18
  • 8. Java™ Programming Lesson 2 – Basic Java Concepts Access modifier Example class Class declaration public class HelloWorld { Instance private String employeeName; public static void main(String[] args) { Variable System.out.println("Hello, World"); Class employeeName = "Jeremy"; Method showMessage("Employee:"); } Instance Method static void showMessage(String msg) { int i; Instance System.out.println(msg + " " + Variable employeeName); } } JPROG2-6 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Java class definition Classes are the encapsulated definition of properties (variables) and subroutines (methods) to operate on those properties. The class definition can be used as a model or blueprint for creating (instantiating) actual examples of the class. The behaviour of the class is defined as methods that operate on the attributes of the class. Attribute values are stored as variables, either for a specific instance of the class (instance variables) or as variables shared by all instances of the class (class variables). The class definition includes the following components: ƒ Access modifier Keyword to specify how external access to this class is managed. Options include public or private. ƒ Class keyword A mandatory keyword. ƒ Instance variables Variables (constants) defined outside of a method and available to all methods in the class. ƒ Class variables Variables (constants) defined with the static keyword – a single instance of the variable is created which is shared by all instances of the class. Instance variables are created when the class is loaded initially and can be set and accessed even before new instances of the class are created. ƒ Local variables Variables (constants) defined inside a method. The variable scope is inside the method where it is declared. ƒ Instance methods Functions (subroutines) that operate on instances of the class. ƒ Class methods Functions (subroutines) that operate on class variables of the class. ƒ Constructors Methods that have the same name as the class and are automatically called to create new instances of the class (initialise instance variables). Page 8 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 9. Lesson 2 – Basic Java Concepts Java™ Programming Methods • Methods are defined within a class • Method signature includes – Access modifier – Static keyword – Arguments – Return type • Method body includes statements public static int getAge(int customer) { ... } JPROG2-7 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Methods Each method is defined within a class, and can be equivalent to a subroutine, a procedure or a function in other programming languages. For each method, the following forms part of the definition: ƒ Access modifier Keyword to specify how external access to this method is managed. Options include: ƒ public - accessible from other classes ƒ private - not accessible outside this class ƒ protected - accessible from sub-classes of this class ƒ default - accessible from other classes in the same package (the default keyword does not appear but is assumed). ƒ Static keyword A mandatory keyword for class methods. ƒ Return type The data type returned by this method. If the method does not return a value, the data type void must be used. ƒ Method name The name of the method. ƒ Arguments A comma separated list of datatypes and names passed as parameters to this method. ƒ Method body Java statements that provide the functionality of this method. Unless a method does not return a value (and has a signature specifying a void return type), the method must end with a ‘return’ statement to provide the value to the calling method. A method may have several exit points (return statements) – each statement must return the same type. main method Executable classes (applications) must have a “ main” method defined. This method is the entry point to the application. Other classes do not need a main method but may have one defined for use as a testing entry point. The main method signature is always: public static void main(String[] args){ ... } Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 9 of 18
  • 10. Java™ Programming Lesson 2 – Basic Java Concepts Code blocks • Method body consists of a code block • Code blocks are enclosed in braces { } • Code blocks can be nested • Use code blocks for { – Class declarations // Get cust, return age Customer c = – Method declarations getCust(customer); – Nesting other blocks return c.getAge(); } JPROG2-8 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Code blocks The body of a method appears as a code block, a set of Java statements enclosed within brace characters ({ and }). Code blocks can be nested to form compound statements, often within conditional or loop constructs. Variables defined within a code block have a scope of that code block only (temporary variables). A temporary variable that is defined with the same name as a variable with a higher scope will mask the definition of the higher scoped variable – this is not good practice for code clarity. Page 10 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 11. Lesson 2 – Basic Java Concepts Java™ Programming Statements • Statements are terminated { with semicolon if (age > 65) pension = true; • Compound statements else { contained within a code pension = false; block calculateTax(); } • Braces used for control createPaySlip(); flow blocks ... } JPROG2-9 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Statements Java statements are always terminated with a semi-colon. Statements may be Java statements (variable declaration, assignment, logic statements) or references to methods within the same or another class. Compound statements are contained within a code block, delimited by braces. Multiple statements can appear on a single line of source code, provided that each statement is delimited with a semi-colon. This is not good practice for coding clarity reasons and should be avoided whenever possible. Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 11 of 18
  • 12. Java™ Programming Lesson 2 – Basic Java Concepts Variables • Must be defined before use • Variables can be primitives or objects • Variable declarations appear one per line • Should be initialised wherever possible • Can be declared as : – Instance variables (start of class) – Method variables (start of code block) – Temporary (within a code block) JPROG2-10 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Variables The Java language is strongly typed, meaning that variables must be defined before they are referenced. For code clarity, a declaration should appear on a separate line in the source file. Multiple variables of the same type can be declared (and initialised) using a single statement. Declarations can appear at the beginning of a code block or within a code block (for temporary variables). Each variable should be initialised on declaration wherever possible. Primitive (built-in) variables and class variables are automatically initialised to an appropriate value (as described later). Object variables (user-defined) may be declared without initialisation values. Page 12 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 13. Lesson 2 – Basic Java Concepts Java™ Programming Comments public class HelloWorld { // comment to end of line private static String employeeName; /* multiline comment */ public static void main(String[] args) { System.out.println("Hello, World"); employeeName = "Jeremy"; showMessage("Employee:"); } /** Documentation comment */ static void showMessage(String msg) { System.out.println(msg + " " + employeeName); } } JPROG2-11 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Comments Code should be commented wherever possible, to ensure clarity for the original developer and for developers that may subsequently work on or use the class. Comments can be specified in several ways: ƒ Using // All characters after // are treated as comments by the compiler. ƒ Using /* and */ A multi-line comment is enclosed between a /* and */ pair ƒ Using /** and */ The /** prefix is used by the Javadoc utility for generating standardised documentation in HTML format (discussed later). Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 13 of 18
  • 14. Java™ Programming Lesson 2 – Basic Java Concepts Compiling an application $ javac HelloWorld.java $ HelloWorld.java:12: ’}’ expected } ^ 1 error $ vi HelloWorld.java $ javac HelloWorld.java $ _ JPROG2-12 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Compiling an application To compile a Java source file, use the JDK Java compiler “ javac.exe” . Change to the directory containing the “ .java” file to be compiled, and run the compiler as shown above. Remember that the name of the source file is case-sensitive for the compiler, whichever operating sytem you are using for the compilation. Errors in the code that prevent compilation will be reported by the compiler immediately. If there are no errors, the compiler will create a class file in the same directory as the source file. Page 14 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 15. Lesson 2 – Basic Java Concepts Java™ Programming Running an application $ java HelloWorld Hello, World Employee: Jeremy JVM HelloWorld HelloWorld $ _ java.lang java.lang JPROG2-13 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Running an application To compile a Java source file, use the JDK Java runtime “ java.exe” . Change to the directory containing the “ .class” file to be execute, and invoke the Java runtime as shown above. Remember that the name of the class file is case-sensitive for the runtime, whichever operating sytem you are using for execution. The java.exe program loads the class and verifies the integrity of the bytecodes before converting the bytecodes into machine code and executing the main() method. The JVM is started to manage the processing. Any other classes referenced in the application will be loaded into the JVM’ s memory space as required. Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 15 of 18
  • 16. Java™ Programming Lesson 2 – Basic Java Concepts Lesson Summary • In this lesson, you learnt: – Important elements of a Java program – Basic Java language syntax – .java and .class file structures – How to run a Java application JPROG2-14 Copyright © Jeremy Russell & Associates, 2003. All rights reserved. Page 16 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates
  • 17. Lesson 2 – Basic Java Concepts Java™ Programming Practice 2 1) Using the notes in this lesson as a guide, define the following terms: a) Class: b) Instance variable: c) Instance method: d) Temporary variable: 2) Examine the following code example and answer the questions below: public class HelloWorld { private String employeeName; private int age; private float salary; public static void main(String[] args) { System.out.println("Hello, World"); employeeName = "Jeremy"; showMessage("Hello, from a method"); } static void showMessage(String msg) { int messageCode = 0; int messagePriority = 0; System.out.println(msg + " " + employeeName); } } a) What is the class name? b) What are the method names? c) What are the names of the instance variables? d) What are the names of the method variables? 3) List four components of the JDK. a) b) c) d) Copyright © 2003 Jeremy Russell & Associates Lesson 2 - Page 17 of 18
  • 18. Java™ Programming Lesson 2 – Basic Java Concepts This page intentionally left blank Page 18 of 18 – Lesson 2 Copyright © 2003 Jeremy Russell & Associates