THÂN CHÀO QUÝ BẠN
Blogger nầy chỉ tồn trử kiến thức và kinh nghiệm về nghề “Materials Testing”, “Textile Screen Printing” và “Internet Programming” của một kỹ sư đã phục vụ tại :
* Trung Tâm Khảo sát Kỹ Thuật Quân Nhu /QLVNCH “ & “ Viện Quốc Gia Định Chuẩn/VNCH”
* Xí nghiệp “Hiệp Hưng / VN” ( sãn xuất giày vãi cao su )
"Bradbury Company Inc/USA"(Textile Screenprinting,Imprinted Sportswear Programs) & “Sundance Graphics Inc / USA” ( in bông vãi sợi ) từ năm 1965 để dành cho thế hệ trẻ muốn học nghề.
Vạn Vật Thái Bình (PEACE ON EARTH).

Tuesday, February 17, 2015

HOW TO USE JAVA PROGRAMMING LANGUAGE

      TÌM HIỂU CÁCH XỬ DỤNG NGÔN NGỮ 
                 “ JAVA PROGRAMMING LANGUAGE”
Ngày nay Java Programming Language được xử dụng hầu hết trong mọi lảnh vực như  Internet, cell phones, telecom, tài chánh, games, data centers, supercomputers ,  Web servers v.v…
James Gosling cùng với nhóm nghiên cứu phục vụ tại Sun Microsystems sau 18 tháng hợp tác đã phát minh Java Programming Language vào năm 1991 nhưng đến năm 1995 mới xuất hiện ngoài thị trường.
                   Muốn xử dụng Java Programming Language 
                                cần phải biết cách viết Java Code và phải có :
* Interpreter & Just in time (JIT) compiler chứa trong  Execution Engine dùng để chuyển đổi byte code thành machine code để cho processor của computer hiểu và hiển thị kết quả ( display results)
* JIT Compiler chuyển đổi Java byte code thành machine code chạy nhanh hơn  machine code của Interpreter .                                   
* Hoc viết programs tức là học viết các codes.Nhưng các codes cần phải có compiler software để chuyển đổi ra bytecode .
Nếu chúng ta không muốn install compiler vào computer thì có thể xử dụng những free compilers online.
* Người viết bài nầy đã xử dụng Java Online Compiler của  javalaunch.com, compiler của  Rextester.com và compiler của Ideone.com.
                                    ----------------------------
     I -  THÍ DỤ MỘT JAVA PROGRAM ĐƠN GIẢN
public class GioiThieu {
public static void main(String[]args) {
  System.out.println("Hello Friends - Best Wishes To You. Đây là program viết bởi HENRY DƯƠNG dùng Java Programming Language, đã được Compiler xác nhận SUCCESS và đổi ra byte codes nên computer đã đọc và hiển thị kết quả như trang bên phải. Nếu chúng ta chịu khó học thì làm việc nầy không có gì gọi là quá khó"); } }

Đây là màn hình của Compiler / javalaunch.com



Sau khi qua Compiler, Java program đơn giãn trên hiện ra như sau.
Result: Success
Hello Friends - Best Wishes To You. Đây là program viết bởi HENRY DƯƠNG dùng Java Programming Language, đã được Compiler xác nhận SUCCESS và đổi ra byte codes nên computer đã đọc và hiển thị kết quả như trang bên phải. Nếu chúng ta chịu khó học thì làm việc nầy không có gì gọi là quá khó.
GHI CHÚ.
Mỗi Java Program có 3 phần.
1* public class + Tên. Phần nây gọi là class header. Tự do chọn Tên thi du class Calculation{ } , class Xaoke{ }, class Test{  },class Helloworld{ }.   
Một số  free online compiler bắt buộc phải dùng tên của họ.Thí dụ class Rextester{   } .
Phần nầy được coi là container của program phải có 2 dấu curly brackets {  }.
Tất cả những gì thuộc program phải viết trong 2 dấu curly brackets đó.
Bắt buộc không viết hoa 2 chữ public class. Phải viết hoa chữ đầu tiên của Tên. Có thể bỏ chữ public. Thí du class Calculation
2* public static void main(String[]args){   } . Phần nầy gọi là method header.Cũng là phần làm cho Java Program được executed bắt đầu từ đây. Nếu không viết đúng như vậy thì compiler không nhận ra nên program không  “run” được .(The compiler will not locate the exact method  syntax and the program will not run.)
Trong các programming khác method chính là function. Đối với Java programming người ta dùng chữ method thay cho function.
Tên của method phải được viết là main(String[]args).Trong parentheses có chứa ký hiệu của parameters là arguments thuộc nhóm string. Có thể viết :
                   main(String args[]) hoặc main(String... args).
