Anda di halaman 1dari 65

Introduction to Core Java

Reference Copy for Beginner Level

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 1


Introduction to Core Java

History Of Java
In December 1990, Patrick Naughton, James Gosling and Mike Sheridan of Sun
Microsystems started to work on a project known as the Green Project. At that tme the
programming languages that was ruling the software market was C and C++. However, C
and C++ have certain complexity and limitations as the programmers have to be
concerned about the platform which they are working on. This frustrated the project team
and they decided to create an object-oriented development environment based on C++,
but easier to learn and use. In April 1991, the team decided on embedded systems
software for smart consumer devices as the delivery platform for their project. James
Gosling wrote the original compiler called "Oak" and, with the other team members,
developed a runtime interpreter for what would become the Java language. In 1994 the
Green Project was aborted because of its restricted market. But from the "OAK emerged
a new language called JAVA.

Java - The Programming Language


Java is an Object Oriented programming language that can run on different platforms. A
Java program can also travel across a network and can be executed on another machine's
browser. Java is a pure object oriented language i.e. everything has to be written within a
class. When a Java program is compiled it is converted into a binary program called by
the Java Compiler. The binary format is called byte codes. Byte codes are actually
machine instructions that can be understood by the Java Virtual Machine. At the time of
execution of the program a Java interpreter that resides inside the Java Virtual
Machine executes the instructions that the byte codes specify. This interpreter is also
entrusted with the responsibility to the byte codes are safe to execute and has not been
tampered with. The interpreter also handles communication with the operating system of
the machine in which it is residing.

Java can be used to create two different types of programs, which are

1. Applications: - Standalone programs written in Java are known, as application. They


can run on the desktop with the help of the JVM.

2. Applets: - Applets are programs that are woven directly into Web pages. It requires a
web browser that has JVM to run on the desktop. They are pieces of executable Java
code that are embedded in an HTML document using the <APPLET> tag. To run an
applet without a browser we need Appletviewer (discussed in the later part of the
book). Applets have been discussed in detail in the later chapters of this book.

Java is a case-sensitive programming language.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 2


Introduction to Core Java

Features of Java
Java is a simple, Object Oriented, distributed, interpreted, robust, secure, architecture
neutral, portable, high performance, multithreaded and dynamic language.

> Simple
The fundamental concepts of Java technology can be are grasped quickly and hence
programmers can be productive from the very beginning.
> Object Oriented
Java is purely object-oriented and supports the basic features of object orientation such as
abstraction, encapsulation, inheritance, and polymorphism.
> Distributed
It has been developed in such a way that it has the capability to share data and resources
across the network. Using Java, multiple programmers can work on a single project from
multiple remote locations.
> Interpreted and compiled
The Java compiler doesn't generate "machine code" in the sense of native hardware
instructions--rather, it generates byte-codes a high-level, machine-independent code for a
hypothetical machine called the Java Virtual Machine (JVM) that is implemented by
the Java interpreter and run-time system. When a program has to be executed, the code is
fetched into the memory and interpreted on the user machine.
> Robust
Java is intended for developing software that must be robust, highly reliable, and secure,
in a variety of ways.
> Secure
Memory allocation and reference model impose the First level of security in Java. The
memory layout decision is not made during the compilation time but during the runtime
depending upon the Hardware and software platform where it is executed. The Second
line of defense is the class loader. Whenever a Java system is executing it may in turn
load class or classes from network, which is verified and tested by the byte code loader.
Java programs cannot read or write outside the program environment. So there is less
probability for the existing resources in the memory to be infected by virus.
> Architecture neutral
The Java programs are not transformed into machine dependent executable code during
compilation. Instead the Java compiler converts the source code into a binary format
called Byte code. The Java Interpreter that resides inside the Java Virtual Machine then
executes this Byte code within the Java Virtual Machine .
 Portable
Since Java programs take an approach of byte code therefore it is portable to any system
on which the Java interpreter and run-time systems have been implemented.
> High performance
Java gives better performance than any Interpreter based language since the interpreter
can run at full speed without checking the runtime environment.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 3


Introduction to Core Java

Comparison between Java and C++


Java C++
Java does not support operator overloading. C++ supports operator overloading.
Java does not support multiple inheritance C++ supports multiple inheritance
It does not use pointer. It uses pointer.
De-allocation of memory is done automatically Requires explicit de-allocation of the memory by
with the help of the Garbage collection the user.
technique.

Writing our first Java program


As discussed earlier, the java program can be written in editors like the Notepad, DOS
editor etc. The java program has two main parts a class definition that encloses the entire
program and a method called main that contains the body. The java source code is stored
in files with .java extension. Usually the file name is the same as the class name that
contains the main() method.
class My
{ Name of the Class
public static void main(String args[])
{ It is Keyword
System.out.println("This is Simple Java Program :");
} }
Write down the Program in Notepad Editor and Save and Close It.
Compile the Java Program Using :- Javac My.java
Execute this Program :- Java My

Public :- access modifier which makes us access everywhere


static :--that is coplie time itself ur static insteance will get initialize..
void :- no return type for this method
main :- it is a thread which the JVM look first and then only i will go inside the
program
Sting[]- that is java will accept everthing as a string array
string- its the run time argument...this thing we will give during run time..we can
give any name..

System: its the class


out: its the object of the class System
println():its the method which tells the compiler to print
a new line.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 4


Introduction to Core Java

Write your Java Program


1. Using Ascii Editor
2. Using IDE ( Integrated Development Environment :

Like as

Save this File or Ctrl+s


File->Exit
Then Java Hello

Output :
Hello this is is Java
Java is Good Language

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 5


Introduction to Core Java

Setting the PATH Variable

The last step before you can use the JDK is to set the PATH environment variable to
indicate where the JDK's tools are installed.

1. Opening the System Properties dialog. Right click on the My Computer icon on
your desktop and select Properties from the menu.

2. Opening the Environment Variables dialog. Select the Advanced tab at the top of
the System Properties dialog (Fig. 14). Click the Environment Variables button to
display the Environment Variables dialog (Fig. 15).

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 6


Introduction to Core Java

Editing the PATH variable. Scroll down


inside the System variables box to select the
PATH variable. Click the Edit button. This will
cause the Edit System Variable dialog to
appear (Fig. 16).

Next :-

1. Changing the contents of the PATH variable. Place the cursor inside the Variable Value
field. Use the left-arrow key to move the cursor to the beginning of the list. At the
beginning of the list, type the name of the directory in which you placed the JDK followed
by \bin; (Fig. 17). If you chose the default installation directory in Step 4 of Installing the
J2SE Development Kit (JDK), you will add C:\Program Files\Java\jdk1.5.0\bin; to
the PATH variable. Click the OK button to complete the modification of the PATH variable.
[Note: The default installation directory is named jdk1.5.0, even though the JDK is now
version 5.0.]

Next -> Reboot the Machine.

Now we can run java Program anywhere in our Machine .

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 7


Introduction to Core Java

Java Architecture

The java architecture consist of four components

1. The java Programming language.


2. Java class File
3. Java Application programming Interface.
4. Java Virtual Machine.

JDK Tools :

Java Development kit consist mainly of core API classes , a java compiler , and a java
virtual machine interpreter . It also consist of useful utilities for debugging dissemblers ,
documenting java source and for interfacing to java code.

1. javac : it is a java compiler , converts java source code to byte code.

javac filename.java

2. java : The java interpreter ,execute java application byte does directly from class
file.

java classname

3. jdb : The java debugger allows you to step through the program one line at a
time ,set break point and examine variables.
4. Rmic : create skeleton and stubs for remote method invocation .

Rmic filename.class

5. Rmiregistry : Registry used to gain access to rmi object on a specific machine.

Start rmiregisrty

6. Jar : java archieve (jar ) file to generate jar files allows multiple java classes and
resources to distributed in one compressed file.

Jar filename.jar classfilename

7. Servletrunner : A simple webserver to test servlets.


8. Appletviewer : A java interpreter that execute java applet classes hosted by html.
9. Javah : It creates header and stub files that let you extend your javacode with c
language.
10. Javadoc : It creates HTML format documentation from java source code files.

Javadoc filename.java

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 8


Introduction to Core Java

Java Standard Library (JSL)

The java API consist of many classes and methods grouped into several packages . jdk1.2
has 58 packages, it is also known as Java Standard Library.

The Seven main package in java are :

1. Java.lang :- It contains the main language support class. These deals with object ,
Strings , Multithreading and basic features of Java.
2. Java.util :- It provides classes that support collections, date ,time, calendar
operation , parsing and Basic event processing.
3. Java.io :- This package that provides reading and writing data in the form of
streams and device independent file services.
4. Java.awt :- This package provides classes for creating GUI programs . It Contains
java Abstract window Toolkit(AWT).
5. Java.applet : This package includes a set of classes with the support for HTML
embedded java Applet.
6. Java.net : It combines the classes supporting low level Internet programming and
www.
7. Javax.swing : It offers classes for components , higher level controls and
pluggable look . it means that capability of swing classes for customization.

Input and Output Streams :

The java.lang package consist a useful class system . This is used to access the
system level behavior , provided for platform independent way. This class consist of
console I/O methods.

The system packages provide three basic streams

1. System.in
2. System.out
3. System.err

System.in : - It refers to standard input stream by default , keyboard.

System.out :- It refers to standard output stream , by default , this is console or screen.

System.err : - It refers to the standard error stream .

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 9


Introduction to Core Java

Input using BufferedReader class :

Class Input {

Public static void main(String args[])

int a;

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));

