Javalecture 1

48
Object Oriented Object Oriented Programming with Java Programming with Java

Transcript of Javalecture 1

Object Oriented Programming Object Oriented Programming with Javawith Java

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

22

TopicTopicLecture 1Lecture 1

C++ vs. JavaC++ vs. Java

Fundamentals of JavaFundamentals of Java

Java Application and AppletJava Application and Applet

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

33

C++ vs. JavaC++ vs. Java

Area of ApplicationArea of Application– C++ is best suitable for developing large C++ is best suitable for developing large

softwaresoftware Library management system, GIS etc.Library management system, GIS etc.

– Java is best suitable for developing Internet Java is best suitable for developing Internet application softwareapplication software Network Protocols, Internet programs, web page, Network Protocols, Internet programs, web page,

web browser etc.web browser etc.

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

44

C++ vs. JavaC++ vs. Java Programming FeaturesProgramming Features

Features in C++ in Java

Data abstraction and encapsulation √ √

Polymorphism √ √

BindingStatic √ √

Dynamic √ √

Inheritance

Single Inheritance √ √

Multiple Inheritance √ ×

Operator overloading √ ×

Template classes √ ×

Global variables √ ×

Header files √ ×

Pointers √ ×

Interface and Package × √

API × √

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

55

C++ vs. JavaC++ vs. Java

Programming Programming EnvironmentEnvironment– C++ provides platform C++ provides platform

dependent dependent programmingprogramming

– Java provides platform Java provides platform independent independent programmingprogramming

C++ sourcecode

C++Complier

C++ objectcode

Java sourcecode

Java BYTEcode

Javacompiler

Javainterprter

W IN32

Javainterprter

Solaris

Javainterprter

M acintosh

Intel Pentium Sun Solaris Apple Macintosh

JVM

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

66

Fundamentals of JavaFundamentals of Java

Java developed by SunJava developed by Sun Sun describes Java as:Sun describes Java as:

– Simple, Object-oriented, Distributed, Interpreted, Simple, Object-oriented, Distributed, Interpreted, Robust, Secure, Architecture neutral, Portable, High-Robust, Secure, Architecture neutral, Portable, High-performance, Multithreaded, and Dynamic Languageperformance, Multithreaded, and Dynamic Language

Java is touted asJava is touted as– Web-savvy programming languageWeb-savvy programming language– Language for Internet ProgrammingLanguage for Internet Programming– Better C++Better C++

Without difficulties and bug commonly encountered in C, C++ Without difficulties and bug commonly encountered in C, C++ programming languagesprogramming languages

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

77

Tools Available for Java ProgrammingTools Available for Java Programming

Java Developer’s Kit (JDK)Java Developer’s Kit (JDK)– JDK from JDK from JavaSoft JavaSoft a division of Sun a division of Sun

Microsystems Inc. Microsystems Inc. – Contains the basic tools and libraries necessary Contains the basic tools and libraries necessary

for creating, testing, documenting and executing for creating, testing, documenting and executing Java programsJava programs

– There are seven main programs in JDKThere are seven main programs in JDK javac – javac – the Java Compilerthe Java Compiler javajava – the Java Interpreter – the Java Interpreter javadocjavadoc – generates documentation in HTML – generates documentation in HTML

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

88

Tools Available for Java ProgrammingTools Available for Java Programming

– Main programs in JDK (contd.)Main programs in JDK (contd.) appletviewer – appletviewer – the Java Interpreter to execute Java the Java Interpreter to execute Java

appletsapplets jdbjdb – the Java Debugger to find and fix bugs in Java – the Java Debugger to find and fix bugs in Java

programsprograms javapjavap – the Java Disassembler to displays the – the Java Disassembler to displays the

accessible functions and data in a compiled class; it accessible functions and data in a compiled class; it also displays the meaning of byte codesalso displays the meaning of byte codes

javahjavah – to create interface between Java and C – to create interface between Java and C routinesroutines

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

99

Tools Available for Java ProgrammingTools Available for Java Programming

Packages in JDKPackages in JDK– API – API – the Application Programming Interface the Application Programming Interface

