SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Introduction to
         Java Programming
                Y. Daniel Liang
Edited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd
 https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd
Introduction
 Course Objectives
 Organization of the Book




VTC Academy       THSoft Co.,Ltd   2
Course Objectives
   Upon completing the course, you will understand
    –   Create, compile, and run Java programs
    –   Primitive data types
    –   Java control flow
    –   Methods
    –   Arrays (for teaching Java in two semesters, this could be the end)
    –   Object-oriented programming
    –   Core Java classes (Swing, exception, internationalization,
        multithreading, multimedia, I/O, networking, Java
        Collections Framework)


VTC Academy                     THSoft Co.,Ltd                          3
Course Objectives, cont.
 You         will be able to
    – Develop programs using Eclipse IDE
    – Write simple programs using primitive data
      types, control statements, methods, and arrays.
    – Create and use methods
    – Write interesting projects




VTC Academy                 THSoft Co.,Ltd              4
Session 03: Method and Class

 Methods
 Object-Oriented   Programming
 Classes
 Packages
 Subclassingand Inheritance
 Polymorphism



VTC Academy          THSoft Co.,Ltd   5
Introducing Methods
                      Method Structure
A method is a
collection of
statements that are
grouped together
to perform an
operation.



  VTC Academy          THSoft Co.,Ltd    6
Introducing Methods, cont.
•parameter profile refers to the type, order, and
number of the parameters of a method.
•method signature is the combination of the
method name and the parameter profiles.
•The parameters defined in the method header
are known as formal parameters.
•When a method is invoked, its formal
parameters are replaced by variables or data,
which are referred to as actual parameters.
  VTC Academy        THSoft Co.,Ltd           7
Declaring Methods

public static int max(int num1,
  int num2) {
   if (num1 > num2)
     return num1;
   else
     return num2;
}



 VTC Academy         THSoft Co.,Ltd   8
Calling Methods, cont.

                                                                       pass i
                                                                                 pass j


public static void main(String[] args) {     public static int max(int num1, int num2) {
  int i = 5;                                   int result;
  int j = 2;
  int k = max(i, j);                             if (num1 > num2)
                                                   result = num1;
    System.out.println(                          else
     "The maximum between " + i +                  result = num2;
     " and " + j + " is " + k);
}                                                return result;
                                             }




     VTC Academy                      THSoft Co.,Ltd                                9
Calling Methods, cont.

The main method     pass 5     The max method


  i:          5                   num1:         5
                    pass 2
                                                    parameters

  j:          2                   num2:         2


  k:          5                  result:        5




VTC Academy             THSoft Co.,Ltd                           10
CAUTION
A return statement is required for a nonvoid
method. The following method is logically
correct, but it has a compilation error, because the
Java compiler thinks it possible that this method
does not return any value.
 public static int xMethod(int n) {
   if (n > 0) return 1;
   else if (n == 0) return 0;
   else if (n < 0) return –1;
 }
To fix this problem, delete if (n<0) in the code.
 VTC Academy          THSoft Co.,Ltd                11
Actions on Eclipse
   Open Eclipse IDE
    –   Create project: Session3Ex
    –   Create package: com.vtcacademy.exopp
    –   Create java class: Ex3WithOpp.java (with main method)
    –   Create java class: Circle.java




              Source                           Run



VTC Academy                   THSoft Co.,Ltd                    12
The Math Class
 Class       constants:
    – PI
    –E
 Class       methods:
    – Trigonometric Methods
    – Exponent Methods
    – Rounding Methods
    – min, max, abs, and random Methods


VTC Academy                THSoft Co.,Ltd   13
Trigonometric Methods
 sin(double        a)
 cos(double        a)
 tan(double        a)
 acos(double        a)
 asin(double        a)
 atan(double        a)


VTC Academy           THSoft Co.,Ltd   14
Exponent Methods
   exp(double a)
    Returns e raised to the power of a.
   log(double a)
    Returns the natural logarithm of a.
   pow(double a, double b)
    Returns a raised to the power of b.
   sqrt(double a)
    Returns the square root of a.

VTC Academy             THSoft Co.,Ltd    15
Rounding Methods
   double ceil(double x)
    x rounded up to its nearest integer. This integer is returned as a
     double value.
   double floor(double x)
    x is rounded down to its nearest integer. This integer is
     returned as a double value.
   double rint(double x)
    x is rounded to its nearest integer. If x is equally close to two
     integers, the even one is returned as a double.
   int round(float x)
    Return (int)Math.floor(x+0.5).
   long round(double x)
    Return (long)Math.floor(x+0.5).


