SlideShare a Scribd company logo
Object Oriented Programming with Java
Topic Lecture 1 C++ vs. Java Fundamentals of Java Java Application and Applet
C++ vs. Java Area of Application C++ is best suitable for developing large software Library management system, GIS etc. Java is best suitable for developing Internet application software Network Protocols, Internet programs, web page, web browser etc.
C++ vs. Java Programming Features √ × API √ × Interface and Package × √ Pointers × √ Header files × √ Global variables × √ Template classes × √ Operator overloading × √ Multiple Inheritance √ √ Single Inheritance Inheritance √ √ Dynamic √ √ Static Binding √ √ Polymorphism √ √ Data abstraction and encapsulation in Java in C++ Features
C++ vs. Java Programming Environment C++ provides platform dependent programming Java provides platform independent programming
Fundamentals of Java Java developed by Sun Sun describes Java as: Simple, Object-oriented, Distributed, Interpreted, Robust, Secure, Architecture neutral, Portable, High-performance, Multithreaded, and Dynamic Language Java is touted as Web-savvy programming language Language for Internet Programming Better C++ Without difficulties and bug commonly encountered in C, C++ programming languages
Tools Available for Java Programming Java Developer’s Kit (JDK) JDK from  JavaSoft  a division of Sun Microsystems Inc.  Contains the basic tools and libraries necessary for creating, testing, documenting and executing Java programs There are seven main programs in JDK javac –  the Java Compiler java  – the Java Interpreter javadoc  – generates documentation in HTML
Tools Available for Java Programming Main programs in JDK (contd.) appletviewer –  the Java Interpreter to execute Java applets jdb  – the Java Debugger to find and fix bugs in Java programs javap  – the Java Disassembler to displays the accessible functions and data in a compiled class; it also displays the meaning of byte codes javah  – to create interface between Java and C routines
Tools Available for Java Programming Packages in JDK API –  the Application Programming Interface enables  Java programmers to develop varieties of applets  and applications It contains six packages: java.applet – for applet programming java.awt –  the Abstract Windowing Toolkit for designing GUI like  Button ,  Checkbox ,  Choice ,  Menu ,  Pannel  etc. java.io  – file input/output handling
Tools Available for Java Programming API in Java (contd.) java.lang  – provides useful classes like to handle  Object ,  Thread ,  Exception ,  String ,  System ,  Math ,  Float ,  Integer  etc. java.net  – classes for network programming; supports TCP/IP networking protocols java.util  – it contains miscellaneous classes like  Vector ,  Stack , List,  Date ,  Dictionary ,  Hash  etc. JDK is a free software and can be downloaded from JavaSoft’s web site at  http://java.sun.com
Third Part Tools for Java Programming Web browser Web browser in a client machine connects a link to a web site, download web page from it and then executes Java environment requires Java-enabled web browser to supports Java applets  Few (free) popular Java-enabled web browsers: HotJava  from JavaSoft web site ( http://java.sun.com ) Netscape Navigator  from Netscape home page ( http:// home.nescape.com ) Internet Explorer  from Microsoft’s web page ( http://www.microsoft.com )
Other Third Part Tools  Java IDE Number of IDEs are available to support the productivity of software development  Few important of them are: Sun’s Java Workshop dev 5  from  Sun’s JavaSoft  (recently powered with Visual Java) Mojo  from  Penumbra Software  (best visual environment for creating Java applets) Jumba   from  Aimtech and IBM  (graphical applet builder) Semantic Café  from  Semantics  (a de-facto standard for Java development on Windows systems)
Programming in Java Java programs are available in two flavors: Applet A java applet is a program that appears embedded in a web document and applet come into effect when the browser browse the web page Application   It is similar to all other kind of programs like in C, C++ to solve a particular problem In the subsequent discussions we will learn how to manage these two types of Java programs
Building a Java Application Our first Java program is a simple Application to print a message on the screen.  Let us consider the following Application: // Hello Java Application // class HelloWorldApp {   public static void main ( String args[] ) {   System.out.println (" Hello  Java   ! ");    } }
How to  edit  this program? Any text editor can be used to write Java programs. For example, In Windows Notepad,   EDIT  etc. In Unix vi ,  emacs  etc. Save the Application Save the Application in a file with the name  HelloWorldApp.java
How to  compile  this program? The Java compiler (  javac  ) converts a Java Application into Java byte code. Open a DOS shell (Windows or NT) or Terminal (Unix) Move to the directory where your Java program has been saved  Enter the following command to compile:   javac HelloWorldApp.java
How to  compile  this program? After the successful compilation, Java byte code will be produced which will be automatically stored in the same directory but with file name having extension  .class   For the running example, the class filename will be  HelloWorldApp .class
How to  execute  this program? To execute the Java Application, type the command  java  (from the command prompt). For example, for the current example HelloWorldApp Application can be execured as java HelloWorldApp Wait! Let’s recapitulate whole things once again!!
Building a Java Application
Building a Java Application Step 1: Edit and Save
Building a Java Application Step 1: Edit and Save
Building a Java Application Step 1: Edit and Save
Building a Java Application Step 1: Edit and Save
Building a Java Application Step 2: Compile
Building a Java Application Step 2: Compile
Building a Java Application Step 3: Execute
Building a Java Applet Suppose, we want to build an applet which will look like the following:
Building a Java Applet Following piece of code is required: // An applet to print Hello World! //  import  java.awt.Graphics; import java.applet.Applet; public class HelloWorld extends Applet {   public void paint (Graphics g ) { g.drawString("Hello World!" 50, 25);    } }
Building a Java Applet   Edit  ->  Save  ->  Compile Edit the code in the same fashion as an Application The name of the applet will be same as the public class, here  HelloWorld.java The program can be compiled in the same fashion as an Application is compiled. That is, javac HelloWorld.java After successful compilation,  t he  javac  will produce a file named HelloWorld.class
Building a Java Applet   Execution Edit an HTML file to host the applet just created. The HTML file will look like as: Save this to file giving a file name  HelloJava.html Note: The name of the file not necessary be the same as the name of the class; But extension should be same as the  .html Now the applet is ready for its execution! To run with  appletviewer  type the following:   appletviewer HelloJava.html <applet code = HelloJava.class width = 200 height = 100> </applet>
More on Java Application Structure of a Java Application Let us analyze the different components in the  HelloWorldApp.java class public, static, void, main String args[ ] System.out.println // Hello Java Application // class  HelloWorldApp {   public static void   main ( String args[ ] )  {   System.out.println  (&quot;Hello  Java !&quot;);    } }
General Structure of an Application
Example: Square Root Calculation /* * One more simple Java Application * * This application computes square root * */ // This is also a comment (one line comment) import java.lang.Math; class SquareRoot  { public static void main (String args[ ]) { double x = 45;  // Variable declaration and initialization   double y;   // Declaration of another variable   y = Math.sqrt (x);   System.out.println(&quot;Square root of &quot;+ x +&quot;=&quot; + y); } }
Application with Multiple Classes // Application with more than one classes  //  class FirstClass {    intidNo;   iIdNo = 555;   public static void print(  ) {    System.out.println ( &quot; First Class citizen&quot;  + idNo );    } } class SecondClass {    int idNo;   idNo = 111;   public startic void print(  ) {   System.out.println ( &quot; Second Class citizen &quot; + idNo) ;   } }
Application with Multiple Classes (contd..) public class PeopleAppln {   FirstClass female;   SecondClass male;   public static void main( String args[ ] ) {   System.out.print(&quot;People from Java World&quot;);   female.print( );   male.print( );   } }
Application without any Class! // Edit the following program as HelloNoClass.java public static void main (String args[ ] ) {   System.out.println( &quot;Hello Classless Java!]); } Type following two commands to run the Hello.java Application : javac HelloNoClass.java // To compile java  HelloNoClass // To run the program
Communication to Java Application How input can be passed to an Application while it is running? Java provides two methods for it Using the  command line arguments Using the  DataInputStream  class
Command Line Arguments class CommnadLineInputTest {    public static void main(String args[ ] ) {   int count; String aString; count = args.length; System.out.println( &quot;Number of arguments = “ +  count); for(int i = 0; i < count; i++) {   aString = args[0]; System.out.println( &quot;args[“ + I + &quot;]“ + &quot;=“ + aString); }   } }
Get Input using  DataInputStream
Get Input using  DataInputStream Calculator Program import java.io.*; class InterestCalculator { public static void main(String args[ ] ) {   Float principalAmount = new Float(0);   Float rateOfInterest = new Float(0);   int numberOfYears = 0;     DataInputStream in = new DataInputStream(System.in);   String tempString;   System.out.print(&quot;Enter Principal Amount: &quot;);   System.out.flush();   tempString = in.readLine();   principalAmount = Float.valueOf(tempString);
Calculator Program (contd..)   System.out.print(&quot;Enter Rate of Interest: &quot;);   System.out.flush();   tempString = in.readLine();   rateOfInterest = Float.valueOf(tempString);   System.out.print(&quot;Enter Number of Years: &quot;);   System.out.flush();     tempString = in.readLine();   numberOfYears = Integer.parseInt(tempString);   // Input is over: calculate the interest   int interestTotal = principalAmount*rateOfInterest*numberOfYears;     System.out.println(&quot;Total Interest = &quot; + interestTotal); } }
Applet Revisited import  java.awt.Graphics; import java.applet.Applet; public class HelloWorld extends Applet {   public void paint (Graphics g ) { g.drawString(&quot;Hello World!&quot; 50, 25);    } }
Structure of an Applet
Basic Methods in Applet public void  init( ) To initialize or pass input to an applet public void  start( ) The start( ) method called after the init( ) method, starts an applet public void  stop( ) To stop a running applet public void  paint (Graphics g) To draw something within an applet public void  destroy( ) To remove an applet from memory completely
Example: Use of init( ) // Use of init( ) method in an applet // import java.awt .Graphics ; import java.applet.Applet; public class HelloWorld extends Applet { public void init( ) {   resize(200,200); } public void paint (Graphics g ) {    g.drawString ( &quot; Hello World !&quot;, 50, 25 ); } }
One More Example: Use of init( ) // Use of  init( ) to pass value through HTML to applet // import java.awt . *; import java.applet. * ; public class RectangleTest extends applet { int x, y, w, h;  public void init (  ) {   x  = Integer.parseInt(get Parameter (&quot; xValue&quot; ));   y  = Integer.parseInt(get Parameter (&quot; yValue&quot; ));   w = Integer.parseInt(get Parameter (&quot; wValue&quot; ));   h  = Integer.parseInt(get Parameter (&quot; hValue&quot; ));  }  public void paint ( Graphics g ) {    g.drawRect (x, y, w, h ); } }
One More Example: Use of init( ) Corresponding HTML document containing this applet and providing  parameter values will be : < applet code = &quot; RectangleTest&quot; width = 150  height = 100 >  < param name = xValue  value = 20 >  < param name = yValue  value = 40 >  <param name  = wValue  value = 100> < param name = hValue  value = 50 > < /applet >
Application vs. Applet Applets  do not use main() method  for initiating the execution of code. Applets, when loaded, automatically call certain methods of  Applet class  to start and execute the code in Applets Unlike Application (stand alone), applets  cannot be run independently . They are to be  embedded in HTML pages  as applet code, which browser can run Applet  cannot read from or write to the file  in the local computers Applet  cannot communicate with other severs  in the networks Applet  cannot run any program  from local computers Applets are  restricted from using libraries  from other languages, such as, C, C++. Why applets are designed with so many restrictions??

More Related Content

Similar to Javalecture 1 (20)

PPT
Java ppts unit1
Priya11Tcs
 
PDF
Java basics notes
poonguzhali1826
 
PDF
ITFT - Java Coding
Blossom Sood
 
PPT
Java review00
saryu2011
 
PPTX
Java Programming Tutorials Basic to Advanced 1
JALALUDHEENVK1
 
PDF
Java basics notes
sanchi Sharma
 
PDF
Java basics notes
Nexus
 
PDF
Java programming basics notes for beginners(java programming tutorials)
Daroko blog(www.professionalbloggertricks.com)
 
PPSX
Java Semimar Slide (Cetpa)
Pratima Parida
 
PPSX
Java Semimar Slide (Cetpa)
Pratima Parida
 
PPTX
Java Basics.pptx from nit patna ece department
om2348023vats
 
PPTX
Chapter 2.1
sotlsoc
 
PPT
Java
kavirishi
 
PPT
Chapter 1 introduction to java technology
sshhzap
 
PPT
java swing
vannarith
 
PPT
this_is_how_to_start_coding_in_java_lang.ppt
AhmedHamzaJandoubi
 
DOCX
JAVA First Day
Sher Singh Bardhan
 
PPTX
Introduction to java by priti sajja
Priti Srinivas Sajja
 
PPTX
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
PPT
Java-Unit-I.ppt
RameswarGprec
 
Java ppts unit1
Priya11Tcs
 
Java basics notes
poonguzhali1826
 
ITFT - Java Coding
Blossom Sood
 
Java review00
saryu2011
 
Java Programming Tutorials Basic to Advanced 1
JALALUDHEENVK1
 
Java basics notes
sanchi Sharma
 
Java basics notes
Nexus
 
Java programming basics notes for beginners(java programming tutorials)
Daroko blog(www.professionalbloggertricks.com)
 
Java Semimar Slide (Cetpa)
Pratima Parida
 
Java Semimar Slide (Cetpa)
Pratima Parida
 
Java Basics.pptx from nit patna ece department
om2348023vats
 
Chapter 2.1
sotlsoc
 
Java
kavirishi
 
Chapter 1 introduction to java technology
sshhzap
 
java swing
vannarith
 
this_is_how_to_start_coding_in_java_lang.ppt
AhmedHamzaJandoubi
 
JAVA First Day
Sher Singh Bardhan
 
Introduction to java by priti sajja
Priti Srinivas Sajja
 
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
Java-Unit-I.ppt
RameswarGprec
 

Recently uploaded (20)

PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Ad

Javalecture 1

  • 2. Topic Lecture 1 C++ vs. Java Fundamentals of Java Java Application and Applet
  • 3. C++ vs. Java Area of Application C++ is best suitable for developing large software Library management system, GIS etc. Java is best suitable for developing Internet application software Network Protocols, Internet programs, web page, web browser etc.
  • 4. C++ vs. Java Programming Features √ × API √ × Interface and Package × √ Pointers × √ Header files × √ Global variables × √ Template classes × √ Operator overloading × √ Multiple Inheritance √ √ Single Inheritance Inheritance √ √ Dynamic √ √ Static Binding √ √ Polymorphism √ √ Data abstraction and encapsulation in Java in C++ Features
  • 5. C++ vs. Java Programming Environment C++ provides platform dependent programming Java provides platform independent programming
  • 6. Fundamentals of Java Java developed by Sun Sun describes Java as: Simple, Object-oriented, Distributed, Interpreted, Robust, Secure, Architecture neutral, Portable, High-performance, Multithreaded, and Dynamic Language Java is touted as Web-savvy programming language Language for Internet Programming Better C++ Without difficulties and bug commonly encountered in C, C++ programming languages
  • 7. Tools Available for Java Programming Java Developer’s Kit (JDK) JDK from JavaSoft a division of Sun Microsystems Inc. Contains the basic tools and libraries necessary for creating, testing, documenting and executing Java programs There are seven main programs in JDK javac – the Java Compiler java – the Java Interpreter javadoc – generates documentation in HTML
  • 8. Tools Available for Java Programming Main programs in JDK (contd.) appletviewer – the Java Interpreter to execute Java applets jdb – the Java Debugger to find and fix bugs in Java programs javap – the Java Disassembler to displays the accessible functions and data in a compiled class; it also displays the meaning of byte codes javah – to create interface between Java and C routines
  • 9. Tools Available for Java Programming Packages in JDK API – the Application Programming Interface enables Java programmers to develop varieties of applets and applications It contains six packages: java.applet – for applet programming java.awt – the Abstract Windowing Toolkit for designing GUI like Button , Checkbox , Choice , Menu , Pannel etc. java.io – file input/output handling
  • 10. Tools Available for Java Programming API in Java (contd.) java.lang – provides useful classes like to handle Object , Thread , Exception , String , System , Math , Float , Integer etc. java.net – classes for network programming; supports TCP/IP networking protocols java.util – it contains miscellaneous classes like Vector , Stack , List, Date , Dictionary , Hash etc. JDK is a free software and can be downloaded from JavaSoft’s web site at http://java.sun.com
  • 11. Third Part Tools for Java Programming Web browser Web browser in a client machine connects a link to a web site, download web page from it and then executes Java environment requires Java-enabled web browser to supports Java applets Few (free) popular Java-enabled web browsers: HotJava from JavaSoft web site ( http://java.sun.com ) Netscape Navigator from Netscape home page ( http:// home.nescape.com ) Internet Explorer from Microsoft’s web page ( http://www.microsoft.com )
  • 12. Other Third Part Tools Java IDE Number of IDEs are available to support the productivity of software development Few important of them are: Sun’s Java Workshop dev 5 from Sun’s JavaSoft (recently powered with Visual Java) Mojo from Penumbra Software (best visual environment for creating Java applets) Jumba from Aimtech and IBM (graphical applet builder) Semantic Café from Semantics (a de-facto standard for Java development on Windows systems)
  • 13. Programming in Java Java programs are available in two flavors: Applet A java applet is a program that appears embedded in a web document and applet come into effect when the browser browse the web page Application It is similar to all other kind of programs like in C, C++ to solve a particular problem In the subsequent discussions we will learn how to manage these two types of Java programs
  • 14. Building a Java Application Our first Java program is a simple Application to print a message on the screen. Let us consider the following Application: // Hello Java Application // class HelloWorldApp { public static void main ( String args[] ) { System.out.println (&quot; Hello Java ! &quot;); } }
  • 15. How to edit this program? Any text editor can be used to write Java programs. For example, In Windows Notepad, EDIT etc. In Unix vi , emacs etc. Save the Application Save the Application in a file with the name HelloWorldApp.java
  • 16. How to compile this program? The Java compiler ( javac ) converts a Java Application into Java byte code. Open a DOS shell (Windows or NT) or Terminal (Unix) Move to the directory where your Java program has been saved Enter the following command to compile: javac HelloWorldApp.java
  • 17. How to compile this program? After the successful compilation, Java byte code will be produced which will be automatically stored in the same directory but with file name having extension .class For the running example, the class filename will be HelloWorldApp .class
  • 18. How to execute this program? To execute the Java Application, type the command java (from the command prompt). For example, for the current example HelloWorldApp Application can be execured as java HelloWorldApp Wait! Let’s recapitulate whole things once again!!
  • 19. Building a Java Application
  • 20. Building a Java Application Step 1: Edit and Save
  • 21. Building a Java Application Step 1: Edit and Save
  • 22. Building a Java Application Step 1: Edit and Save
  • 23. Building a Java Application Step 1: Edit and Save
  • 24. Building a Java Application Step 2: Compile
  • 25. Building a Java Application Step 2: Compile
  • 26. Building a Java Application Step 3: Execute
  • 27. Building a Java Applet Suppose, we want to build an applet which will look like the following:
  • 28. Building a Java Applet Following piece of code is required: // An applet to print Hello World! // import java.awt.Graphics; import java.applet.Applet; public class HelloWorld extends Applet { public void paint (Graphics g ) { g.drawString(&quot;Hello World!&quot; 50, 25); } }
  • 29. Building a Java Applet Edit -> Save -> Compile Edit the code in the same fashion as an Application The name of the applet will be same as the public class, here HelloWorld.java The program can be compiled in the same fashion as an Application is compiled. That is, javac HelloWorld.java After successful compilation, t he javac will produce a file named HelloWorld.class
  • 30. Building a Java Applet Execution Edit an HTML file to host the applet just created. The HTML file will look like as: Save this to file giving a file name HelloJava.html Note: The name of the file not necessary be the same as the name of the class; But extension should be same as the .html Now the applet is ready for its execution! To run with appletviewer type the following: appletviewer HelloJava.html <applet code = HelloJava.class width = 200 height = 100> </applet>
  • 31. More on Java Application Structure of a Java Application Let us analyze the different components in the HelloWorldApp.java class public, static, void, main String args[ ] System.out.println // Hello Java Application // class HelloWorldApp { public static void main ( String args[ ] ) { System.out.println (&quot;Hello Java !&quot;); } }
  • 32. General Structure of an Application
  • 33. Example: Square Root Calculation /* * One more simple Java Application * * This application computes square root * */ // This is also a comment (one line comment) import java.lang.Math; class SquareRoot { public static void main (String args[ ]) { double x = 45; // Variable declaration and initialization double y; // Declaration of another variable y = Math.sqrt (x); System.out.println(&quot;Square root of &quot;+ x +&quot;=&quot; + y); } }
  • 34. Application with Multiple Classes // Application with more than one classes // class FirstClass { intidNo; iIdNo = 555; public static void print( ) { System.out.println ( &quot; First Class citizen&quot; + idNo ); } } class SecondClass { int idNo; idNo = 111; public startic void print( ) { System.out.println ( &quot; Second Class citizen &quot; + idNo) ; } }
  • 35. Application with Multiple Classes (contd..) public class PeopleAppln { FirstClass female; SecondClass male; public static void main( String args[ ] ) { System.out.print(&quot;People from Java World&quot;); female.print( ); male.print( ); } }
  • 36. Application without any Class! // Edit the following program as HelloNoClass.java public static void main (String args[ ] ) { System.out.println( &quot;Hello Classless Java!]); } Type following two commands to run the Hello.java Application : javac HelloNoClass.java // To compile java HelloNoClass // To run the program
  • 37. Communication to Java Application How input can be passed to an Application while it is running? Java provides two methods for it Using the command line arguments Using the DataInputStream class
  • 38. Command Line Arguments class CommnadLineInputTest { public static void main(String args[ ] ) { int count; String aString; count = args.length; System.out.println( &quot;Number of arguments = “ + count); for(int i = 0; i < count; i++) { aString = args[0]; System.out.println( &quot;args[“ + I + &quot;]“ + &quot;=“ + aString); } } }
  • 39. Get Input using DataInputStream
  • 40. Get Input using DataInputStream Calculator Program import java.io.*; class InterestCalculator { public static void main(String args[ ] ) { Float principalAmount = new Float(0); Float rateOfInterest = new Float(0); int numberOfYears = 0; DataInputStream in = new DataInputStream(System.in); String tempString; System.out.print(&quot;Enter Principal Amount: &quot;); System.out.flush(); tempString = in.readLine(); principalAmount = Float.valueOf(tempString);
  • 41. Calculator Program (contd..) System.out.print(&quot;Enter Rate of Interest: &quot;); System.out.flush(); tempString = in.readLine(); rateOfInterest = Float.valueOf(tempString); System.out.print(&quot;Enter Number of Years: &quot;); System.out.flush(); tempString = in.readLine(); numberOfYears = Integer.parseInt(tempString); // Input is over: calculate the interest int interestTotal = principalAmount*rateOfInterest*numberOfYears; System.out.println(&quot;Total Interest = &quot; + interestTotal); } }
  • 42. Applet Revisited import java.awt.Graphics; import java.applet.Applet; public class HelloWorld extends Applet { public void paint (Graphics g ) { g.drawString(&quot;Hello World!&quot; 50, 25); } }
  • 43. Structure of an Applet
  • 44. Basic Methods in Applet public void init( ) To initialize or pass input to an applet public void start( ) The start( ) method called after the init( ) method, starts an applet public void stop( ) To stop a running applet public void paint (Graphics g) To draw something within an applet public void destroy( ) To remove an applet from memory completely
  • 45. Example: Use of init( ) // Use of init( ) method in an applet // import java.awt .Graphics ; import java.applet.Applet; public class HelloWorld extends Applet { public void init( ) { resize(200,200); } public void paint (Graphics g ) { g.drawString ( &quot; Hello World !&quot;, 50, 25 ); } }
  • 46. One More Example: Use of init( ) // Use of init( ) to pass value through HTML to applet // import java.awt . *; import java.applet. * ; public class RectangleTest extends applet { int x, y, w, h; public void init ( ) { x = Integer.parseInt(get Parameter (&quot; xValue&quot; )); y = Integer.parseInt(get Parameter (&quot; yValue&quot; )); w = Integer.parseInt(get Parameter (&quot; wValue&quot; )); h = Integer.parseInt(get Parameter (&quot; hValue&quot; )); } public void paint ( Graphics g ) { g.drawRect (x, y, w, h ); } }
  • 47. One More Example: Use of init( ) Corresponding HTML document containing this applet and providing parameter values will be : < applet code = &quot; RectangleTest&quot; width = 150 height = 100 > < param name = xValue value = 20 > < param name = yValue value = 40 > <param name = wValue value = 100> < param name = hValue value = 50 > < /applet >
  • 48. Application vs. Applet Applets do not use main() method for initiating the execution of code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the code in Applets Unlike Application (stand alone), applets cannot be run independently . They are to be embedded in HTML pages as applet code, which browser can run Applet cannot read from or write to the file in the local computers Applet cannot communicate with other severs in the networks Applet cannot run any program from local computers Applets are restricted from using libraries from other languages, such as, C, C++. Why applets are designed with so many restrictions??