enables Java programmers to develop varieties enables Java programmers to develop varieties of applets and applicationsof applets and applications

– It contains six packages:It contains six packages: java.applet – for applet programmingjava.applet – for applet programming java.awt – java.awt – the Abstract Windowing Toolkit for the Abstract Windowing Toolkit for

designing GUI like designing GUI like ButtonButton, , CheckboxCheckbox, , ChoiceChoice, , MenuMenu, , PannelPannel etc. etc.

java.iojava.io – file input/output handling – file input/output handling

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1010

Tools Available for Java ProgrammingTools Available for Java Programming

– API in Java (contd.)API in Java (contd.) java.langjava.lang – provides useful classes like to handle – provides useful classes like to handle

ObjectObject, , ThreadThread, , ExceptionException, , StringString, , SystemSystem, , MathMath, , FloatFloat, , IntegerInteger etc. etc.

java.netjava.net – classes for network programming; – classes for network programming; supports TCP/IP networking protocolssupports TCP/IP networking protocols

java.util java.util – it contains miscellaneous classes like – it contains miscellaneous classes like VectorVector, , StackStack, List, , List, DateDate, , DictionaryDictionary, , HashHash etc. etc.

JDK is a free software and can be downloaded from JDK is a free software and can be downloaded from JavaSoft’s web site at JavaSoft’s web site at http://java.sun.comhttp://java.sun.com

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1111

Third Part Tools for Java ProgrammingThird Part Tools for Java Programming

Web browserWeb browser– Web browser in a client machine connects a link Web browser in a client machine connects a link

to a web site, download web page from it and then to a web site, download web page from it and then executesexecutes

– Java environment requires Java-enabled web Java environment requires Java-enabled web browser to supports Java applets browser to supports Java applets