Trong mỗi Java Program bắt buộc phải có method main( ) và phải có String.Vì Java program chỉ được executed từ method main( ).Nếu không có main( ) method hoặc thiếu sót String thì compiler sẽ cho biết sai lầm (erros) và không run program.
void là không return gì hết (No return value at all).Muốn return thi không được vì void phải đi với method main().
static  dùng để quản lý tiết kiệm memory (used for memory management only) .
      static chỉ liên hệ đến class (tức là container) của program.
Khi dùng chữ static đi với chữ main thì nên biết chữ static đó ám chỉ tới class đang ở trạng thái static class nên compiler không cần phải “instantiate an object for the class”.
Instance là sự tạo ra một object chứa trong memory để xử dụng.Nếu không tạo instance thì không có object trong memory.
Compiler khi gặp chữ static trong main( ) method sẽ hiểu ngay và cho program chạy theo static class mặc dầu chúng ta không viết chữ static đi kèm với chữ class.Vậy chữ static luôn luôn phải đi kèm với chữ main( ).
Nếu dùng method mà không có chữ static kèm theo thì phải tạo một instance cho class để có thể liên lạc riêng đến cá thể tức là object chứa trong class( individual of the class ) nên không tiết kiệm memory.Xem thí dụ 3.3 sau.
Nếu không declare static cho main method thì Java Virtual Machine sẽ tạo instance of class làm cho JVM không tìm được main method.
       public là method được called ở bất cứ nơi đâu.
Nếu muốn method được called trong defined class thì dùng chữ private,trong package thì dùng chữ protected.
Trường hợp default, tức là không quy định : sẽ tự động có non static và protected.
3* System.out.println(  ) là một method có rất nhiều codes đã viết sẵn trong System Libraries.Chúng ta chỉ cần biết xử dụng nó mà thôi.
   System là tên của một class lấy từ API (Application Programmer Interface).
   out là object trong class.
   println hay print dùng để display text output
                                 ----------------------------------
Một Java program được cấu tạo bởi nhiều classes nhưng tối thiểu phải có một class.
Khi làm compiling Java program mà chúng ta đã viết xong tồn trử dạng .java thì compiler sẽ chuyển nó thành một file khác goị la class file tích chứa những hướng dẫn để Java Virtual machine (JVM ) có thể thông dịch .

II- NHỮNG JAVA PROGRAMS CĂN BẢN.
Nếu chúng ta đã biết rành cách viết JavaScript Programs thì sẽ hiểu rất nhanh những Java Programs căn bản nầy.
Mỗi variable phải được declared bằng chữ String nếu variable là chữ (keyword).
String firstName="Xao";
Mỗi variable phải được declared bằng chữ int nếu variable có value là một con số nguyên (integer)
int a =12 ;
Mỗi variable phải được declared bằng chữ double nếu variable có value là một con số decimal
double x =41.25
                        ---------------------------------------------                 

2.1- public class Test{
   public static void main(String[]args){
    int a,b,c,add,multiplication,square ; // integer
    double x,y,adding ;// decimal
        a=10 ;
        b=5 ;
        c=6 ;
        add = a+b ;
        multiplication = c*a ;
        square = 5*5 ;
        x=2.5 ; 
        y=7.5 ;
        adding=x+y ;
   System.out.println(add +"\n "+ multiplication+"\n "+ square+"\n"+adding);
}}
      Result : success
Compilation time: 0.72 sec, absolute running time: 0.13 sec, cpu time: 0.09 sec, memory peak: 18 Mb, absolute service time: 0.86 sec
15
 60
 25
10.0
                                     -------------------

2.2 - public class StringVariables{         
public static void main(String[]args){
  String firstName="Xao";
  String familyName="Ke";
  System.out.println(firstName+ " "+familyName);
}}
Result: Success
Xao Ke
                              ---------------------    