VTC Academy                    THSoft Co.,Ltd                           16
min, max, abs, and random
 max(a,      b)and min(a, b)
   Returns the maximum or minimum of two
   parameters.
 abs(a)
   Returns the absolute value of the parameter.
 random()
   Returns a random double value
   in the range [0.0, 1.0).


VTC Academy            THSoft Co.,Ltd             17
Example 3.1 Computing Mean
       and Standard Deviation
Generate n random numbers and compute the mean
 and standard deviation

                n                                            n
                      xi                    n            (         xi )2
                i 1                               xi2        i 1
      mean                                  i 1                  n
                    n      deviation
                                                        n 1




  VTC Academy              THSoft Co.,Ltd                                  18
Example 3.2 Obtaining Random
             Characters
Write the methods for generating random
characters. The program uses these methods to
generate 175 random characters between „!' and „~'
and displays 25 characters per line. To find out the
characters between „!' and „~', see Appendix B,
“The ASCII Character Set.”




  VTC Academy         THSoft Co.,Ltd            19
OO Programming Concepts

An object                                       A Circle object

                                                                  Data Field
                data field 1
                                                                  radius = 5

                    ...               State
                                                                   Method
                data field n                                      findArea


                 method 1


                    ...             Behavior


                 method n




  VTC Academy                  THSoft Co.,Ltd                                  20
Class and Objects

                        Circle                   UML Graphical notation for classes

                  radius: double                 UML Graphical notation for fields


                                                 UML Graphical notation for methods
                  findArea(): double

new Circle()                                 new Circle()

      circle1: Circle              circlen: Circle             UML Graphical notation
                                                               for objects
        radius = 2        ...        radius = 5

                                                               Illustration on code
    VTC Academy                        THSoft Co.,Ltd                                 21
Class Declaration
class Circle {
  double radius = 1.0;

    double findArea(){
      return radius * radius * 3.14159;
    }
}




     VTC Academy         THSoft Co.,Ltd   22
Declaring Object Reference Variables
  ClassName objectReference;


  Example:
  Circle myCircle;




VTC Academy     THSoft Co.,Ltd    23
Creating Objects
objectReference = new ClassName();


Example:
myCircle = new Circle();


The object reference is assigned to the object
 reference variable.


VTC Academy         THSoft Co.,Ltd               24
Declaring/Creating Objects
               in a Single Step
ClassName objectReference = new ClassName();

Example:
Circle myCircle = new Circle();
Circle myCircle2;




   VTC Academy      THSoft Co.,Ltd     25
Constructors
  Circle(double r) {
    radius = r;
  }                Constructors are a
                   special kind of
  Circle() {       methods that are
    radius = 1.0; invoked to construct
  }                objects.

  myCircle = new Circle(5.0);

VTC Academy      THSoft Co.,Ltd     26
Constructors
  Circle(double r) {
    radius = r;
  }                Constructors are a
                   special kind of
  Circle() {       methods that are
    radius = 1.0; invoked to construct
  }                objects.

  myCircle = new Circle(5.0);

VTC Academy      THSoft Co.,Ltd     27
Constructors, cont.
A constructor with no parameters is referred to
as a default constructor.
     Constructors must have the same name
as the class itself.
     Constructors do not have a return type—
not even void.
       Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing
objects.
 VTC Academy         THSoft Co.,Ltd         28
Example 3.3 Using Classes from
       the Java Library
 Objective:    Demonstrate using classes from the
   Java library. Use the JFrame class in the
   javax.swing package to create two frames;
   use the methods in the JFrame class to set
   the title, size and location of the frames and
   to display the frames.



                                      Illustration on code
VTC Academy          THSoft Co.,Ltd                    29
Subclassing and Inheritance
 private
 None
 protected
 Public




                                  Illustration on code
VTC Academy      THSoft Co.,Ltd                    30
Example 3.4

                                  Shape




    TwoDimensionalShape                            ThreeDimensionalShape




Circle        Square   Triangle              Sphere        Cube     Tetrahedron




VTC Academy                       THSoft Co.,Ltd                             31
Example 3.4
 http://blogs.unsw.edu.au/comp1400/blog/20
   11/09/tut-10/