System.out.println(“Enter your name :”);

a=Integer.parseInt(br.readLine());

System.out.println(“value of I IS :” +a);

}}

Using Scanner (just jdk1,5 version)

import java.util.Scanner; // program uses Scanner

public class GradeBookTest

public static void main( String args[] )

Scanner input = new Scanner( System.in );

GradeBookTest myGradeBook = new GradeBookTest();

System.out.println( "Please enter the course name:" );

String name = input.nextLine();

System.out.println("Hello your Course Name is :" +name);

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 10


Introduction to Core Java

Java Class Concepts


Java is a purely object oriented language. We have already seen that in a Java program every
single piece of code is written inside a class definition. So much so that we even write the main ()
method in Java within a class definition.

The class is the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and the nature of an object. Any concept
that we wish to implement in a Java program must be encapsulated within a class.
A collection of variable and related function grouped together into a single
unique name is called Class .

Declaring a Class in Java

class <class name>


{
// Statements
}
A class name:

> Must not be a keyword in Java.


> Can begin with a letter, an underscore '_' or a '$' symbol.
> Must not contain embedded spaces or period ('.') .
> Can contain characters from different alphabets like Japanese, Greek, Cyrillic and
Hebrew

Apart from the above rules it is a good programming practice to ensure that the first letter of the
class should be in upper case.