2.3 - public class Calculation{
public static void main(String[] args){
int firstNumber, secondNumber, thirdNumber, answer;
//Ở đây dùng chữ int vì variable có value là một con số integer
firstNumber=150;
secondNumber=50;
thirdNumber=25;
answer=(firstNumber-secondNumber)+thirdNumber;
System.out.println("Total="+ answer);
}}
 Result: Success
Total=125
                                      ------------------------------------------------------------------                                    

2.4 - public class concatStrings{
public static void main(String[] args){
String str1 = "Hello";
String str2 = "Mr BAXAO XIKE IN CALIFORNIA";
String concatenatedString = str1+" "+str2;
System.out.println("The output of concatenated string is"+" " +concatenatedString);
}}
 Result:Success
The output of concatenated string is Hello Mr BAXAO XIKE IN CALIFORNIA
----------------------------------------
2.5 - class Namelist{
      public static void main(String[] args){
     String[] name = {"Xao Ke", "Ba Xao", "Henry Duong"};
      // In ra những tên chứa trong String array name 
     for ( int i = 0; i < name.length; i++ ){
      System.out.println( name[i] );}
      } }
Result  :  success
Compilation time: 1.24 sec, absolute running time: 0.14 sec, cpu time: 0.06 sec,
 memory peak: 18 Mb, absolute service time: 1.38 sec
 
Xao Ke
Ba Xao
Henry Duong
Save in Permanent link: http://rextester.com/VSHX98768
Ghi chú.
Trong method main(String[] args) có parameter là data type thuộc lọai array of String
 args là variables của main method.
 args[0] là first element of this array.
 args[1] là second element of this array.     
 args.length() là the length of the array

----------------
 Java Programs dùng parseInt()
2.6.1 - class ParseInt{
    public static void main(String[] args){
     String a = "14";
     String b = "36";
    System.out.println( a + b );
           // a + b = "14" + "36" = "1436"
           // Because of concatenate when used on strings
    System.out.println(Integer.parseInt(a) + Integer.parseInt(b));    
           // Integer.parseInt(a) + Integer.parseInt(b)
           // = Integer.parseInt("14") + Integer.parseInt("36")
           // = 14 + 36 = 50
      }}
Result : success
Compilation time: 0.93 sec, absolute running time: 0.13 sec, cpu time: 0.06 sec, memory peak: 18 Mb, absolute service time: 1.08 sec
   1436
     50
----------------------------------
2.6.2 -  public class ParseDouble{
      public static void main(String[] args){
             String a = "12.34";
             String b = "56.78";
             System.out.println( a + b );
                           // a + b = "12.34" + "56.78" = "12.3456.78" 
                           // Because of concatenate when used on strings
             System.out.println( Double.parseDouble(a) + Double.parseDouble(b) );
                           // Double.parseDouble(a) + Double.parseDouble(b)
            // = Double.parseDouble("12.34") +  Double.parseDouble("56.78")  
                           // = 12.34 + 56.78 = 69.12
      }}
 
Result: success
Compilation time: 0.82 sec, absolute running time: 0.13 sec, cpu time: 0.06 sec,memory peak: 18 Mb,absolute service time: 0.96 sec
12.3456.78
69.12            
--------------
2.7 - public class Condition{
public static void main(String[] args){
 boolean age = false;// if true, the 1 st print will display.
 if (age){
System.out.println("You are under 25 years old");
}
else{
System.out.println("How old are you ?");} 
}}
Result: Success

Compilation time: 0.72 sec, absolute running time: 0.15 sec, cpu time: 0.06 sec,
 memory peak: 16 Mb, absolute service time: 0.88 sec 
How old are you ?
                  --------------------------

2.8-CÔNG, TRỪ, NHÂN, CHIA và  MODULUS

         public class Arithmetic{
            public static void main(String[]args){
            int i = 25;
             int j = 20;
             double x = 20.5;
             double y = 4.5;
            System.out.println("Adding");
            System.out.println(" i + j = " + (i + j));
            System.out.println(" x + y = " + (x + y));
 
            System.out.println("Subtracting");
            System.out.println(" i - j = " + (i - j));
            System.out.println(" x - y = " + (x - y));
 
            System.out.println("Multiplying");
            System.out.println(" i * j = " + (i * j));
            System.out.println(" x * y = " + (x * y));
 
            System.out.println("Dividing");
            System.out.println(" i / j = " + (i / j));
            System.out.println(" x / y = " + (x / y));
 
            // the remainder resulting from dividing numbers
            System.out.println("Modulus");
            System.out.println(" i % j = " + (i % j));
            System.out.println(" x % y = " + (x % y));
 
    }
}
 