VTC Academy        THSoft Co.,Ltd         32
Abstract Classes and
                    Methods
 Abstract      classes
    – Are superclasses (called abstract superclasses)
    – Cannot be instantiated
    – Incomplete
          subclasses   fill in "missing pieces"
 Concrete      classes
    – Can be instantiated
    – Implement every method they declare
    – Provide specifics
VTC Academy                   THSoft Co.,Ltd            33
Abstract Classes and Methods
               (Cont.)
 Abstract classes not required, but reduce
  client code dependencies
 To make a class abstract
    – Declare with keyword abstract
    – Contain one or more abstract methods
         public abstract void draw();
    – Abstract methods
          No   implementation, must be overridden


VTC Academy                 THSoft Co.,Ltd           34
Abstract Classes and Methods
               (Cont.)
   Application example
     – Abstract class Shape
             Declares draw as abstract method
     – Circle, Triangle, Rectangle extends Shape
             Each must implement draw
     – Each object can draw itself
   Iterators
     – Array, ArrayList (Chapter 22)
     – Walk through list elements
     – Used in polymorphic programming to traverse a collection


                                                    Illustration on code
VTC Academy                        THSoft Co.,Ltd                    35
Case Study: Creating and Using
            Interfaces
   Use interface Shape
    – Replace abstract class Shape
   Interface
    – Declaration begins with interface keyword
    – Classes implement an interface (and its methods)
    – Contains public abstract methods
             Classes (that implement the interface) must implement these
              methods




VTC Academy                      THSoft Co.,Ltd                        36
1   // Fig. 10.18: Shape.java
  2   // Shape interface declaration.
  3
  4   public interface Shape {
  5     public double getArea(); // calculate area
  6     public double getVolume(); // calculate volume
  7     public String getName(); // return shape name
  8
  9   } // end interface Shape




                           Lines 5-7
                           Classes that implement Shape
                           must implement these methods