– Few (free) popular Java-enabled web browsers:Few (free) popular Java-enabled web browsers: HotJavaHotJava from JavaSoft web site ( from JavaSoft web site (http://java.sun.comhttp://java.sun.com)) Netscape NavigatorNetscape Navigator from Netscape home page ( from Netscape home page (http://http://

home.nescape.comhome.nescape.com)) Internet ExplorerInternet Explorer from Microsoft’s web page ( from Microsoft’s web page (

http://www.microsoft.comhttp://www.microsoft.com))

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1212

Other Third Part Tools Other Third Part Tools

Java IDEJava IDE– Number of IDEs are available to support the Number of IDEs are available to support the

productivity of software development productivity of software development – Few important of them are:Few important of them are:

Sun’s Java Workshop dev 5Sun’s Java Workshop dev 5 from from Sun’s JavaSoft Sun’s JavaSoft (recently powered with Visual Java)(recently powered with Visual Java)

MojoMojo from from Penumbra Software Penumbra Software (best visual environment (best visual environment for creating Java applets)for creating Java applets)

JumbaJumba fromfrom Aimtech and IBM Aimtech and IBM (graphical applet builder)(graphical applet builder) Semantic CaféSemantic Café from from Semantics Semantics (a de-facto standard for (a de-facto standard for

Java development on Windows systems)Java development on Windows systems)

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1313

Programming in JavaProgramming in Java Java programs are available in two flavors:Java programs are available in two flavors:

– AppletApplet A java applet is a program that appears embedded in A java applet is a program that appears embedded in

a web document and applet come into effect when a web document and applet come into effect when the browser browse the web pagethe browser browse the web page

– ApplicationApplication It is similar to all other kind of programs like in C, C+It is similar to all other kind of programs like in C, C+

+ to solve a particular problem+ to solve a particular problem

In the subsequent discussions we will learn how to manage In the subsequent discussions we will learn how to manage

these two types of Java programsthese two types of Java programs

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1414

Building a Java ApplicationBuilding a Java ApplicationOur first Java program is a simple Application to print a Our first Java program is a simple Application to print a

message on the screen. message on the screen.

Let us consider the following Application:Let us consider the following Application:

1.1. // Hello Java Application //// Hello Java Application //

2.2. class HelloWorldApp {class HelloWorldApp {

3.3. public static void main ( String args[] ) {public static void main ( String args[] ) {

4.4. System.out.println ("System.out.println ("Hello JavaHello Java !!"); ");

5.5. }}

6.6. }}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1515

How to How to editedit this program? this program?

Any text editor can be used to write Java Any text editor can be used to write Java programs. For example,programs. For example,– In WindowsIn Windows

Notepad,Notepad, EDIT EDIT etc.etc.

– In UnixIn Unix vivi, , emacsemacs etc. etc.

Save the ApplicationSave the Application– Save the Application in a file with the name Save the Application in a file with the name

HelloWorldApp.javaHelloWorldApp.java

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1616

How to How to compilecompile this program? this program?

The Java compiler ( The Java compiler ( javac javac ) converts a Java ) converts a Java Application into Java byte code.Application into Java byte code.– Open a DOS shell (Windows or NT) or Terminal Open a DOS shell (Windows or NT) or Terminal

(Unix)(Unix)– Move to the directory where your Java program Move to the directory where your Java program

has been saved has been saved – Enter the following command to compile:Enter the following command to compile:

javac HelloWorldApp.javajavac HelloWorldApp.java

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1717

How to How to compilecompile this program? this program?

After the successful compilation, Java byte After the successful compilation, Java byte code will be produced which will be code will be produced which will be automatically stored in the same directory automatically stored in the same directory but with file name having extension but with file name having extension .class.class

For the running example, the class filename For the running example, the class filename will be will be

HelloWorldAppHelloWorldApp.class.class

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1818

How to How to executeexecute this program? this program?

To execute the Java Application, type the To execute the Java Application, type the command command javajava (from the command prompt). (from the command prompt).

For example, for the current example For example, for the current example HelloWorldApp Application can be execured HelloWorldApp Application can be execured asas

java HelloWorldAppjava HelloWorldApp

Wait! Let’s recapitulate whole things once again!!Wait! Let’s recapitulate whole things once again!!

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

1919

Building a Java ApplicationBuilding a Java Application

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2020

Building a Java ApplicationBuilding a Java ApplicationStep 1: Edit and SaveStep 1: Edit and Save

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2121

Building a Java ApplicationBuilding a Java Application

Step 1: Edit and SaveStep 1: Edit and Save

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2222

Building a Java ApplicationBuilding a Java ApplicationStep 1: Edit and SaveStep 1: Edit and Save

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2323

Building a Java ApplicationBuilding a Java ApplicationStep 1: Edit and SaveStep 1: Edit and Save

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2424

Building a Java ApplicationBuilding a Java ApplicationStep 2: CompileStep 2: Compile

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2525

Building a Java ApplicationBuilding a Java ApplicationStep 2: CompileStep 2: Compile

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2626

Building a Java ApplicationBuilding a Java ApplicationStep 3: ExecuteStep 3: Execute

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2727

Building a Java AppletBuilding a Java Applet

Suppose, we want to build an applet which will Suppose, we want to build an applet which will look like the following:look like the following:

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2828

Building a Java AppletBuilding a Java Applet

Following piece of code is required:Following piece of code is required:

1.1. // An applet to print Hello World! // // An applet to print Hello World! //

2.2. import java.awt.Graphics;import java.awt.Graphics;

3.3. import java.applet.Applet;import java.applet.Applet;

4.4. public class HelloWorld extends Applet {public class HelloWorld extends Applet {

5.5. public void paint (Graphics g ) {public void paint (Graphics g ) {

6.6. g.drawString("Hello World!" 50, g.drawString("Hello World!" 50, 25); 25);

7.7. }}

8.8. }}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

2929

Building a Java AppletBuilding a Java Applet Edit Edit →→ Save Save →→ Compile Compile

Edit the code in the same fashion as an ApplicationEdit the code in the same fashion as an Application The name of the applet will be same as the public The name of the applet will be same as the public

class, here class, here

HelloWorld.javaHelloWorld.java The program can be compiled in the same fashion The program can be compiled in the same fashion

as an Application is compiled. That is,as an Application is compiled. That is,

javac HelloWorld.javajavac HelloWorld.java

After successful compilation,After successful compilation, t the he javacjavac will produce will produce a file nameda file named

HelloWorld.classHelloWorld.class

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3030

Building a Java AppletBuilding a Java Applet ExecutionExecution

Edit an HTML file to host the applet just created. The Edit an HTML file to host the applet just created. The HTML file will look like as:HTML file will look like as:

Save this to file giving a file name Save this to file giving a file name HelloJava.htmlHelloJava.html

Note: The name of the file not necessary be the same Note: The name of the file not necessary be the same as the name of the class; But extension should be as the name of the class; But extension should be same as the same as the .html.html

Now the applet is ready for its execution!Now the applet is ready for its execution! To run with To run with appletviewerappletviewer type the following: type the following:

appletviewer HelloJava.htmlappletviewer HelloJava.html

<applet code = HelloJava.class width = 200 height = 100></applet>

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3131

More on Java ApplicationMore on Java ApplicationStructure of a Java ApplicationStructure of a Java Application

Let us analyze the different components in the Let us analyze the different components in the HelloWorldApp.javaHelloWorldApp.java

classclasspublic, static, void, mainpublic, static, void, mainString args[ ]String args[ ]System.out.printlnSystem.out.println

// Hello Java Application //// Hello Java Application //

classclass HelloWorldApp { HelloWorldApp { public static voidpublic static void main ( String args[ ] )main ( String args[ ] ) { {

System.out.printlnSystem.out.println ("Hello Java !"); ("Hello Java !"); }}}}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3232

General Structure of an ApplicationGeneral Structure of an Application

D o cu m en t sec tio n (o p tio n a l)

P ack ag e s ta tem en t (o p tio n a l)

In te rface s ta tem en t (o p tio n a l)

C lass d e fin itio n (s ) (o p tio n a l)

M a in c lass d e fin itio n { m a in m e th o d d e fin itio n }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3333

Example: Square Root CalculationExample: 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("Square root of "+ x +"=" + y);

} }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3434