Class Cube
{
Int breadth;
Int height;
Int length;

Sum();
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 11


Introduction to Core Java

Declaring Objects in Java


Object :- Basic Runtime entities of Object Oriented Programming System.
Cube myCube;
myCube = new Cube();

or cube mycube =new cube();


class Cube {
int length;
int breadth;
int height;

class CubeVolume {
public static void main (String args [])
{
Cube myCube = new Cube ();
myCube.length = 20;

int volume = myCube.length * myCube.breadth * myCube.height;


System.out.println ("The volume of the cube is : " + volume);

The output of the above program is :

The volume of the first cube is :


1000 The volume of the second cube is :
8000

Methods
Methods are the functionality exhibited by the object. These methods are described in the
class, the designing template of object.
The syntax for declaring a method is:

<returntype> < method name > (parameter list )


{
// Statements
}
The following rules must be complied with while declaring a method:

> Must not be a keyword in Java.


> Can begin with a letter, an underscore '_' or a '$' symbol.
> Must not contain embedded spaces or period '.' .
> Can contain characters from different alphabets like Japanese, Greek, Cyrillic and
Hebrew.
Now that we have understood the necessity and importance of methods in a class, let us
discuss about the two other important aspects of methods, namely :

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 12


Introduction to Core Java

> Passing arguments to a method


> Returning values from a method
Passing arguments to methods
An argument can be defined as a value or a variable that is passed to a called
method when it is invoked from the caller method. On the other hand, a
parameter signifies the variable defined by the called method, which receives
the argument when the called method is invoked.
class Cube {
int length;
int breadth;
int height;

void setCube (int l, int b, int h) {


length = l; breadth = b; height = h;
} }

class CubeVolume {
public static void main (String args [])
{
Cube myCubel = new Cube ();
Cube myCube2 = new Cube ();
myCubel.setCube(10, 10, 10);
myCube2.setCube(20, 20, 20);
int volume = 0;
volume = myCubel.length * myCubel.breadth * myCubel.height;
System.out.println ("The volume of the first cube is : " + volume);
volume = myCube2.length * myCube2.breadth * myCube2.height;
System.out.println("The volume of the second cube is : " + volume);
}}

Access Control In java :

In java Access specifier are three types


1.public
2. Private
3.Protected

Public : public data and function can be access from inside as


well as outside the classes.

Private : private data and function are accessible only from


within class . If a member is private , it can only be used by
member function and friend of a class in which is declared.

Protected : If a member is protected , its access is the same


for private.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 13


Introduction to Core Java

How to Access private data member

Class A
{
Int a;
Public int b;
Private int c;
Void setc(int i)
{
C=I;
}
Int getc()
{
Return c;
}
}
Class Acce
{
Public static void main(String args[])
{
A ob=new A();
Ob.a=10;
Ob.b=23;
Ob.setc(100);
System.out.println(“The value of a is :”+a);
System.out.println(“The value of b is :”+b);
System.out.println(“The value of c is :”+getc());
}}

Constructor
A constructor is a method defined inside the class having the same name that of the class. The
constructor should not have a return type. The constructor contains the code for initializing the
data members of the class. It is executed automatically when an object of the class is created.
At the time of defining a constructor, we have to comply the following two rules:

> A constructor is a method defined inside the class having the same name as that of
the class.
> The constructor should not have a return type. As it is called automatically, you
cannot return any value.
Constructors can be divided into two broad categories, namely:

> Default Constructors


> Parameterized Constructors
> Copy Constructor

Default constructors

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 14


Introduction to Core Java

Every class has at least one constructor. Even if no user-defined constructor is provided,
Java provides a default constructor with no argument and an empty body.
class defaultConst
{
String ecode;
String name;
defaultConst()
{
ecode=”90”;
name=”Susan”;
}
void display()
{
System.out.println("the code of the employee is" + ecode);
System.out.println("the name of the employee is" + name);
}

class dConst{

public static void main(String args[]) {

defaultConst c1=new defaultConst();

c1.display();

}
}

Parameterized Constructors
This is because the instance variables of all the objects of defaultConst that we create
will have the value 90 and Susan. So, in order to create multiple objects of defautConst
class that will have different values of ecode and name, we take the help of
Parameterized Constructors .
class
parameterConst{
String ecode;
String name;

parmeterConst(String x,String y)
{
ecode=x;
name=y;
}

void disp()

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 15


Introduction to Core Java

{
System.out.println("the code of the employee is"+ecode);
System.out.println("the name of the employee is"+name);
}
}

class argumentConst{
public static void main(String args[])
{
parameterConst c1=new parameterConst("9","David");
parameterConst c2 = new parameterConst("10","John");
c1.disp();
c2.disp();
}
}
When an object is no longer referred to by any variables, Java
automatically reclaims the memory used by that object. This is
known as garbage collection. Thus, there are no destructor
methods in Java as in C/C++.
The Finalize () method
Java have the garbage collection mechanism which automatically free up the memory
allocated by the object when that particular object goes out of scope. However, garbage
collector has a limitation in the sense that it is unable to de-allocate the memory occupied
by the non-Java objects such as file descriptors or window system fonts. In order to free
up this space we should use the finalize () method that is defined in java. Before an object
is reclaimed by the garbage collector the finalize () defined for that object will be
invoked.

The following is the syntax for declaring finalize () method is as follows:

protected void finalize () {


{
//statements that make up the code for the finalize ()
method
}
Method Overloading
If we write more than one method with the same name but with different method
signatures, then this phenomenon is known as Method Overloading.
There can be a situation when you want to create several methods that perform closely
related tasks. Since these methods perform the same essential tasks, name of these
methods can be same. But when we define two or more methods having same name their
signature should be different. The signature of a method consists of:

> The name of the method.


> The number of arguments it takes.
> The data type of the arguments.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 16


Introduction to Core Java

> The order/sequence of the arguments.


we can say two or methods are overloaded when they differ in the number of arguments,
datatype of the argument or the sequence of the arguments that the method can accept.
The program implements the concept of method overloading.

class Calculator
{
int add(int x,int y)
{
return (x + y);
}
float add(float x,int y)
{
return (x + y);
}
float add(float x,float y)
{
return (x + y);
}
float add(float y,float x, float z)
{
return (x + y +z);
}
}
class overloadDemo {
public static void main(String args[])
{
int i;
float j, k;
Calculator calcobj = new Calculator();
i = calcobj.add (2,2);
System.out.println (i);
j = calcobj.add (2.1f,3.1f);
System.out.println (j);
k = calcobj.add (5, 5.5f);
System.out.println (k);
k = calcobj.add (6.6f, 7.7f ,8.8f);
System.out.println (k);
}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 17


Introduction to Core Java

Overloading Constructors
Like overloaded methods, we can also have overloaded constructors. It means more than one
constructor within a class definition having different signature.

class Addition
{
int x;
int y;
Addition
{
x=0;
y=0;
}
Addition (int a)
{
x=a;
y=0;
}
Addition (int a, int b) // Two argument constructor
{
x=a;
y=b;
}
void display ()
{
System.out.println("Values of x and y are : " +
x + " " + y);
}
}
class overloadedConstructorDemo {
public static void main(String args[])
{
Addition obj1=new Addition ();
obj1.display ();
Addition obj2=new Addition (10);
obj2.display ();
Addition obj3=new Addition (10,20);
obj3.display ();
}
}
The output of the above program is as follows:
Values of x and y are: 0 0
Values of x and y are: 10 0
Values of x and y are: 10 20

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 18


Introduction to Core Java

Exercise

// Simple program for constructor


class add
{
int a,b;

add() //constructor declaration


{
System.out.println("It is default constructor");

a=10;
b=20;
}
void sum()
{
System.out.println("The result will be ="+(a+b));
}
}
public class cons1
{
public static void main(String args[])
{
add a1=new add();

a1.sum();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 19


Introduction to Core Java

// Constructor with parameterized


import java.io.*;

class add
{
int a,b;

add(int a1,int b1)


{

a=a1;
b=b1;

}
void sum()
{

System.out.println("The sum is :"+(a+b));


}
}

class cons2
{
public static void main(String args[])
{
add ae=new add(10,20);

ae.sum();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 20


Introduction to Core Java

// Enter two variables through constructor parameters


// and write down program to swap and print the values.

import java.io.*;
class swap
{
int a,b;

swap(int x,int y)
{
a=x;
b=y;
}
void method_swap()
{
int t=a;
a=b;
b=t;
}
void display()
{
System.out.println("The VALUE OF A IS:"+a);
System.out.println("The VALUE OF B IS:" +b);
}
}
class cons3
{
public static void main(String args[]) throws IOException
{
int u,v;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value for A:");
System.out.flush();
u=Integer.parseInt(br.readLine());
System.out.println("Enter the value for B:");
v=Integer.parseInt(br.readLine());

swap sw=new swap(u,v);


System.out.println("Original values:");
sw.display();
System.out.println("Swapped values:");
sw.method_swap();
sw.display();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 21


Introduction to Core Java

//Its big example copy constructor

// To accept employee name,address, basic salary


// print salary structure in this condition
// da=basic*50% and hra=basic*40% and gross=basic+da+hra

import java.io.*;

class teacher
{
String name;
String address;
int basic;
double da;
double hra;
double gross;

teacher(String ename,String eaddress,int ebasic)


{
name=ename;
address=eaddress;
basic=ebasic;
da=0.0;
hra=0.0;
gross=0.0;

}
void display()
{
System.out.println("Employee name is:"+name);
System.out.println("Employee Address is:"+address);
System.out.println("--------------------------");
System.out.println("Basic Salary is:"+basic);
System.out.println("Dearness allowances:"+da);
System.out.println("House Rent allownaces is:"+hra);
System.out.println("The Gross salary is:"+gross);

void cal_da( teacher nteach)


{
da=0.50*basic;
}
void cal_hra(teacher nteach)
{

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 22


Introduction to Core Java

hra=0.40*basic;
}

void cal_gross(teacher nteach)


{
gross=basic+hra+da;
}

}
class cons4
{
public static void main(String args[]) throws IOException

String n,a;
int b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Employee name:");


System.out.flush();
n=br.readLine();
System.out.println("Enter the Address:");
System.out.flush();
a=br.readLine();
System.out.println("Enter the Basic Pay");
b=Integer.parseInt(br.readLine());

teacher te=new teacher(n,a,b);

System.out.println("Total Information About a Teacher");


System.out.println("----------------------------------");
te.cal_da(te);
te.cal_hra(te);
te.cal_gross(te);
te.display();
//teacher nteach=te;
//System.out.println();
//nteach.display();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 23


Introduction to Core Java

// Constructor Overloading
class add
{
int a,b,c;

add(int x,int y, int z)


{
a=x;
b=y;
c=z;
}

add(int x, int y)
{
a=x;
b=y;
}
void sum()
{
System.out.println("The Sum is :="+(a+b+c));
}
}
class cons5
{
public static void main(String args[])
{
add aw=new add(12,12,10);
aw.sum();
add ae=new add(12,12,0);
ae.sum();

}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 24


Introduction to Core Java

// Constructor overloading to compute the volume of a cube a box and a Rectangle


class cu
{
int l,b,h;
cu(int x)
{
l=x;b=h=1;
}
cu(int x,int y)
{
l=x; b=y; h=1;
}
cu(int x,int y,int z)
{
l=x; b=y; h=z;
}
void display()
{
int f=l*b*h;
System.out.println("vol = "+f);
}
}
class cons6
{
public static void main(String args[])
{
cu c1,c2,c3;

c1=new cu(5);
c2=new cu(7,5);
c3=new cu(7,5,2);
System.out.println("The volume of a cube is");

c1.display();

System.out.println("The volume of a Rectangle");

c2.display();

System.out.println("The volume of a Box is:");

c3.display();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 25


Introduction to Core Java

Inheritance :
Inheritance is the process of Creation of new class from an already
existing class.

Types of Inheritance :

1. Single
2. Multilevel
3. Hierarchical
4. Multiple

Class A
Class A Class A

Class B Class B
Class B Class C Class D

Single Class C Hierarchical Inheritance

Class D
Class A Class B
Multilevel

Class C
Multiple Inheritance

But in Java does not support Multiple Inheritance , so use the new Technique for
implement Multiple Inheritance is called Interface.

Advantage of Inheritance :

1. Reusability of code.
2. Accessibility of Variables
3. Methods and functions derived from Parent Class.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 26


Introduction to Core Java

//This is the Example of Single Inheritance


class a
{
int a;
}

class b extends a
{
int b, s=0;

void sum()
{
s=a+b;

System.out.println("The Sum is :"+s);


}}
class in1
{
public static void main(String args[])
{

b b1=new b();
b1.a=10;
b1.b=20;
b1.sum();
}}
// This is the Example of the multilevel Inheritance
class a
{
int a;
}
class b extends a // it inherit class a
{
int b;
}
class c extends b // it also inherit the class a, and b
{
int c;
int s=0;

void sum()
{
s=a+b+c;
System.out.println("The sum is :"+s);

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 27


Introduction to Core Java

class in2
{
public static void main(String args[])
{
c c1=new c();

c1.a=12;
c1.b=14;
c1.c=13;
c1.sum();
}}
// This is the example of Hierarchical Inheritance
class a
{
int a,b;

void input_data(int k1,int m1)


{
a=k1;
b=m1;
}
}
class b extends a

{
void sum()
{
System.out.println("The sum is :"+(a+b));
}
}

class c extends a
{
void multi()
{
System.out.println("The multiplication is :"+(a*b));
}
}
class d extends a
{
void sub()

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 28


Introduction to Core Java

{
System.out.println("The substraction is :"+(a-b));
}
}
class in3
{
public static void main(String args[])
{
b b1=new b();
b1.input_data(12,10);
b1.sum();
c c1=new c();
c1.input_data(1,12);
c1.multi();

d d1=new d();
d1.input_data(12,10);
d1.sub();

}}

The keyword super

What Super Key do …..

1. First it calls the Superclass Constructor


2. To access a member of the Super Class that has been hidden member of
a subclass..

class Base
{
int num;
}
class Child extends Base
{
int num;
Child (int x, int y)
{
super.num = x; //num of Base class
num = y;//num of Child class
}
void display ()
{
System.out.println ("Value of num in class Base is :
" +super.num);
System.out.println ("Value of num in class Child is :
" + num);
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 29


Introduction to Core Java

}
class testSuper {
public static void main (String args []) {
Child sub = new Child (10,70);
sub.display ();
}
}

Note :- In the above program, both the class Base and Child have an instance variable of the
same name (num). In such cases, num in class Child hides the instance variable num in class
Base. So, super is used to access the access the variable num in class Base.

Next Example for Call the Super Class Constructor :

Class Test1

{
int a;
int b;

Test1(int x, int y)
{
a=x;
b=y;
}
}
Class B extends Test1
{
Int c;
b(int x , int y, int p)
{
Super(x,y);
C=p;
}
Void sum()
{
System.out.println(“ The sum is “ +(a+b+c));
}
}

Class T1
{

public static void main(String args[])


{
B b1=new B(12,12,12);
B1.sum();
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 30


Introduction to Core Java

Overriding
Overriding is a mechanism of creation of methods in the
subclasses with the same name and signature at that of the
parent or the super class. The datatype of the value returned
by both the overriding and the overridden methods must be the
same.
This is a significant difference between method overriding and
method overloading. In the latter case the overloaded methods
can differ in their return type. The new method declared in
the subclass hides the method of super class.

class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}
}
class Chair extends Furniture
{
void display( )
{
System.out.println (" This is a Chair");
}
}
class overrideDemo
{
public static void main (String args [])
{
Chair c = new Chair( );
c.display( ); // the display( ) method of class Chair is
called
}
}
Note : In the above example an object of Chair class is created. It will call the version of display ()
method present in the Chair class because the version of display ( ) inside Chair class overrides the display
() method defined inside the Furniture class. Thus, the output of the above program will be :
This is a Chair

In order to access the display () method of the Furniture class the keyword super
should
be used as illustrated below:

class Furniture
{
void display( )
{
System.out.println (" This is a furniture");
}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 31


Introduction to Core Java

class Chair extends Furniture


{
void display( )
{
super.display ();
System.out.println (" This is a Chair");
}
}
class overrideDemo
{
public static void main (String args [])
{
Chair c = new Chair( );
c.display( ); // the display( ) method of class Chair
is called
}
}
The output of the above program is as follows:
This is a furniture
This is a Chair

Static member and Final keyword


Normally, a member of a class is accessed with the help of an
object belonging to that class. However, there may arise a
situation where a member of a class is to be accessed prior to
the creation of any object of that class. An example in this
regard can be the main () method which is invoked prior to the
creation of any object of the class in which the main ()
method has been defined.So, how do we create such class
members? The answer is to use the keyword static. When a class
member has been declared as static it can be accessed before
the creation of any object belonging to that class. The static
keyword can be applied to variables, methods and a special
kind of block called the static block. A static member of a
class can be accessed in the following manner from outside the
class: Classname.i
In the above syntax, i signify a member of a class (instance variable or method)
A method declared as static must comply with the following restrictions:
A static method can only access other static methods.
A static method can only access static instance variables.
A static method cannot refer to the keyword super.
The program given below illustrates the usage of static methods:

class staticClass
{
static int ivar1 = 2;
static int ivar2 = 2 * 4;
static void display (int x)

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 32


Introduction to Core Java

{
ivar1 = ivar1 * x;
ivar2 = ivar1 + x;
System.out.println ("The values of ivar1 and ivar2 are :
" + ivar1 + " " + ivar2);
}
}
class staticDemo
{
public static void main (String args [])
{
staticClass.display (10);
}
}
In the above program, the method display () in the staticClass
has been declared as
static. Thus, we have used the name of the class (staticClass)
to invoke the method
display () without creating an instance of staticClass.
The output of the above program is :
The values of ivar1 and ivar2 are : 20 30

The final keyword

The final keyword can be applied to classes, variables and methods

1. Final Class :
The classes are declared final in Java to ensure security.
Once a class is declared final, we cannot create a subclass
of that class. So we can not access the class using
Inheritance Property. We can prevent inherit from this
Final keyword.

Like as :
Final class A
{
Int a;

Class B extends A
{
} // It create Error Because A is Final so it can not Inherit by another Class.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 33


Introduction to Core Java

2. Final Variable :
When a variable has been declared as final, it cannot be
modified. A final variable is similar to a const in C++. An
object reference variable declared as final cannot be
changed.

Final a=4;

3. Final methods:
Methods declared final cannot be overridden in a subclass.
When a final method is called, the Java compiler copies the
byte code for the subroutine directly to the compiled code of
the calling method, thus eliminating a costly method call.

Abstract Class
Abstract classes are created using abstract keyword. A class
is declared as abstract if it contains one or more abstract
methods. Abstract methods are those methods, whichhave only
method declaration but no method body. The syntax for
declaring an abstract method is as follows:

abstract return_type method_name (parameter_list);

It is mandatory for a class to be declared as abstract in the following


circumstances:
The class contains one or more abstract methods.
The class inherits one or more abstract methods (from its
base class) for which it does not provide implementation.
The class implements an interface (we will discus interface
in the subsequent chapter) but does not provide implementation
to all the methods declared in that interface.

Example :

Abstract class A
{
Abstract void callme();
Void display()
{
System.out.println(“This is Display method”);
}}
Class B extends A
{
Void callme()
{
System.out.println(“This is derived from Parent class:”);
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 34


Introduction to Core Java

Class A1
{
public static void main(String args[])
{
A A1=new A();
A1.display();
A1.callme();
}
}
Example 2:
abstract class abs1
{
abstract public void add(int x, int y);
abstract public void sub(int a, int b);
public void disp()
{
System.out.println("This is te Abstract calss");
}
}
class abs2 extends abs1
{
int x;
int y;
public void add(int x, int y)
{
this.x=x;
this.y=y;
System.out.println(x+y);
}
public void sub(int a, int b)
{
x=a;
y=b;
System.out.println(x-y);
}
public static void main(String[] args)
{
abs2 ab=new abs2();
ab.add(10,20);
ab.sub(40,2);
ab.disp();
System.out.println("Hello World!");
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 35


Introduction to Core Java

Interfaces

An interface is like an abstract class whose all methods are


abstract. However, interfaces do not contain instance
variables and all the methods declared in the interface do not
have method body.
Like Classes Interface can be extended.

Unlike C++, Java does not allow multiple inheritance. Multiple


inheritance takes place when a particular is extended from two
or more classes. Since a class can implement multiple
interfaces, we can say that with interfaces we can perform
some of the functionality that can be performed using multiple
inheritances.

Declaration of Interface :

acess Interface interface_name


{
final datatype varname = value;
return_type methodname1(parameter_list);
}

Access specifier for an interface can be either public or not


specified. If the access specifier is not specified then the
methods declared within that interface is available to the
classes present in the same package. If the access specifier
is public, then that interface can be accessed by all classes
both inside and outside the package.

Example:

Interface In
{
Static final int reg=1234;
Static final String n=”Jahiruddin Ahamed”;
Void display();
}
Class B implements In
{
Void display()
{
System.out.println(“The int value is :”=+reg);
System.out.println(“The String value is :”=+n);
}}
Class Me {
Public static void main(String args[])
{
B b1=new B();
B1.display();
}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 36


Introduction to Core Java

The interface is implemented by using the implements keyword.

Another Example :

Calculate the Area of the Circle

interface area
{
final static double pi = 3.14;
double calcArea (double x);
}
class circle implements area
{
public double calcArea (double x)
{
return (pi*x*x);
}
public static void main(String args[])
{
circle cr=new circle();
area ar;
ar=cr;
System.out.println("area of circle is" + ar.calcArea(2));
}}

The output of the above program is as follows:


Area of circle is : 12.56

Note :

Thus in our program we are declaring an object reference variable of type area
called ar.To this variable we are storing the reference to the object (cr) of
class circle. When the method area () is invoked using ar the area () method of
the object (whose reference is stored in cr) of class circle will be invoked.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 37


Introduction to Core Java

//one interface can extending another interface

interface ABC {
void method1();
void method2();
}
//XYZ interface extends ABC interface
interface XYZ {
void method3();
}
//class Myclass implements XYZ interface
class Myclass implements XYZ {
public void method1()
{
System.out.println("This is method 1 ");
}
public void method2()
{
System.out.println("This is method 2 ");
}
public void method3()
{
System.out.println("This is method 3 ");
}
}
class Mtest {
public static void main(String arg[])
{
Myclass obj = new Myclass();
obj.method1();
obj.method2();
obj.method3();
}
}
The output of the program is as follows:
This is method1
This is method2
This is method3.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 38


Introduction to Core Java

Exception Handling

Java Programming normally encounter two types of Error during


coding - 1. Syntax Error
 Semantic Error
Syntax Error :
It imply error in grammar of usage of keywords. For example
misspelling, improper use, wrong context of keywords. Such
errors are automatically detected at the compile time and
error message appear. So we can correct the error and
recompile the program.

Semantic or Runtime Error :


The error which show during the execution of program . such
as division by zero, array index out of bounds, and many more.

Compile Time Error :


1. Variable undefined
2. Missing or mismatch curly braces.
3. Wrong spelling of identifiers and
keyword.
4. Mismatch of double quote in a string.
5. Mixing up of data types.
6. Bad reference to object.
7. Wrong use of = and == operator
8. Wrong specification of directly path.

Runtime Error :
1. Division by zero.
2. Array index out of bounds.
3. Incompatible data types.
4. Passing wrong arguments to a method.
5. Negative index for array.
6. Converting non numeric string to number.

Exception : runtime errors are called exceptions. Java


provide way to deal with these runtime error can occur due to
illegal operation such as integer divided by zero.

Java has a class that called Throwable class thatv deals with
exception and error.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 39


Introduction to Core Java

The hierarchy of exception class is:

Some of the exception classes under Exception class are:

> ClassNotFoundException
> IllegalAccessException
> InterruptedException
Some of the exception classes under RuntimeException class are:
ArithmeticException
> ArrayStoreException
> IllegalArgumentException
> IllegalMonitorStateException
> ArrayIndexOutOfBoundsException

There are two reserve words in java for deal with exception.

1. Try
2. Catch

try: - If any part of code is expected to give rise to an exception, it is put inside a try
block The statements that comprise the try block should be enclosed within curly braces.
A try block cannot comprise of a single statement. It is possible to develop nested try
blocks that is one try block can be placed inside another try block.

The syntax for try block is as follows:


try
{
Statement which may cause exception
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 40


Introduction to Core Java

catch: The catch block comes after the try block and performs the actual error handling
functions. One try block may be associated with one or more catch blocks. All the corresponding
catch blocks for a try block should come after the try block.

Example :

Class myclass
{
Public static void main(String args[])
{

Int a=23;
Int b=0;

try
{
C=a/b;
}
Catch(Exception e)
{
System.out.println(“Zero divide error :”);
}}
}
In above program the try clause tells the compiler to try to
execute the code . But if it fails to execute then an
exception is generated and thrown which is caught by catch
clause.

// One try clause can contain one or more catch clause.


class ExceptionDemo
{
public static void main (String args [])
{
try
{
int nums [] = {10,12,13};
for (int i = 0; i < 5; i++)
System.out.println (nums[i]);
}
catch (ArrayIndexOutOfBoundsException a)
{
System.out.println ("The array length is only 3.");
}
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 41


Introduction to Core Java

Throw and Throws :

So far java runtime was throwing exceptions. your program can


also throw exception explicitly using a throw statement .

Like as :

Class Test
{
Public static void ExceptionTest() throws ArithmaticException
{
Throw new ArithmeticException(“Demo”);
}
Public staic void main(String args[])
{
Try
{
ExcepTest();
}
Catch(ArithmaticException e)
{
System.out.println(e);
}}

//Catch Error when input

Import java.io.*;
Class Test {
Public static void main(String args[]) throws IOException{
String s;
Buffereader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter your Name :”);
S=br.readLine();
System.out.println(“Your name is :”+s);
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 42


Introduction to Core Java

Finally :

The code in this clause executes in every condition even


if the exception is generated and is caught.

Or this is an optional block of statement.


It is executed whether or not an exception is occurred . The
try statement at least one catch or finally block.

Syntax :

Try {

// statement that may cause an exceptions.


}
Catch
{
// Error handling technique
}
Finally {
//statements
}

Example:
Class exedemo
{
Public static void main(String args[])
{
Try
{
Int b=5,a=0;
C=b/a;
}catch(Exception e)
{
System.out.println(“arithmetic exception caught”);
}
finally
{
System.out.println(“ This is finally block”);
}
System.out.println(“Program completed:”);
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 43


Introduction to Core Java

APPLET

Applet is Small Java Programs that are integrated into webpage like HTML . For this
reasons applet is most important features of Java , Because Today Internet has an over
bearing presence in our day –to- day life.
Applets are powerful tools in Supporting client-side programming , a major issue for the
web.

What is Applet Viewer :


An appletviewer is a standard JDK tool that can be used for
the execution of applets in a window separate from the
browser window. Appletviewer is an ideal tool for testing
applets that we create.
Till now we have become used to write Java program whose execution starts from the
main () method. However, for applets this is not the case. An applet is executed by
following an entirely mechanism about which we will discuss a little later.
Every applet is implemented by creating a subclass of the class called Applet. The
Applet class contains a single default parameterless constructor. The runtime
environment constructs Applets when they are loaded and do not have to be explicitly
constructed.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 44


Introduction to Core Java

Advantage of Applet :
1. There is no Installation Issue.
2. An Applet has true platform independence (including the ability to easily play audio file
nad many more ….)
3. Applets completely eliminate the fear of viruses.
4. It is integrated with HTML, so it is so simple for build.

Security Restrictions:
Applets Cannot…

• Read from the local (client) disk


– Applets cannot read arbitrary files
– They can, however, instruct the browser to display pages that are
generally accessible on the Web, which might include some local
files
• Write to the local (client) disk
– The browser may choose to cache certain files, including some
loaded by applets, but this choice is not under direct control of the
applet
• Open network connections other than to the
server from which the applet was loaded
– This restriction prevents applets from browsing behind network
firewalls
5

• Discover private information about the user


– Applets should not be able to discover the username of the person
running them or specific system information such as current users,
directory names or listings, system software, and so forth
– However, applets can determine the name of the host they are on;
this information is already reported to the HTTP server that
delivered the applet.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 45


Introduction to Core Java

So Life Cycle of Applet can be Divided into Five Stage .


1. Init()
2. Start()
3. Stop()
4. Destroy()
5. paint()
6. repaint(optional)

public void init()

Called once by the applet container when an applet is loaded for execution. This
method initializes an applet. Typical actions performed here are initializing fields,
creating GUI components, loading sounds to play, loading images to display (
Multimedia: Applets and Applications) and creating threads ( Multithreading).
public void start()

Called by the applet container after method init completes execution. In addition, if
the user browses to another Web site and later returns to the applet's HTML page,
method start is called again. The method performs any tasks that must be completed
when the applet is loaded for the first time and that must be performed every time the
applet's HTML page is revisited. Actions performed here might include starting an
animation or starting other threads of execution .

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 46


Introduction to Core Java

public void paint( Graphics g )

Called by the applet container after methods init and start. Method paint is also
called when the applet needs to be repainted. For example, if the user covers the applet
with another open window on the screen and later uncovers the applet, the paint
method is called. Typical actions performed here involve drawing with the Graphics
object g that is passed to the paint method by the applet container.
public void stop()

This method is called by the applet container when the user leaves the applet's Web
page by browsing to another Web page. Since it is possible that the user might return
to the Web page containing the applet, method stop performs tasks that might be
required to suspend the applet's execution, so that the applet does not use computer
processing time when it is not displayed on the screen. Typical actions performed here
would stop the execution of animations and threads.
public void destroy()

This method is called by the applet container when the applet is being removed from
memory. This occurs when the user exits the browsing session by closing all the
browser windows and may also occur at the browser's discretion when the user has
browsed to other Web pages. The method performs any tasks that are required to clean
up resources allocated to the applet.

The repaint () method:


This method is invoked whenever there is a need to update the information displayed in
the applet window. The repaint () method calls the update () method, which redraws
either the whole or a specific portion of the window in which the applet is displayed. The
update () method in turn calls the paint () method. There are four overloaded versions of
the repaint () method. They are as follows:
void repaint (): It results in the repainting of the entire window.
void repaint (int, int, int, int) : This version of the repaint () method is used to
repaint a specific section of the window. The first two integer parameters of this
method specifies the co-ordinates of the top-left corner of the window and the last
two integer parameters denote the height and the width of the region to be repainted.
void repaint (long delay) : This version specifies the period expressed in
millisecond
that must transpire after which the update () method must be called. This version is
required because the repaint () will not be able to invoke the update () method
immediately if the system is slow or busy for any reason.

void repaint (long delay, int, int, int, int): Here delay specifies the period of the time
that must expire before the update () method is called and the four integer parameters
denote the co-ordinates of the top-left corner of the window where the applet is
displayed and its height and width respectively.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 47


Introduction to Core Java

Applet is not application program so it does not execute in console based interpreter .
we execute the java applets by using web browser like internet explorer or Netscape
Navigator or an Appletviewer. In java Applets always extends Applet class that is
defined in java.applet package . It has several methods to manipulate and the control
of the execution of Applet.
Java Applet package three parts :-
1. Applet Context
2. Audio Clip
3. Applet Stub
Also import all methods of awt(Abstract window Toolkit) class . It is used for load and
display image and load to play the audio clip. Etc. It also supports for Window based
Interface.

When an applet is called, its execution sequence is as follows:


init ()
start ()
paint ()
stop ()
destroy ()
import java.awt.*;
import java.applet.*;
/*
<applet code="appletskel" width=300 height=100>
</applet>
*/
public class appletskel extends Applet{
public void init()
{
//initialization like as Variable,image loading,etc.
}
public void start()
{
//start or resume execution
}
public void stop()
{
//suspends execution
}
public void destroy()
{
//perform shutdown activity
}
public void paint(Graphics g)
{
//redisplay contents of window or drawing
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 48


Introduction to Core Java

Now that we have created at least a skeleton let us learn how to compile and execute an
applet.
Compilation of an applet
The process that we follow for compiling an applet is the same that is required to compile
a Java application i.e

javac file_name.java
In the above syntax, file_name stands for the name of the Java source file. This name
should be the same as the name of the class that extends the Applet class.
Execution of an applet
We can execute an applet in the following two manner:
Executing the Applet within a Java-compatible Web browser, such as Netscape
Navigator or Internet Explorer. To execute an Applet in a Web browser, we need to
write a short HTML text file that contains the appropriate APPLET tag.
Using an applet viewer, such as standard JDK tool, appletviewer. This is the fastest
and easiest way to test the applet that we have created.
EMBEDDING AN APPLET :
The applet program is embedded in the web page by writing a short HTML code whose
syntax is shown below:
<Applet
codebase = codebaseURL
code = applet_name
alt = alternative text
width = w
height = h
alignment = a
vspace = v
hspace = h
>
<param name = parameter_name value = parameter_value>
</applet>
Let us now learn about the significance about each of the above attributes.
Internet Programming Using Core Java – Part 2
SR/JAVP2/301/1001/SC/3.0 13
The CODEBASE attribute of the applet tag is for specifying the path or the URL of
the applet program. This is needed if the applet does not exist in the same directory as
the web page. By default, the directory of the HTML file in which the applet is
embedded will be considered as the codebase. It is an optional attribute.
The CODE attribute specifies the name of the html file that embeds the .class file
that constitutes the applet. The browser will call this html file and then the applet will
then be interpreted and displayed in the browser.
Width and height attributes specify the area in pixels in which the applet is
displayed. The applet can be resized if it is being run it the appletviewer but in the
browser it cannot be resized.
The ALT attribute is an optional attribute that specifies a short text message that
should be displayed if the browser is not able to execute the Applet.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 49


Introduction to Core Java

The ALIGN attribute is used to stipulate the alignment of the applet. This attribute
can take the following values:
• LEFT
• RIGHT
• TOP
• BOTTOM
• MIDDLE
• BASELINE
• TEXTTOP
• ABSMIDDLE
• ABSBOTTOM
The VSPACE and HSPACE attributes are optional and are specified in pixels.
VSPACE is used to arrange the space above and below the applet and HSPACE is
used to determine the spacing on both the sides of the applet.
THE <PARAM> TAG:
The applet can use run time values, which may be passed to it from the web page. To
pass parameter from the web page the PARAM tag is used. This parameter has two
attributes: (name : the name of the parameter. And value : the value of the parameter.
The syntax is as follows:
<applet code=appletname width=w height=h>
<param name = font value = “TimesRoman”>
<param name = size value=“28”>
</applet>
Thus for each parameter a single param tag is used.
First Example :
import java.awt.*; //Graphics Class which contains Paint()
import java.applet.*;
/*
<applet code = "sampleApplet" width = 300 height = 50>
</applet>
*/
public class sampleApplet extends Applet
{
public void init ()
{
setBackground (Color.cyan);
setForeground (Color.red);
}
public void paint (Graphics g)
{
g.drawString ("Welcome to the exciting world of Java
Applets", 20, 30);
showStatus ("Status Line Calling!!!");
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 50


Introduction to Core Java

Useful Methods in Graphics Class :


• drawString(string, left, bottom)
– Draws a string in the current font and color with the bottom left corner of the string at
the specified location – One of the few methods where the y coordinate refers to
the bottom of shape, not the top. But y values are still with respect to the top left corner
of the applet window
• drawRect(left, top, width, height)
– Draws the outline of a rectangle (1-pixel border) in the current color
• fillRect(left, top, width, height)
– Draws a solid rectangle in the current color
• drawLine(x1, y1, x2, y2)
– Draws a 1-pixel-thick line from (x1, y1) to (x2, y2)
drawOval, fillOval
– Draws an outlined and solid oval, where the arguments
describe a rectangle that bounds the oval
• drawPolygon, fillPolygon
– Draws an outlined and solid polygon whose points are defined by arrays or a Polygon
(a class that stores a series of points) – By default, polygon is closed; to make an open
polygon use the drawPolyline method
• drawImage
– Draws an image – Images can be in JPEG or GIF (including animated GIF)
format
24

Drawing Color :
• setColor, getColor
– Specifies the foreground color prior to drawing operation – By default, the graphics
object receives the foreground color of the window – AWT has 16 predefined colors
(Color.RED, Color.BLUE, etc.) or create your own color:
new Color(r, g, b)– Changing the color of the Graphics object affects only
the drawing that explicitly uses that Graphics object
• To make permanent changes, call the applet’s
setForeground method.

setFont, getFont
– Specifies the font to be used for drawing text – Determine the size of a character through
FontMetrics (in Java 2 use LineMetrics) – Setting the font for the Graphics object does not
persist to subsequent invocations of paint – Set the font of the window (I.e., call the applet’s
setFont method) for permanent changes to the font – Standard Java font names: Serif (e.g., Times
New Roman), SansSerif (e.g., Arial), Monospaced (e.g., Courier New), Dialog, and
DialogInput.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 51


Introduction to Core Java

Examples of Drawing Shape :


import java.awt.*;
import java.applet.*;
/*
<applet code=Shapes height=200 width=400>
</applet>*/
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.drawLine(40,20,100,20);
g.drawRect(40,70,60,40);
g.fillRect(140,60,70,40);
g.drawRoundRect(240,60,70,40,10,20);
g.fillRoundRect(140,120,70,40, 10,20);
g.drawOval(210,105,70,40);
}}

Draw a Image :
import java.applet.Applet;
import java.awt.*;
/** An applet that loads an image from a relative URL. */
public class JavaMan1 extends Applet {
private Image javaMan;
public void init() {
javaMan = getImage(getCodeBase(),"images/Java-Man.gif");
}
public void paint(Graphics g) {
g.drawImage(javaMan, 0, 0, this);
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 52


Introduction to Core Java

1. Write a program for Applet just Line Drawing


import java.awt.*;
import java.applet.*;
/*
<applet code = "sample" width = 300 height = 50>
</applet>
*/
public class sample extends Applet
{
public void init ()
{
setBackground (Color.cyan);
setForeground (Color.red);
}
public void paint (Graphics g)
{
g.drawString ("Welcome to the exciting world of Java Applets", 20, 30);
showStatus ("statusbar !!!");
}
}

1. Write a program for Draw different shapes.

import java.awt.*;
import java.applet.*;
/*
<applet code=shapes height=200 width=400>
</applet>*/
public class shapes extends Applet
{
public void paint (Graphics g)
{
g.drawLine(40,20,100,20); // line drawing
g.drawRect(40,70,60,40); //Rectangle
g.fillRect(140,60,70,40); //Filled Rectangle
g.drawRoundRect(240,60,70,40,10,20);
g.fillRoundRect(140,120,70,40, 10,20);
g.drawOval(210,105,70,40);
}
}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 53


Introduction to Core Java

1. Write a program for show different Font-style


import java.awt.*;
import java.applet.*;
/*
<applet code=fonts height=200 width=400>
</applet>
*/
public class fonts extends Applet
{
Font f1, f2, f3,f4;
public void init()
{
f1= new Font("Arial",Font.PLAIN,15);
f2=new Font("Times New Roman",Font.PLAIN+Font.ITALIC,20);
f3=new Font("Courier New",Font.BOLD,10);
f4=new Font("Courier New",Font.BOLD+Font.ITALIC,20);
}
public void paint(Graphics g)
{
g.setFont(f1);
g.setColor(Color.red);
g.drawString("This font is Arial and size is 15",30,30);
g.setFont(f2);
g.setColor(Color.pink);
g.drawString("This font is Times New Roman and size is 20",30,50);
g.setFont(f3);
g.drawString("This font is Courier New and size is 10",30,70);
}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 54


Introduction to Core Java

1. 29 To draw human face using Applet

import java.applet.*;
import java.awt.*;
/*
<applet code= "AppFace" width=500 height=400>
</applet> */
public class AppFace extends Applet
{
public void paint(Graphics g) {
//face
g.setColor(Color.orange);
g.fillOval( 90,40, 220,280);
//left eye
g.setColor(Color.black);
g.drawOval(120,120, 70,50);
//left eye ball
g.fillOval(150,135, 20,20);
//left eye brow
g.drawArc(110,100,80,20,0,160);
//right eye
g.drawOval(215,120, 70,50);
//right eye ball
g.fillOval(245,135, 20,20); //for right Eye Ball
g.drawArc(215,100,80,20,20,180);
g.drawOval( 195,140,20,70); //noise
//mouth
g.setColor(Color.red);
g.fillArc( 150,190,100,70,0,-180);
g.setColor(Color.orange);
g.fillArc( 150,200,100,50,0,-180);
}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 55


Introduction to Core Java

Working with Windows, Graphics and Text


Java components are part of java.awt package. It is the class, which lies at the top of the
AWT hierarchy. Component is an abstract class, which encapsulates all of the attributes
of a visual component. Components are mostly used to create a graphical user interface in
Java. When user interaction occurs with these components, they respond to all these
interactions through events. It is responsible for remembering the current foreground and
background colors and the currently selected text font.

Add components
Components are stored as classes inside the java.awt package. Now if we want to place
them inside the window, we have to create the instance of the component object first,
then that object must be added to the window. To do this, we use the add(CompObj)
method.
Here is the syntax:
add(obj1);
Where obj1 is the component object.

Add components
Components are stored as classes inside the java.awt package. Now if we want to place
them inside the window, we have to create the instance of the component object first,
then that object must be added to the window. To do this, we use the add(CompObj)
method.
Here is the syntax:
add(obj1);
Where obj1 is the component object.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 56


Introduction to Core Java

Types of Components
Labels
The Label control is used to display text inside the window. It is a passive control, means
it never responds to the user interaction.
The constructors are:
Label() :- Constructs a empty label
Label(String) :- Constructs a label with the string specified and left justified.
Label(String, int) :- Constructs a label with the string specified and int represents
the alignment. The alignment can be LEFT, CENTER and RIGHT.

The methods available are:

Buttons
Button object is used to create a push button, which will respond whenever the user will
press it.
The constructors are:
Button() :- Creates a button with no label
Button(String) :- Creates a button with the label specified in the string

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 57


Introduction to Core Java

Some of the methods available in this class are:

You can create the button object by calling its constructor. Here we are creating a Button
with a Caption “OK”.
Button b1=new Button(“OK”);
Where b1 is the object variable to this Button object. Once the object is created, add it to
the window.
Checkbox
Checkbox is a component that can be in either an "on" or "off" state. Clicking on a
checkbox changes its state from "on" to "off," or from "off" to "on."

Checkbox() :- Creates a ckeckbox with no label


Checkbox(String) :- Creates a ckeckbox with the label specified
Checkbox(String, boolean) :- Creates a ckeckbox with the label specified and the
state.
Checkbox(String, boolean, CheckboxGroup) :- Creates a ckeckbox with the label
specified, the state and the ckechbox group
Checkbox(String, CheckboxGroup, boolean) :- Creates a ckeckbox with the label
specified, the ckechbox group and the state.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 58


Introduction to Core Java

Radio Buttons
There is no special class known as Readio Button, but you can get the functionality of the
Radio Button by manipulating the Checkbox class. For that, first you have to create a
CheckboxGroup object. Once it is created, then that object will be used in a special
constructor of the Checkbox.
That constructor is:
Checkbox(String str, boolean value, CheckboxGroup cbg);
Checkboxes present under a common CheckboxGroup behave like Radio Buttons, only
one option can be selected within a sigle CheckboxGroup.
Here how it works:
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox(“One”,true,cbg);
Checkbox cb2=new Checkbox(“Two”,false,cbg);

TextField
TextField component is used to accept input from the user. However, it is applicable for
single line entry. While creating the object, you can specify the number of columns as a
parameter to the constructor. That does not mean, the input is restricted within that
number of characters only. You can enter characters more than the number of columns
specified, only that many numbers of characters will be visible at a time.
The constructors are:
TextField() :- Creates a new textfield
TextField(int) :- Creates a new empty textfield with the specified length
TextField(String) :- Creates a new textfield initialized with the string value
TextField(String int) :- Creates a new textfield initialized with the string value and
the maximum length it can hold.

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 59


Introduction to Core Java

If you want to use the TextField to accept the password from the user, then you can use
the setEchoChar() method.

T1.setEchoChar(‘*’); on T1. Afterwards, whatever you are typing inside T1 will


appear as ‘*’ .
TextArea
It is used to accept multiple lines of text from the user.
The constants that can be used with textarea are:
SCROLLBARS_BOTH :- To display both the scrollbars on the textarea
SCROLLBARS_HORIZONTAL_ONLY :- To display only the Horizontal
scrollbar
SCROLLBARS_VERTICAL_ONLY :- To display only the Vertical scrollbar
SCROLLBARS_NONE :- Used not to display scrollbar on the text field
The constructors of this class are:
TextArea() :- Creates a new textarea
TextArea(int, int) :- Creates a new textarea with the specified number of rows and
columns
TextArea(String) :- Creates a new textarea with the specified text
TextArea(String, int, int) :- Creates a new textarea with the specified text and
number of rows of columns
TextArea(String, int, int, int) :- Creates a new textarea with the specified text,
number of rows of columns and the type of scrollbar
Some of the methods belonging to this class are stipulated below:

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 60


Introduction to Core Java

Choice Control
Choice control is used to make a drop down list. While using the choice control only the
instantiation of this class is not enough, you have to add different elements to this control.
The constructor is:
Choice() :- Creates a new choice control
Some of the methods available in this class are:

Example :
First create a Choice control in this way:
Choice ch=new Choice();
Then call the addItem() method on this object. Here is the example:
ch.addItem(“Sunflower”);
ch.addItem(“Lily”);
ch.addItem(“Rose”);
ch.addItem(“Tulip”);

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 61


Introduction to Core Java

Now suppose you want to access the element, which is selected. For that you have a
getSelectedItem() present in the Choice control. This method returns the String associated
with the currently selected object.

Example :

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test2 height=400 width=400>
</Applet>
*/
public class Test2 extends Applet{
Label l,l1;

public void init()


{
l=new Label("My Name is Boss");

l1=new Label("Carry on Java ............................ Because Java is Too Much Best");

}
public void start(){
add(l);
add(l1);
}
}

Ex2 :

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test3 height=400 width=250>
</Applet>
*/
public class Test3 extends Applet{
Label l,l1;
TextField t1,t2;
Button b1,b2;

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 62


Introduction to Core Java

public void init()


{
l=new Label("Enter Your Name:-");
t1=new TextField(10);

l1=new Label("Enter Your Password:-");


t2=new TextField(10);
t2.setEchoChar('*');
b1=new Button("Submit");
b2=new Button("Cancel");

}
public void start(){
add(l);
add(t1);
add(l1);
add(t2);
add(b1);
add(b2);

}}
Ex3 : This Program for Applet & Action Listener.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=Test4 height=400 width=250>
</Applet>
*/
public class Test4 extends Applet implements ActionListener{
Label l,l1,l2,l3;
TextField t1,t2,t3;
Button b1,b2;
TextArea ta;
Choice ch;

public void init()


{

setFont(new Font("SansSerif",Font.BOLD,12));

l=new Label("Enter Your Name:-");


t1=new TextField(10);

l1=new Label("Enter Your Password:-");


t2=new TextField(10);

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 63


Introduction to Core Java

t2.setEchoChar('*');
l2=new Label("Address:-");ta=new TextArea("",10,20);
l3=new Label("Region");
ch=new Choice();
ch.addItem("East");
ch.addItem("West");
ch.addItem("North");
ch.addItem("South");

b1=new Button("Submit");
b2=new Button("Cancel");

t3=new TextField(20);

}
public void start(){
add(l);
add(t1);

add(l1);
add(t2);

add(l2);
add(ta);
add(l3);
add(ch);
add(t3);
add(b1);
add(b2);
add(t3);

b1.addActionListener(this);
b2.addActionListener(this);
}

public void submit()


{
String s=t1.getText();
String s1=t2.getText();
if(s.equals(s1))
{
t3.setText("Authenticated:");

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 64


Introduction to Core Java

}
else
{
t3.setText("Access Denied:");
}

public void actionPerformed(ActionEvent act)


{
if(act.getSource()==b1)
{
submit();
}

}}

Prepared by : Jahiruddin Ahamed(Lecturer Of Information Technology) 65

Anda mungkin juga menyukai