VTC Academy                                    THSoft Co.,Ltd   37
1    // Fig. 10.19: Point.java
      2    // Point class declaration implements interface Shape.
      3
      4    public class Point extends Object implements Shape {
      5      private int x; // x part of coordinate pair
      6      private int y; // y part of coordinate pair
      7
      8       // no-argument constructor; x and y default to 0
      9       public Point()
      10      {
      11        // implicit call to Object constructor occurs here
      12      }
      13
      14      // constructor
      15      public Point( int xValue, int yValue )
      16      {                                                       Error compile
      17         // implicit call to Object constructor occurs here
      18         x = xValue; // no need for validation
      19         y = yValue; // no need for validation
      20      }
      21
      22      // set x in coordinate pair
      23      public void setX( int xValue )
      24      {
      25         x = xValue; // no need for validation
      26      }
      27



VTC Academy                                       THSoft Co.,Ltd                      38
Action on class
 Teacher
    – hauc2@yahoo.com
    – 0984380003
    – https://play.google.com/store/search?q=thsoft+co&c=apps

 Captions
 Members




VTC Academy                  THSoft Co.,Ltd                     39

Weitere ähnliche Inhalte

Was ist angesagt?

Cvpr2010 open source vision software, intro and training part-iii introduct...
Cvpr2010 open source vision software, intro and training   part-iii introduct...Cvpr2010 open source vision software, intro and training   part-iii introduct...
Cvpr2010 open source vision software, intro and training part-iii introduct...zukun
 
Micro Blaze C Reference
Micro Blaze C ReferenceMicro Blaze C Reference
Micro Blaze C Referenceiuui
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminarGautam Roy
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisSilvio Cesare
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilersComputer Science Club
 
C Programming Language
C Programming LanguageC Programming Language
C Programming LanguageRTS Tech
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
M Gumbel - SCABIO: a framework for bioinformatics algorithms in Scala
M Gumbel - SCABIO: a framework for bioinformatics algorithms in ScalaM Gumbel - SCABIO: a framework for bioinformatics algorithms in Scala
M Gumbel - SCABIO: a framework for bioinformatics algorithms in ScalaJan Aerts
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna universitysangeethajames07
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your codevmandrychenko
 

Was ist angesagt? (20)

Cvpr2010 open source vision software, intro and training part-iii introduct...
Cvpr2010 open source vision software, intro and training   part-iii introduct...Cvpr2010 open source vision software, intro and training   part-iii introduct...
Cvpr2010 open source vision software, intro and training part-iii introduct...
 
Micro Blaze C Reference
Micro Blaze C ReferenceMicro Blaze C Reference
Micro Blaze C Reference
 
PECCS 2014
PECCS 2014PECCS 2014
PECCS 2014
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Getting started with image processing using Matlab
Getting started with image processing using MatlabGetting started with image processing using Matlab
Getting started with image processing using Matlab
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
Bc0037
Bc0037Bc0037
Bc0037
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Generic programming
Generic programmingGeneric programming
Generic programming
 
M Gumbel - SCABIO: a framework for bioinformatics algorithms in Scala
M Gumbel - SCABIO: a framework for bioinformatics algorithms in ScalaM Gumbel - SCABIO: a framework for bioinformatics algorithms in Scala
M Gumbel - SCABIO: a framework for bioinformatics algorithms in Scala
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna university
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
04slide
04slide04slide
04slide
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 

Andere mochten auch

kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1ifis
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 

Andere mochten auch (11)

JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
JavaYDL18
JavaYDL18JavaYDL18
JavaYDL18
 
01slide
01slide01slide
01slide
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
07slide
07slide07slide
07slide
 
10slide
10slide10slide
10slide
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Exception handling
Exception handlingException handling
Exception handling
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 

Ähnlich wie Java cơ bản java co ban

Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1chidabdu
 
Software tookits for machine learning and graphical models
Software tookits for machine learning and graphical modelsSoftware tookits for machine learning and graphical models
Software tookits for machine learning and graphical modelsbutest
 
CP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithmsCP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithmsSheba41
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
CP4151 ADSA unit1 Advanced Data Structures and Algorithms
CP4151 ADSA unit1 Advanced Data Structures and AlgorithmsCP4151 ADSA unit1 Advanced Data Structures and Algorithms
CP4151 ADSA unit1 Advanced Data Structures and AlgorithmsSheba41
 
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...Marcel Bruch
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
StacksqueueslistsFraboni Ec
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsYoung Alista
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsTony Nguyen
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm AnalysisMary Margarat
 
Design and Analysis of Algorithm Brute Force 1.ppt
Design and Analysis of Algorithm Brute Force 1.pptDesign and Analysis of Algorithm Brute Force 1.ppt
Design and Analysis of Algorithm Brute Force 1.pptmoiza354
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On RandomnessRanel Padon
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to MatlabAmr Rashed
 
The Concurrent Constraint Programming Research Programmes -- Redux (part2)
The Concurrent Constraint Programming Research Programmes -- Redux (part2)The Concurrent Constraint Programming Research Programmes -- Redux (part2)
The Concurrent Constraint Programming Research Programmes -- Redux (part2)Pierre Schaus
 

Ähnlich wie Java cơ bản java co ban (20)

Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
Software tookits for machine learning and graphical models
Software tookits for machine learning and graphical modelsSoftware tookits for machine learning and graphical models
Software tookits for machine learning and graphical models
 
CP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithmsCP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithms
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
ALGO.ppt
ALGO.pptALGO.ppt
ALGO.ppt
 
CP4151 ADSA unit1 Advanced Data Structures and Algorithms
CP4151 ADSA unit1 Advanced Data Structures and AlgorithmsCP4151 ADSA unit1 Advanced Data Structures and Algorithms
CP4151 ADSA unit1 Advanced Data Structures and Algorithms
 
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Midterm
MidtermMidterm
Midterm
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Design and Analysis of Algorithm Brute Force 1.ppt
Design and Analysis of Algorithm Brute Force 1.pptDesign and Analysis of Algorithm Brute Force 1.ppt
Design and Analysis of Algorithm Brute Force 1.ppt
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
 
The Concurrent Constraint Programming Research Programmes -- Redux (part2)
The Concurrent Constraint Programming Research Programmes -- Redux (part2)The Concurrent Constraint Programming Research Programmes -- Redux (part2)
The Concurrent Constraint Programming Research Programmes -- Redux (part2)
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Kürzlich hochgeladen (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Java cơ bản java co ban

  • 1. Introduction to Java Programming Y. Daniel Liang Edited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd
  • 2. Introduction  Course Objectives  Organization of the Book VTC Academy THSoft Co.,Ltd 2
  • 3. Course Objectives  Upon completing the course, you will understand – Create, compile, and run Java programs – Primitive data types – Java control flow – Methods – Arrays (for teaching Java in two semesters, this could be the end) – Object-oriented programming – Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework) VTC Academy THSoft Co.,Ltd 3
  • 4. Course Objectives, cont.  You will be able to – Develop programs using Eclipse IDE – Write simple programs using primitive data types, control statements, methods, and arrays. – Create and use methods – Write interesting projects VTC Academy THSoft Co.,Ltd 4
  • 5. Session 03: Method and Class  Methods  Object-Oriented Programming  Classes  Packages  Subclassingand Inheritance  Polymorphism VTC Academy THSoft Co.,Ltd 5
  • 6. Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation. VTC Academy THSoft Co.,Ltd 6
  • 7. Introducing Methods, cont. •parameter profile refers to the type, order, and number of the parameters of a method. •method signature is the combination of the method name and the parameter profiles. •The parameters defined in the method header are known as formal parameters. •When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters. VTC Academy THSoft Co.,Ltd 7
  • 8. Declaring Methods public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } VTC Academy THSoft Co.,Ltd 8
  • 9. Calling Methods, cont. pass i pass j public static void main(String[] args) { public static int max(int num1, int num2) { int i = 5; int result; int j = 2; int k = max(i, j); if (num1 > num2) result = num1; System.out.println( else "The maximum between " + i + result = num2; " and " + j + " is " + k); } return result; } VTC Academy THSoft Co.,Ltd 9
  • 10. Calling Methods, cont. The main method pass 5 The max method i: 5 num1: 5 pass 2 parameters j: 2 num2: 2 k: 5 result: 5 VTC Academy THSoft Co.,Ltd 10
  • 11. CAUTION A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, delete if (n<0) in the code. VTC Academy THSoft Co.,Ltd 11
  • 12. Actions on Eclipse  Open Eclipse IDE – Create project: Session3Ex – Create package: com.vtcacademy.exopp – Create java class: Ex3WithOpp.java (with main method) – Create java class: Circle.java Source Run VTC Academy THSoft Co.,Ltd 12
  • 13. The Math Class  Class constants: – PI –E  Class methods: – Trigonometric Methods – Exponent Methods – Rounding Methods – min, max, abs, and random Methods VTC Academy THSoft Co.,Ltd 13
  • 14. Trigonometric Methods  sin(double a)  cos(double a)  tan(double a)  acos(double a)  asin(double a)  atan(double a) VTC Academy THSoft Co.,Ltd 14
  • 15. Exponent Methods  exp(double a) Returns e raised to the power of a.  log(double a) Returns the natural logarithm of a.  pow(double a, double b) Returns a raised to the power of b.  sqrt(double a) Returns the square root of a. VTC Academy THSoft Co.,Ltd 15
  • 16. Rounding Methods  double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value.  double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value.  double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.  int round(float x) Return (int)Math.floor(x+0.5).  long round(double x) Return (long)Math.floor(x+0.5). VTC Academy THSoft Co.,Ltd 16
  • 17. min, max, abs, and random  max(a, b)and min(a, b) Returns the maximum or minimum of two parameters.  abs(a) Returns the absolute value of the parameter.  random() Returns a random double value in the range [0.0, 1.0). VTC Academy THSoft Co.,Ltd 17
  • 18. Example 3.1 Computing Mean and Standard Deviation Generate n random numbers and compute the mean and standard deviation n n xi n ( xi )2 i 1 xi2 i 1 mean i 1 n n deviation n 1 VTC Academy THSoft Co.,Ltd 18
  • 19. Example 3.2 Obtaining Random Characters Write the methods for generating random characters. The program uses these methods to generate 175 random characters between „!' and „~' and displays 25 characters per line. To find out the characters between „!' and „~', see Appendix B, “The ASCII Character Set.” VTC Academy THSoft Co.,Ltd 19
  • 20. OO Programming Concepts An object A Circle object Data Field data field 1 radius = 5 ... State Method data field n findArea method 1 ... Behavior method n VTC Academy THSoft Co.,Ltd 20
  • 21. Class and Objects Circle UML Graphical notation for classes radius: double UML Graphical notation for fields UML Graphical notation for methods findArea(): double new Circle() new Circle() circle1: Circle circlen: Circle UML Graphical notation for objects radius = 2 ... radius = 5 Illustration on code VTC Academy THSoft Co.,Ltd 21
  • 22. Class Declaration class Circle { double radius = 1.0; double findArea(){ return radius * radius * 3.14159; } } VTC Academy THSoft Co.,Ltd 22
  • 23. Declaring Object Reference Variables ClassName objectReference; Example: Circle myCircle; VTC Academy THSoft Co.,Ltd 23
  • 24. Creating Objects objectReference = new ClassName(); Example: myCircle = new Circle(); The object reference is assigned to the object reference variable. VTC Academy THSoft Co.,Ltd 24
  • 25. Declaring/Creating Objects in a Single Step ClassName objectReference = new ClassName(); Example: Circle myCircle = new Circle(); Circle myCircle2; VTC Academy THSoft Co.,Ltd 25
  • 26. Constructors Circle(double r) { radius = r; } Constructors are a special kind of Circle() { methods that are radius = 1.0; invoked to construct } objects. myCircle = new Circle(5.0); VTC Academy THSoft Co.,Ltd 26
  • 27. Constructors Circle(double r) { radius = r; } Constructors are a special kind of Circle() { methods that are radius = 1.0; invoked to construct } objects. myCircle = new Circle(5.0); VTC Academy THSoft Co.,Ltd 27
  • 28. Constructors, cont. A constructor with no parameters is referred to as a default constructor. Constructors must have the same name as the class itself. Constructors do not have a return type— not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. VTC Academy THSoft Co.,Ltd 28
  • 29. Example 3.3 Using Classes from the Java Library  Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames. Illustration on code VTC Academy THSoft Co.,Ltd 29
  • 30. Subclassing and Inheritance  private  None  protected  Public Illustration on code VTC Academy THSoft Co.,Ltd 30
  • 31. Example 3.4 Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron VTC Academy THSoft Co.,Ltd 31
  • 32. Example 3.4  http://blogs.unsw.edu.au/comp1400/blog/20 11/09/tut-10/ VTC Academy THSoft Co.,Ltd 32
  • 33. Abstract Classes and Methods  Abstract classes – Are superclasses (called abstract superclasses) – Cannot be instantiated – Incomplete  subclasses fill in "missing pieces"  Concrete classes – Can be instantiated – Implement every method they declare – Provide specifics VTC Academy THSoft Co.,Ltd 33
  • 34. Abstract Classes and Methods (Cont.)  Abstract classes not required, but reduce client code dependencies  To make a class abstract – Declare with keyword abstract – Contain one or more abstract methods public abstract void draw(); – Abstract methods  No implementation, must be overridden VTC Academy THSoft Co.,Ltd 34
  • 35. Abstract Classes and Methods (Cont.)  Application example – Abstract class Shape  Declares draw as abstract method – Circle, Triangle, Rectangle extends Shape  Each must implement draw – Each object can draw itself  Iterators – Array, ArrayList (Chapter 22) – Walk through list elements – Used in polymorphic programming to traverse a collection Illustration on code VTC Academy THSoft Co.,Ltd 35
  • 36. Case Study: Creating and Using Interfaces  Use interface Shape – Replace abstract class Shape  Interface – Declaration begins with interface keyword – Classes implement an interface (and its methods) – Contains public abstract methods  Classes (that implement the interface) must implement these methods VTC Academy THSoft Co.,Ltd 36
  • 37. 1 // Fig. 10.18: Shape.java 2 // Shape interface declaration. 3 4 public interface Shape { 5 public double getArea(); // calculate area 6 public double getVolume(); // calculate volume 7 public String getName(); // return shape name 8 9 } // end interface Shape Lines 5-7 Classes that implement Shape must implement these methods VTC Academy THSoft Co.,Ltd 37
  • 38. 1 // Fig. 10.19: Point.java 2 // Point class declaration implements interface Shape. 3 4 public class Point extends Object implements Shape { 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor; x and y default to 0 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 } 13 14 // constructor 15 public Point( int xValue, int yValue ) 16 { Error compile 17 // implicit call to Object constructor occurs here 18 x = xValue; // no need for validation 19 y = yValue; // no need for validation 20 } 21 22 // set x in coordinate pair 23 public void setX( int xValue ) 24 { 25 x = xValue; // no need for validation 26 } 27 VTC Academy THSoft Co.,Ltd 38
  • 39. Action on class  Teacher – hauc2@yahoo.com – 0984380003 – https://play.google.com/store/search?q=thsoft+co&c=apps  Captions  Members VTC Academy THSoft Co.,Ltd 39