Application with Multiple ClassesApplication with Multiple Classes// Application with more than one classes //

class FirstClass { intidNo; iIdNo = 555; public static void print( ) { System.out.println ( " First Class citizen" + idNo ); }}

class SecondClass { int idNo; idNo = 111; public startic void print( ) { System.out.println ( " Second Class citizen " + idNo) ; }}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3535

Application with Multiple ClassesApplication with Multiple Classes(contd..)(contd..)

public class PeopleAppln { FirstClass female; SecondClass male; public static void main( String args[ ] ) { System.out.print("People from Java World"); female.print( ); male.print( ); }

}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3636

Application without any Class!Application without any Class!

// Edit the following program as HelloNoClass.java

public static void main (String args[ ] ) { System.out.println( "Hello Classless Java!]);}

Type following two commands to run the Hello.java Application :

javac HelloNoClass.java // To compilejava HelloNoClass // To run the program

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3737

Communication to Java ApplicationCommunication to Java Application

How input can be passed to an Application How input can be passed to an Application while it is running?while it is running?

Java provides two methods for itJava provides two methods for it– Using the Using the command line argumentscommand line arguments– Using theUsing the DataInputStream DataInputStream classclass

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3838

Command Line ArgumentsCommand Line Arguments1.1. class CommnadLineInputTestclass CommnadLineInputTest2.2. { { 3.3. public static void main(String args[ ] ) {public static void main(String args[ ] ) {4.4. int count;int count;5.5. String aString;String aString;6.6. count = args.length;count = args.length;7.7.8.8. System.out.println( "Number of arguments = “ + count);System.out.println( "Number of arguments = “ + count);9.9.10.10. for(int i = 0; i < count; i++) {for(int i = 0; i < count; i++) {11.11. aString = args[0];aString = args[0];12.12. System.out.println( "args[“ + I + "]“ + "=“ + aString);System.out.println( "args[“ + I + "]“ + "=“ + aString);13.13. }}14.14. }}15.15. } }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

3939

Get Input using Get Input using DataInputStreamDataInputStream

principalAm ount

rateOfInterest

num berOfYears

interestTotal

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4040

Get Input using Get Input using DataInputStreamDataInputStreamCalculator ProgramCalculator 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("Enter Principal Amount: "); System.out.flush(); tempString = in.readLine(); principalAmount = Float.valueOf(tempString);

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4141

Calculator Program (contd..)Calculator Program (contd..)

System.out.print("Enter Rate of Interest: "); System.out.flush(); tempString = in.readLine(); rateOfInterest = Float.valueOf(tempString);

System.out.print("Enter Number of Years: "); System.out.flush(); tempString = in.readLine(); numberOfYears = Integer.parseInt(tempString);

// Input is over: calculate the interest int interestTotal = principalAmount*rateOfInterest*numberOfYears; System.out.println("Total Interest = " + interestTotal);

} }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4242

