Java Notes 2
Java Notes 2
Java Notes 2
• Introduction
• Building Java Applications
• Building Java applets
o Basic Methods in Applet
• Differences between applet and Application
• Practice Questions
• Assignment
• Q&A
Introduction
Java provides us to write Java programs in two flavors : applets and Applications. These two kind
of programs are differ by the way how a browser and Java interpreter will deal them. Simply
speaking, a Java applet is a program that appears embedded in a web document, whereas, a
Java Application (it is expressed with capital letters to differentiate from all programs as
applications) is the term applied to all other kind of Java programs. There is however number of
technical differences between applet and Application. Before gong to discuss about their
differences, let us see how these two kind of programs can be developed.
class helloworld{
public static void main(String args[]){
System.out.println("Hello, World!");
System.out.println("Hi...."+" Debasis");
}
}
These lines comprise the minimum components necessary to print Hello Java ! onto the screen .
NOTE:
1. How to edit this Program: Java program Can be written with any text
editor. In Windows or System 7.5 we can use Notepad or EDIT, in Unix vi
or emacs can be used. Save this file having name HelloJavaAppln.Java.
The name of the Java source file is not arbitrary; it must be the same as the
name of the public class (here it is HelloJavaAppln) and extension must be
java.
2. How to compile this Program : The Java compiler converts the Java
programs into Java byte codes.
For Window 95 and NT users, you will need to open a DOS Shell window
make sure that you are in the directory you are using to store your Java
classes, then enter the following command :
javac helloworld.java
After the successful compilation, Java byte codes will be produced which
will be automatically stored in the same directory but with file name
having extension .class ( e.g. here the class file name will be
HelloJavaAppln.class).
3.How to run the Java Application: To run the Application, you have to
type the command java ( from the commend prompt ).
For example, our helloworld Application can be run as:
java helloworld
With this the Java interpreter will be invoked and it executes the byte code
stored in helloworld.class file. The output then will appear onto the
screen.
4. Basic structure of any Application : An Application must contain at
least one class which include the main function. It may contain more than
one class also. In any case, the name of the Application (program file )
will be according to the name of the class which contains main
(�) function.
Illustration 2.2
// TestArray.java
class TestArray{
public static void main(String args[]){
int b[]= {10, 20, 30, 40, 50}; //Initialization
//Traversing array
for (int i=0; i < a.length; i++){ //length is the property of array
System.out.print(a[i]+" ");
}
System.out.println();
// Average calculation
float sum = 0, avg;
for(int i=0; i < a.length;i++) //Calculating the sum of the numbers
sum += a[i];
avg = sum/a.length;
System.out.println("Average = " + avg);
}
}
OUTPUT:
10 20 30 40 50
Average = 30.0
Illustration 2.3
// a3DArray.java
class a3DArray {
public static void main(String args[]) {
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
my3DArray[i][j][k] = i * j * k;
OUTPUT:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Note:
The source code stored in a program file whose extension is java; the
compiled version of the program file is stored in a file having same
name as the source program file but having extension class. These
class files are containing java byte code and can be interpreted by
Java run time environment i.e. Java interpreter.
Illustration 2.4
class Demonstration_41
{
public static void main(String[] args) {
int x=555;
System.out.println("1. println ");
System.out.println("2. println ");
OUTPUT:
1. println
2. println
1. print
2. print 3. Print 555
Illustration 2.5
class Demonstration_42
{
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple integer: x = %d\n", x);
float n = 5.2f;
n = 2324435.3f;
OUTPUT:
Printing simple integer: x = 100
Formatted with precison: PI = 3.
14
Formatted to specific width: n =
5.2
Formatted to right margin: n = 2
324435.25
Illustration 2.6
/* Command line input in Java */
// Edit Demonstration_43.java
//}
//System.out.print(args[i]+" ");
//System.exit(0);
}
}
Illustration 2.7
OUTPUT:
No command line arguments found.
Illustration 2.8
Illustration 2.9
/*The following program snippet shows how to read and write to the console.*/
//Edit Demonstration_46.java
import java.util.*;
Illustration 2.10
import java.io.*;
class Demonstration_47{
public static void main(String args[ ] ) throws Exception { // throws Exception
Float principalAmount = new Float(0);
Float rateOfInterest = new Float(0);
int numberOfYears = 0;
//try{
DataInputStream in = new DataInputStream(System.in);
String tempString;
System.out.print("Enter Principal Amount: ");
System.out.flush();
tempString = in.readLine();
principalAmount = Float.valueOf(tempString);
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
float interestTotal =
principalAmount*rateOfInterest*numberOfYears;
System.out.println("Total Interest = " + interestTotal);
// }
// catch (Exception ex)
// {}
}
}
import java.awt.Graphics;
import java.applet.Applet;
public class HelloJava extends Applet {
public void paint (Graphics g ) {
// Html code
< html>
< body>
< applet code=" HelloJava.class" width="200" height="100">
< / applet>
< / body>
< / html>
These are the essential code to display the message Hello Java ! onto the screen. Novice
programmer may be puzzled with so many new lines, but this is just for an adventure, actual
understanding will take place in due time. This applet will be edited in the same fashion as
Application. The name of the applets will be same as the public class ( here HelloJava.java ).
The program then can be compiled using javac in the same manner as an Application is
compiled. The Java compiler produces a file named HelloJava.class .
How to run the Java applet : Before going to run the Java applet, we have to create an HTML
document to host it. In HTML, type this few line through any editor (don�t worry, everything will
be discussed in detail).
< applet code = HelloJava.class width =200 height =100> < / app
let >
This is the minimum HTML Page for running the Java Applet HelloJava. Save this file by giving a
name HelloJava.html (the name of the file should be same as the name of the class and
extension must be html ).
Afte the HTML page is prepared, the applet is ready for execution.If you have any browser ( like
HotJava or Netscape), invoke this browser, open the HTML file and click then RUN button on it.
Other way, the JDK includes a program appletviewer which also can be used to run the applet.
Type the following command on command line:
appletviewer HelloJava.html.
NOTE:
Figure 2.1 represents the basic components in any Java applet : Let us
explain the various parts in context of the applet HelloJava :
Part 1: HelloJava imports two classes, namely :
java.awt.Graphics;
java.applet.Applet;
The different classes that can be imported will be discussed in due
time.
Part 2:Name of the applet HelloJava is placed in place
of NewAppletName.
Part 3 : There are no variable declared and used in this applet . This
part is hence, optional.
Part 4:Only one method vide public void paint( Graphics g ) is
declared in this applet which is defined with a function drawString
(��) ; this function is defined in Graphics.class.
Here, Part 4 is the main component in any applet. This includes the
various method(s) which actually defines the applet. These methods are
responsible for interacting between the browser and applet. In fact, no
user defined routines are required to define an applet. There are number
of routines available in the class Applet. Programmer can use these or
can override these function. Following Section 2.2.1 gives an idea
about these methods
Figure 2.1 Basic Structure of an applet
Illustration 2.12 :
/* A "Hello, World" Applet*/
// Demonstration_22.java
import java.applet.*;
import java.awt.*;
// Html code
< html>
< title>The Hello, World Applet< / title>
< hr>
< applet code = "Demonstration_22.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
< / applet>
< hr>
< / html>
The init ( ) method gets called first. This member function is called only once and is called at the
time the applet is created and first loaded into Java-enabled browser (such as the appletviewer ).
Illustration 2.13
/* Resize Applet Window Example*/
// Demonstration_23.java
import java.applet.Applet;
import java.awt.Graphics;
// Html code
< html>
< title>The Hello, World Applet< / title>
< hr>
< applet code = "Demonstration_23.class" width = "200" height = "200">
< / applet>
< hr>
< / html>
One can pass number of information to an applet through HTML document by init( )
method. Illustration 2.14 is such an attempt.
Corresponding HTML document containing this applet and providing parameter values is
mentioned as below :
< 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 >
Observe, how < param �.> tag and getParameter (String S ) ( defined in Applet Class ) can be
used. It is not necessary that getParameter(..) should be in the same order as parameter
values passed in HTML; also if some parameter is not available, getParameter(..) will
return a default value which is null.
Suppose, this applet is loaded in an HTML file, and that HTML document is displayed on the
screen; there is a link point on the document for the applet. If we click this link point ( by mouse )
then this applet will start its working. With the help of this function, then an applet can be called
multiple times if the user keeps leaving and returning to the HTML document. It can be noted
that, init() is called once - the first time an applet is loaded, start() is called each time the
applet�s link is activated. Actual illustration of start() method will take place after
discussing Thread and Event.
Public void stop()
The stop() method stops the applet running. This method is called when the browser wishes to
stop executing the document or whenever the user leaves the applet. This method can be
overriden in an applet, an example includes as below :
This method is called when the browser determines that the applets need to be remove
completely from memory. The java.applet.Applet class does nothing in this member function, In
the applet class (derived class ), therefore, user should override this method to do final cleanup
and freeing any resources holding the ceased applet. Detail use of this method will be illustrated
during the discussion of Multi-threading in Java (Chapter 6, Part II).
Illustration 2.15
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
// Html code
< html>
< title>The Hello, World Applet< / title>
< hr>
< applet code = "Demonstration_24.class" width = "200" height = "200">
< / applet>
< hr>
< / html>
Illustration 2.16
// Html code
< html>
< title> The Hello, World Applet < / title>
< hr>
< applet code = " Demonstration_25.class" width = "480" height = "320">
< param name = "color" value = "blue">
< param name = "squaresize" value = "30">
< / applet>
< hr>
< / html>
Illustration 2.17
import java.applet.Applet;
import java.awt.Graphics;
public class Demonstration_26 extends Applet{
/*
< applet code="Demonstration_26.class" width="300" height="300">
< / applet>
*/
Table 2.1
Technical Point Java Application Java applet
Method expected by the JVM main ( ) - start up routine No main ( ) but some
methods
Practice questions
Practice 2.1
/*
One more simple Java Application. This application computes square root */
//Edit SquareRoot.java
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);
}
}
Is the compilation successful? What is the output?
Practice 2.2
/*
Example java program without any class
*/
// Edit HelloNoClass.java
Practice 2.3
/*
Application with more than one classes within same java file
*/
//Edit PeopleApp.java
class FirstClass {
int idNo;
idNo = 555;
public static void print( ) {
System.out.println ( " First Class citizen" + idNo );
}
}
class SecondClass {
int idNo;
idNo = 111;
public static void print( ) {
System.out.println ( " Second Class citizen " + idNo) ;
}
}
public class PeopleApp {
FirstClass female;
SecondClass male;
public static void main( String args[ ] ) {
System.out.print("People from Java World");
female.print( );
male.print( );
}
}
(This problem has a minor mistake. Identify the mistake and then write the correct
code.)
Practice 2.4
/*
Application with more than one class in separate java file
*/
//Edit AnotherFirstClass.java
class AnotherFirstClass {
static int idNo = 777;
public static void print( ) {
System.out.println ( " First Class citizen" + idNo );
}
}
//Edit AnotherSecondClass.java
class AnotherSecondClass {
static int idNo = 888;
public static void print( ) {
System.out.println ( " Second Class citizen " + idNo) ;
}
}
//Edit AnotherPeopleApp.java
class CommnadLineInputTest{
public static void main(String args[ ] ) {
int count;
String aString;
count = args.length;
import java.io.*;
class ReadNumber{
public static void main(String args[ ] ) {
Float number1 = new Float(0);
Float number2 = new Float(0);
System.out.println("Number 1: "+number1);
System.out.println("Number 2: "+number2);
}
What is the output?
Practice 2.7
/* while loop example */
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Assignment
Q: Write java program to calculate the Square of a number.
Q: Write java program to add two numbers, take input as command line
argument.
Q: Write java program to multiply two numbers, numbers should be taken
from standard input.
Q: Write Java program to read the three integers a, b and c from the
keyboard and then print the largest value read.
Q: Write a Java Application to read the name of a student (studentName),
roll Number (rollNo) and marks (totalMarks) obtained. rollNo may be an
alphanumeric string. Display the data as read..
Q: Write Java program to calculate the perimeter and the area of the circle.
The radius of the circle is taken as user input. Use to different functions
to calculate the perimeter and area. Define the value of PI as class
constant.
Q: Write a program to check the number is even or odd. Input is taken from
keyboard.
Q: Write a program to find out the number of days in a month using switch-
case. Month number and year is taken as input through keyboard.
Q: Write java program to calculate the Sum of the square of first 10 integers.
Q: Write java program to calculate the Factorial of a 10 (iteratively and
recursively).
Q: Write a program to calculate the grade of a student. There are five
subjects. Marks in each subject are entered from keyboard. Assign grade
based on the following rule:
Total Marks >= 90 Grade: Ex
90 > Total Marks >= 80 Grade: A
80 > Total Marks >= 70 Grade: B
70 > Total Marks >= 60 Grade: C
60 > Total Marks Grade: F
Q&A
Q: Why are there no global variables in java?
A: Global variables are considered bad form for a variety of reasons: adding state
variables breaks referential transparency, state variables lessen the cohesion
of a program.
Q: What is Dynamic Method Dispatch?
A: Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at run time, rather than at compile time.
Q: What is the use of bin and lib in JDK?
A: Bin contains all tools such as javac, appletviewer, awt tool etc. whereas lib
contains API and all packages.
Q: What are the different types of casting?
A: There are two types of casting