Result: Success
 Compilation time: 0.83 sec, absolute running time: 0.13 sec, cpu time: 0.06 sec,
 memory peak: 18 Mb, absolute service time: 0.97 sec
 Adding
 i + j = 45
 x + y = 25.0
Subtracting
 i - j = 5
 x - y = 16.0
Multiplying
 i * j = 500
 x * y = 92.25
Dividing
 i / j = 1
 x / y = 4.555555555555555
Modulus
 i % j = 5
 x % y = 2.5
   
 Permanent link: http://rextester.com/DURV4047
                     
  -----------------------------------

Hoc viết programs tức là học viết các codes.Nhưng các codes cần phải có compiler software để chuyển đổi ra bytecode .
Nếu chúng ta không muốn install compiler vào computer thì có thể xử dụng những free compilers online.
 
III- TẠO THÊM NHIỀU METHODS MỚI TRONG JAVA PROGRAM.
Tự tạo nhiều methods theo ý muốn trong class nhưng nhớ cứ mỗi method phải tạo instance cho class sau main method
An instance is an object created in memory. We create an object and instantiate it in order to use it.
Tạo thêm một method call() nên phải tạo một object cho class Rextester
3-1- class Rextester
    private void call(){
        System.out.println(" World");}
    public static void main(String[] args){
        System.out.println("Hello");
        Rextester object= new Rextester();
        object.call();
     }}
Compilation time: 0.82 sec, absolute running time: 0.14 sec, 
cpu time: 0.06 sec, memory peak: 18 Mb, absolute service time: 0.98 sec
 
   Hello
     World
                      ------------------------------------------
3-2 - class Rextester{
 public static void main(String[] args){
    staticMethod();// this calls static method
    Rextester object = new Rextester();// create an object for class Rextester
    object.nonStaticMethod();} // this calls non static method 
 static void staticMethod(){
    System.out.println("We do not create an object to call this staticMethod");}
 void nonStaticMethod(){
    System.out.println("We must create an object to call this nonStaticMethod");}
  }}
Result : Success
We do not create an object to call this staticMethod
We must create an object to call this nonStaticMethod
                    -----------------
Tạo thêm 2 methods là call() và display() nên phải tạo thêm 2 objects là xaoke và baxao cho class Rextester.
3-3 - class Rextester{
    private void call(){
    System.out.println("My Friends Around The World.I Love You All");}
    private void display(){
    System.out.println("Do You Want to Learn  Java Programming ?");}
   public static void main(String[] args){
    System.out.println("Hello");
    Rextester xaoke=new Rextester();
    xaoke.call();
   Rextester baxao=new Rextester();
    baxao.display();
}}
Result : Success
Compilation time: 0.84 sec, absolute running time: 0.13 sec, cpu time: 0.06 sec, memory peak: 16 Mb, absolute service time: 0.98 sec
Hello
My Friends Around The World.I Love You All
Do You Want to Learn Java Programming ?
--------------------------------------------------
Methods được tạo thêm nếu có viết static kèm theo như thí dụ dưới đây thì không cần tạo object cho class nữa để tiết kiệm memory.

3.4-class Test1{         
      private static void print(){
      System.out.println("Hello Friends!I love you all.");}
    public static void main(String args[]){
       print();}
}
SUCCESS.
Compilation time: 1.06 sec, absolute running time: 0.14 sec,
 cpu time: 0.08 sec, memory peak: 18 Mb,absolute service time: 1.21 sec
Hello Friends!I love you all.
            -----------------------------------------------
3.5-class Test2{         
      private static void print(){
      System.out.println("Hello Friends!I love you all.");}
      private static void display(){
      System.out.println("Because we are human beings created by one Father.");}
 public static void main(String args[]){
       print();display();}
}
SUCCESS.
Compilation time: 0.74 sec, absolute running time: 0.13 sec,
cpu time: 0.06 sec, memory peak: 18 Mb, absolute service time: 0.88 sec
Hello Friends!I love you all.
Because we are human beings created by one Father.

còn tiếp