Applet RevisitedApplet Revisitedimport java.awt.Graphics;import java.awt.Graphics;

import java.applet.Applet;import java.applet.Applet; public class HelloWorld extends Applet {public class HelloWorld extends Applet { public void paint (Graphics g ) {public void paint (Graphics g ) { g.drawString("Hello World!" 50, g.drawString("Hello World!" 50,

25); 25); }} }}

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4343

Structure of an AppletStructure of an Applet

Im p o rt S e c tio n P a rt 1

V a ria b le d e c la ra tio n (s ) P a rt 3

Ja v a c o d e to a c c o m p lish e d a ta sk

M e th o d (s ) fo r o b je c t in te ra c tio n d e c la re d a n d d e fin e d h e re

p u b lic c la s s N e w A p p le tN a m e e x te n d s A p p le t { P a rt 2

}

P a rt 4

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4444

Basic Methods in AppletBasic Methods in Applet public void public void init( )init( )

– To initialize or pass input to an appletTo initialize or pass input to an applet public void public void start( )start( )

– The start( ) method called after the init( ) method, starts The start( ) method called after the init( ) method, starts an appletan applet

public void public void stop( )stop( )– To stop a running appletTo stop a running applet

public void public void paint (Graphics g)paint (Graphics g)– To draw something within an appletTo draw something within an applet

public void public void destroy( )destroy( )– To remove an applet from memory completelyTo remove an applet from memory completely

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4545

Example: Use of init( )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 ( " Hello World !", 50, 25 );

} }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4646

One More Example: Use of init( )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 (" xValue" )); y = Integer.parseInt(get Parameter (" yValue" )); w = Integer.parseInt(get Parameter (" wValue" )); h = Integer.parseInt(get Parameter (" hValue" )); }

public void paint ( Graphics g ) { g.drawRect (x, y, w, h );

} }

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4747

One More Example: Use of init( )One More Example: Use of init( )

Corresponding HTML document containing this applet and providing parameter values will be :

< applet code = " RectangleTest" 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 >

18.04.2318.04.23 Short Term Course on C++ and Java, Short Term Course on C++ and Java, 14-30 June, 2004, IIT Kharagpur, Lec14-30 June, 2004, IIT Kharagpur, Lecture #1ture #1

4848

Application vs. AppletApplication vs. Applet Applets Applets do not use main() methoddo not use main() method for initiating the for initiating the

execution of code. Applets, when loaded, automatically call execution of code. Applets, when loaded, automatically call certain methods of certain methods of Applet classApplet class to start and execute the to start and execute the code in Appletscode in Applets

Unlike Application (stand alone), applets Unlike Application (stand alone), applets cannot be run cannot be run independentlyindependently. They are to be . They are to be embedded in HTML pagesembedded in HTML pages as applet code, which browser can runas applet code, which browser can run

Applet Applet cannot read from or write to the filecannot read from or write to the file in the local in the local computerscomputers

Applet Applet cannot communicate with other severscannot communicate with other severs in the in the networksnetworks

Applet Applet cannot run any programcannot run any program from local computers from local computers Applets are Applets are restricted from using librariesrestricted from using libraries from other from other

languages, such as, C, C++.languages, such as, C, C++.

Why applets are designed with so many restrictions??Why applets are designed with so many restrictions??