title: introduction java programmingpg)-4.pdf · introduction java programming java programming...

61
Title: Introduction Java Programming Prepared By G.Vidya, Assistant Professor, Department of Computer Science (PG), Kongunadu Arts and Science College, Coimbatore-641029

Upload: others

Post on 16-Jul-2020

81 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Title: Introduction Java Programming

Prepared By

G.Vidya, Assistant Professor, Department of Computer Science (PG), Kongunadu Arts and Science College, Coimbatore-641029

Page 2: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Introduction Java Programming

Java programming language was originally developed by Sun Microsystems which was initiated by James

Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE). With the advancement

of Java and its widespread popularity, multiple configurations were built to suite various types of

platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.

Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java

is guaranteed to be Write Once, Run Anywhere.

Java is:

Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based

on the Object model.

Platform independent: Unlike many other programming languages including C and C++, when

Java is compiled, it is not compiled into platform specific machine, rather into platform

independent byte code. This byte code is distributed over the web and interpreted by virtual

Machine (JVM) on whichever platform it is being run.

Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java

would be easy to master.

Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.

Authentication techniques are based on public-key encryption.

Architectural-neutral :Java compiler generates an architecture-neutral object file format which

makes the compiled code to be executable on many processors, with the presence of Java runtime

system.

Portable:Being architectural-neutral and having no implementation dependent aspects of the

specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability

boundary which is a POSIX subset.

Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on

compile time error checking and runtime checking.

Multithreaded: With Java's multithreaded feature it is possible to write programs that can do

many tasks simultaneously. This design feature allows developers to construct smoothly running

interactive applications.

Interpreted:Java byte code is translated on the fly to native machine instructions and is not

stored anywhere. The development process is more rapid and analytical since the linking is an

incremental and light weight process.

High Performance: With the use of Just-In-Time compilers, Java enables high performance.

Distributed:Java is designed for the distributed environment of the internet.

Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to

an evolving environment. Java programs can carry extensive amount of run-time information that

can be used to verify and resolve accesses to objects on run-time.

HISTORY:James Gosling initiated the Java language project in June 1991 for use in one of his many set-

top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office,

also went by the name Green and ended up later being renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run

Anywhere (WORA), providing no-cost run-times on popular platforms.

Page 3: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

On 13 November 2006, Sun released much of Java as free and open source software under the terms of

the GNU General Public License (GPL).

On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from

a small portion of code to which Sun did not hold the copyright.

Tools you will need:For performing the examples discussed in this tutorial, you will need a Pentium 200-

MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).

You also will need the following softwares:

Linux 7.1 or Windows 95/98/2000/XP operating system.

Java JDK 5

Microsoft Notepad or any other text editor

public class MyFirstJavaProgram {

public static void main(String []args) {

System.out.println("Hello World");

}

}

When we consider a Java program it can be defined as a collection of objects that communicate via

invoking each other's methods. Let us now briefly look into what do class, object, methods and instance

variables mean.

Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as

well as behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describes the behaviors/states that

object of its type support.

Methods - A method is basically a behavior. A class can contain many methods. It is in methods

where the logics are written, data is manipulated and all the actions are executed.

Instance Variables - Each object has its unique set of instance variables. An object's state is

created by the values assigned to these instance variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.

* This will print 'Hello World' as the output

*/

public static void main(String []args) {

System.out.println("Hello World"); // prints Hello World

}}

Let's look at how to save the file, compile and run the program. Please follow the steps given below:

Open notepad and add the code as above.

Page 4: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go To the directory where you saved the class. Assume it's

C:\.

Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no

errors in your code, the command prompt will take you to the next line (Assumption : The path

variable is set).

Now, type ' java MyFirstJavaProgram ' to run your program.

You will be able to see ' Hello World ' printed on the window.

C : > javac MyFirstJavaProgram.java

C : > java MyFirstJavaProgram

Hello World

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have

different meaning in Java.

Class Names - For all class names the first letter should be in Upper Case.

If several words are used to form a name of the class, each inner word's first letter should be in

Upper Case.

Example class MyFirstJavaClass

Method Names - All method names should start with a Lower Case letter.

If several words are used to form the name of the method, then each inner word's first letter

should be in Upper Case.

Example public void myMethodName()

Program File Name - Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case sensitive)

and append '.java' to the end of the name (if the file name and the class name do not match your

program will not compile).

Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as

'MyFirstJavaProgram.java'

public static void main(String args[]) - Java program processing starts from the main() method

which is a mandatory part of every Java program..

Java Identifiers: All Java components require names. Names used for classes, variables and methods are

called identifiers.In Java, there are several points to remember about identifiers. They are as follows:

All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore

(_).

After the first character identifiers can have any combination of characters.

A key word cannot be used as an identifier.

Most importantly identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value

Examples of illegal identifiers: 123abc, -salary

Java Modifiers: Like other languages, it is possible to modify classes, methods, etc., by using modifiers.

There are two categories of modifiers:

Page 5: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Access Modifiers: default, public , protected, private

Non-access Modifiers: final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables: We would see following type of variables in Java:

Local Variables

Class Variables (Static Variables)

Instance Variables (Non-static variables)

Above example will produce the following result: Size: MEDIUM

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be

defined inside enums as well.

Java Keywords: The following list shows the reserved words in Java. These reserved words may not be

used as constant or variable or any other identifier names.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long Native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

. Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports

the following fundamental concepts:

Polymorphism

Inheritance

Encapsulation

Abstraction

Classes

Objects

Instance

Method

Message Parsing

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can find many objects

around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.

Page 6: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Software objects also have a state and behavior. A software object's state is stored in fields and behavior

is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object

communication is done via methods.

Classes in Java:

A class is a blue print from which individual objects are created.

A sample of a class is given below:

public class Dog{

String breed;

int age;

String color;

void barking(){

}

void hungry(){

}

void sleeping(){ }}

A class can contain any of the following variable types.

Local variables: Variables defined inside methods, constructors or blocks are called local

variables. The variable will be declared and initialized within the method and the variable will be

destroyed when the method has completed.

Instance variables: Instance variables are variables within a class but outside any method. These

variables are instantiated when the class is loaded. Instance variables can be accessed from inside

any method, constructor or blocks of that particular class.

Class variables: Class variables are variables declared with in a class, outside any method, with

the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above

example, barking(), hungry() and sleeping() are methods.

Below mentioned are some of the important topics that need to be discussed when looking into classes of

the Java Language.

Constructors:When discussing about classes, one of the most important sub topic would be constructors.

Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler

builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors

is that they should have the same name as the class. A class can have more than one constructor.

Example of a constructor is given below:

public class Puppy{

public Puppy(){

}

Page 7: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

public Puppy(String name){

// This constructor has one parameter, name.

}

}

Java also supports Singleton Classes where you would be able to create only one instance of a class.

Creating an Object:

As mentioned previously, a class provides the blueprints for objects. So basically an object is created

from a class. In Java, the new key word is used to create new objects.

There are three steps when creating an object from a class:

Declaration: A variable declaration with a variable name with an object type.

Instantiation: The 'new' key word is used to create the object.

Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the

new object.

Example of creating an object is given below:

public class Puppy{

public Puppy(String name){

// This constructor has one parameter, name.

System.out.println("Passed Name is :" + name );

}

public static void main(String []args){

// Following statement would create an object myPuppy

Puppy myPuppy = new Puppy( "tommy" );

}

}

If we compile and run the above program, then it would produce the following result:

Passed Name is :tommy

Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects. To access an instance variable the fully

qualified path should be as follows:

/* First create an object */

ObjectReference = new Constructor();

/* Now call a variable as follows */

ObjectReference.variableName;

/* Now you can call a class method as follows */

ObjectReference.MethodName();

Example:

Page 8: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

This example explains how to access instance variables and methods of a class:

public class Puppy{

int puppyAge;

public Puppy(String name){

// This constructor has one parameter, name.

System.out.println("Passed Name is :" + name );

}

public void setAge( int age ){

puppyAge = age;

}

public int getAge( ){

System.out.println("Puppy's age is :" + puppyAge );

return puppyAge;

}

public static void main(String []args){

/* Object creation */

Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */

myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */

myPuppy.getAge( );

/* You can access instance variable as follows as well */

System.out.println("Variable Value :" + myPuppy.puppyAge );

}

}

If we compile and run the above program, then it would produce the following result:

Passed Name is :tommy

Puppy's age is :2

Variable Value :2

Source file declaration rules:

As the last part of this section let's now look into the source file declaration rules. These rules are

essential when declaring classes, import statements and package statements in a source file.

There can be only one public class per source file.

A source file can have multiple non public classes.

The public class name should be the name of the source file as well which should be appended by

.java at the end. For example : The class name is . public class Employee{} Then the source file

should be as Employee.java.

If the class is defined inside a package, then the package statement should be the first statement in

the source file.

If import statements are present then they must be written between the package statement and the

class declaration. If there are no package statements then the import statement should be the first

line in the source file.

Page 9: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Import and package statements will imply to all the classes present in the source file. It is not

possible to declare different import and/or package statements to different classes in the source

file.

Access Control Modifiers:

Java provides a number of access modifiers to set access levels for classes, variables, methods and

constructors. The four access levels are:

Visible to the package, the default. No modifiers are needed.

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Non Access Modifiers:

Java provides a number of non-access modifiers to achieve many other functionality.

The static modifier for creating class methods and variables

The final modifier for finalizing the implementations of classes, methods, and variables.

The abstract modifier for creating abstract classes and methods.

The synchronized and volatile modifiers, which are used for threads.

Creating Method:

Considering the following example to explain the syntax of a method:

public static int funcName(int a, int b) {

// body

}

Here,

public static : modifier.

int: return type

funcName: function name

a, b: formal parameters

int a, int b: list of parameters

Methods are also known as Procedures or Functions:

Procedures: They don't return any value.

Functions: They return value.

Method definition consists of a method header and a method body. The same is shown below:

modifier returnType nameOfMethod (Parameter List) {

// method body

}

The syntax shown above includes:

modifier: It defines the access type of the method and it is optional to use.

Page 10: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

returnType: Method may return a value.

nameOfMethod: This is the method name. The method signature consists of the method name

and the parameter list.

Parameter List: The list of parameters, it is the type, order, and number of parameters of a

method. These are optional, method may contain zero parameters.

method body: The method body defines what the method does with statements.

Example:

Here is the source code of the above defined method called max(). This method takes two parameters

num1 and num2 and returns the maximum between the two:

/** the snippet returns the minimum between two numbers */

public static int minFunction(int n1, int n2) {

int min;

if (n1 > n2)

min = n2;

else

min = n1;

return min;

}

Method Calling:

For using a method, it should be called. There are two ways in which a method is called i.e. method

returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the program control gets

transferred to the called method. This called method then returns control to the caller in two conditions,

when:

return statement is executed.

reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example:

System.out.println("This is tutorialspoint.com!");

System is a built-in class present in java.lang package. This class has a final modifier,

which means that, it cannot be inherited by other classes. It contains pre-defined methods

and fields, which provides facilities like standard input, output, etc.

out is a static final field (ie, variable)in System class which is of the type PrintStream (a

built-in class, contains methods to print the different data values). static fields and

methods must be accessed by using the class name, so ( System.out ).

out here denotes the reference variable of the type PrintStream class.

println() is a public method in PrintStream class to print the data values. Hence to access

a method in PrintStream class, we use out.println() (as non static methods and fields can

only be accessed by using the refrence varialble)

Page 11: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Java Bean

Prepared By

G.Vidya,

Assistant Professor,

Department of Computer Science (PG),

Kongunadu Arts and Science College,

Coimbatore-641029

Page 12: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

What am I going to talk about?

Introduction to Java Bean

Why Java Bean?

Java Bean conventions

Bean Tags

Using BDK

Jar Files

Putting it all together

Page 13: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Introduction to Java Bean

Java Bean is a Java class.

Java Bean is used in creating dynamic webpages and is still considered as the best and better approach for creating dynamic webpages.

It was developed in the late 90’s by Sun Microsystems.

In simple terms, Java Bean can be thought as a standard for webpages.

Supports Reusability and Boilerplate coding.

Though widely used, has some disadvantages.

Page 14: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Introduction to Java Bean

Page 15: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Why Java Bean?

Used for Web to solve complex problems.

User friendly and less intimidating for non Java programmers so,

it’s one less thing to think about.

Helps us understand View Logic and Business Logic.

Better than Scriptlet and include statements because of code

reusability and easy understandability.

Flexible and does not require frequent modifications.

Usually created using IDE’s like IntelliJ, Eclipse or NetBeans.

Page 16: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Tiers

Page 17: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Java Bean Conventions

Java Beans follows certain conventions and all of these conventions

are to be followed while creating a Java Bean. They are:

Must have a constructor with no arguments.

Must have the accessor and mutator methods.

The specific class must implement the Serializable Interface.

Page 18: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Constructors

A constructor in Java is a block of code similar to a method that’s

called when an instance of an object is created.

Constructors are different from methods.

A constructor allows you to provide initial values for class fields

when you create the object.

Can be thought as a simple method.

Page 19: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

public class Hello {

String name;

Hello(){

this.name = “I code Java!";

}

public static void main(String[] args) {

Hello obj = new Hello();

System.out.println(obj.name);

}

}

Page 20: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Getters and Setters

Getters and Setters are conventional methods used for retrieving

and updating the value of a variable.

Variables in most professional scenarios are private in nature.

Gives control to a programmer to know which variable does what

and provides transparency.

Always let Getters and Setters have higher access specifiers than

the variables.

Page 21: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Getters and Setters – Professional Definition

Getters and setters encapsulate the fields of a class by making them

accessible only through its public methods and keep the values

themselves private. That is considered a good OO principle.

Page 22: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

public class SimpleGetterAndSetter {

private int number;

public int getNumber() {

return this.number;

}

public void setNumber(int num) {

this.number = num;

}

}

SimpleGetterAndSetter obj = new SimpleGetterAndSetter();

obj.number = 10; //Pointless Code

out.println(number); //Pointless Code

Page 23: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

public class SimpleGetterAndSetter {

private int number;

public int getNumber() {

return this.number;

}

public void setNumber(int num) {

this.number = num;

}

}

SimpleGetterAndSetter obj = new SimpleGetterAndSetter();

obj.setNumber(10);

obj.getNumber();

Page 24: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Serializable Interface

Serialization is the process of saving an object’s states in a

persistent format and later restoring them back from the stream.

In Java, an object of a class is serializable if the class implements

the java.io.Serializable interface.

This is a marker interface which tells the JVM that the class is

eligible for serialization.

Serialization is used for storing data in a disk, saving a state of a

game, sending data over a network in a chat application.

Page 25: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James
Page 26: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Let’s see an example + a few JSP

tags!

Page 27: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JSP Tags – Bean Tags

<jsp: useBean id = “beanName”

scope = "page | request | session | application"

class = "packageName.className"

type= "packageName.className"

beanName="packageName.className | <%= expression >" >

</jsp:useBean>

Page 28: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

The Bean Development Kit (BDK)

BDK stands for Bean Development Kit and is entirely different from JDK.

BDK provides tools and resources for Bean development.

The BDK provides a reference bean container, the “BeanBox”.

The BeanBox provides a lot of functionalities and ways to test your Bean and comprehend different Bean behavior.

More about BDK can be learnt at http://www.oracle.com/technetwork/middleware/beehive/java-bdk-082633.html

Page 29: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Jar Files

Jar stands for Java-Archive.

It is a package file format typically used to aggregate many Java

class files and the associated metadata, resources into one file to

distribute application software or libraries on the Java platform.

Has several advantages and is widely used in professional

environments.

Page 30: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Title: Java Package

Prepared By

G.Vidya, Assistant Professor, Department of Computer Science (PG), Kongunadu Arts and Science College, Coimbatore-641029

Page 31: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.//save as Simple.java

1. package mypack;

2. public class Simple{

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

4. System.out.println("Welcome to package"); }}

5. How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

Page 32: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

The import keyword is used to make the classes and interface of another package accessible to the current package.

Example of package that import the packagename.//save by A.java

1. package pack;

2. public class A{

3. public void msg(){System.out.println("Hello");}

4. }

1. //save by B.java

2. package mypack;

3. import pack.*;

4.

5. class B{

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

7. A obj = new A();

8. obj.msg();

9. }

10. }

Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname//save by A.java

1. import pack.A;

2. class B{

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

4. A obj = new A();

5. obj.msg(); } }

Output:Hello3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to

import. But you need to use fully qualified name every time when you are accessing the class or interface.It is

generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

Example of package by import fully qualified name//save by A.java

1. package pack;

2. public class A{

3. public void msg(){System.out.println("Hello");} }

1. //save by B.java

2. package mypack;

3. class B{

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

5. pack.A obj = new pack.A();//using fully qualified name

Page 33: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

6. obj.msg(); } }

Output:Hello

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A

class implements an interface, thereby inheriting the abstract methods of the interface.Unless the class

that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways −

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface matching the name of

the file.

The byte code of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that

matches the package name.

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface must be declared

both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an

interface −

/* File name : NameOfInterface.java */

importjava.lang.*;

publicinterfaceNameOfInterface{

// Any number of final, static fields

// Any number of abstract method declarations\

}

Interfaces have the following properties −

Page 34: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an

interface.Each method in an interface is also implicitly abstract, so the abstract keyword is not

needed.Methods in an interface are implicitly public.

Example

/* File name : Animal.java */

interfaceAnimal{

publicvoid eat();

publicvoid travel();

}

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, agreeing

to perform the specific behaviors of the interface. If a class does not perform all the behaviors of

the interface, the class must declare itself as abstract.A class uses the implements keyword to

implement an interface. The implements keyword appears in the class declaration following the

extends portion of the declaration.

Example

/* File name : MammalInt.java */

publicclassMammalIntimplementsAnimal{

publicvoid eat(){

System.out.println("Mammal eats");}

publicvoid travel(){

System.out.println("Mammal travels");}

publicstaticvoid main(Stringargs[]){

MammalInt m =newMammalInt();

m.eat();

m.travel();

}}

This will produce the following result −

Mammal eats

Mammal travels

Page 35: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JAVA SWING

Prepared By

G.Vidya,

Assistant Professor,

Department of Computer Science (PG),

Kongunadu Arts and Science College,

Coimbatore-641029

Page 36: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• Java Swing tutorial is a part of Java Foundation

Classes (JFC) that is used to create window-based

applications. It is built on the top of AWT (Abstract

Windowing Toolkit) API and entirely written in java.

• Unlike AWT, Java Swing provides platform-independent

and lightweight components.

• The javax.swing package provides classes for java swing

API such as JButton, JTextField, JTextArea, JRadioButton,

JCheckbox, JMenu, JColorChooser etc.

Page 37: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Differences between java awt and swing that are given below.

N

o

.

Java AWT Java Swing

AWT components are platform-dependent. Java swing components are platform-

independent.

AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

AWT provides less components than Swing. Swing provides more powerful

componentssuch as tables, lists, scrollpanes,

colorchooser, tabbedpane etc.

AWT doesn't follows MVC(Model View Controller) where model represents data, view

represents presentation and controller acts as an interface between model and view.

Swing follows MVC.

Page 38: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James
Page 39: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JButton

• public class JButton extends AbstractButton implements Accessible

• JButton() It creates a button with no text and icon.

• JButton(String s)-It creates a button with the specified text.

• JButton(Icon i)-It creates a button with the specified icon object.

Page 40: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Methods of AbstractButton class:

• void setText(String s) : It is used to set specified text on button

• String getText() : It is used to return the text of the button.

• void setEnabled(boolean b) :It is used to enable or disable the button.

• void setIcon(Icon b) : It is used to set the specified Icon on the button.

• Icon getIcon() : It is used to get the Icon of the button. • void setMnemonic(int a): It is used to set the

mnemonic on the button. • void addActionListener(ActionListener a) : It is used to

add the action listener to this object.

Page 41: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• Java JButton Example import javax.swing.*; public class ButtonExample { public static void main(String[] args) { JFrame f=new JFrame("Button Example"); JButton b=new JButton("Click Here"); b.setBounds(50,100,95,30); f.add(b); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } } ADDING IMAGE • JFrame f=new JFrame("Button Example"); • JButton b=new JButton(new ImageIcon("D:\\icon.png"));//adding

image to button

Page 42: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JLabel • The object of JLabel class is a component for placing text

in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.

• JLabel() :Creates a JLabel instance with no image and with an empty string for the title.

• JLabel(String s): Creates a JLabel instance with the specified text.

• JLabel(Icon i): Creates a JLabel instance with the specified image.

• JLabel(String s, Icon i, int horizontalAlignment) :Creates a JLabel instance with the specified text, image, and horizontal

alignment.

Page 43: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• Methods Description

• String getText() - returns the text string that a label displays.

• void setText(String text)- defines the single line of text this component will display.

• void setHorizontalAlignment(int alignment)-It sets the alignment of the label's contents along the X axis.

• Icon getIcon()-It returns the graphic image that the label displays.

• int getHorizontalAlignment()-It returns the alignment of the label's contents along the X axis.

Page 44: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• Example: JFrame f= new JFrame("Label Example"); JLabel l1,l2; l1=new JLabel("First Label."); l1.setBounds(50,50, 100,30); l2=new JLabel("Second Label."); l2.setBounds(50,100, 100,30); f.add(l1); f.add(l2); f.setSize(300,300); f.setLayout(null); f.setVisible(true);

Page 45: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JTextField

public class JTextField extends JTextComponent implements SwingConstants

• JTextField(String text, int columns): Creates a new TextField initialized with the specified text and columns.

• void addActionListener(ActionListener l)-It is used to add the specified action listener to receive action events from this textfield.

• Action getAction()-It returns the currently set Action for this ActionEvent source, or null if no Action is set.

• void setFont(Font f)-It is used to set the current font.

• void removeActionListener(ActionListener l)-It is used to remove the specified action listener so that it no longer receives action events from this textfield.

Page 46: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• JFrame f= new JFrame("TextField Example");

JTextField t1,t2;

t1=new JTextField("Welcome to Javatpoint.“);

t1.setBounds(50,100, 200,30);

t2=new JTextField("AWT Tutorial");

t2.setBounds(50,150, 200,30);

f.add(t1); f.add(t2);

f.setSize(400,400);

Page 47: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• public class JTextArea extends JTextComponent • JTextArea(String s, int row, int column)-Creates a text area with

the specified number of rows and columns that displays specified text.

• void setRows(int rows)-It is used to set specified number of rows.

• void setColumns(int cols)-It is used to set specified number of columns.

• void setFont(Font f)-It is used to set the specified font.

• void insert(String s, int position)-It is used to insert the specified text on the specified position.

• void append(String s)-It is used to append the given text to the end of the document.

• JTextArea area=new JTextArea("Welcome to javatpoint");

area.setBounds(10,30, 200,200);

Page 48: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JPassword

• public class JPasswordField extends JTextField

• JPasswordField(String text, int columns)-Construct a new JPasswordField initialized with the specified text

and columns.

• e.g

• JPasswordField value = new JPasswordField();

• JLabel l1=new JLabel("Password:");

• l1.setBounds(20,100, 80,30);

Page 49: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

check box • JCheckBox(String text, boolean selected)-Creates

a check box with text and specifies whether or not it is initially selected.

• JCheckBox(Action a)-Creates a check box where properties are taken from the Action supplied.

• Methods • AccessibleContext getAccessibleContext() • It is used to get the AccessibleContext associated

with this JCheckBox. • protected String paramString() • It returns a string representation of this

JCheckBox.

Page 50: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• public class JCheckBox extends JToggleButton implements Accessible

CheckBoxExample(){ JFrame f= new JFrame("CheckBox Example"); JCheckBox checkBox1 = new JCheckBox("C++");

checkBox1.setBounds(100,100, 50,50); JCheckBox checkBox2 = new JCheckBox("Java", tr

ue); checkBox2.setBounds(100,150, 50,50);

Page 51: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

» JRADIOBUTTON

• public class JRadioButton extends JToggleButton implements Accessible

• JRadioButton(String s, boolean selected)- Creates a radio button with the specified text and selected status.

• void setText(String s)-It is used to set specified text on button. • String getText()--It is used to return the text of the button. • void setEnabled(boolean b)--It is used to enable or disable the button. • void setIcon(Icon b)--It is used to set the specified Icon on the button. • Icon getIcon()--It is used to get the Icon of the button. • void setMnemonic(int a)--It is used to set the mnemonic on the button. • void addActionListener(ActionListener a)--It is used to add the action listener to this object

JRadioButton r1=new JRadioButton("A) Male"); JRadioButton r2=new JRadioButton("B) Female"); r1.setBounds(75,50,100,30); r2.setBounds(75,100,100,30); ButtonGroup bg=new ButtonGroup(); bg.add(r1);bg.add(r2); f.add(r1);f.add(r2);

Page 52: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JScrollbar

• public class JScrollBar extends JComponent implements Adjustable, Accessible

• JScrollBar(int orientation, int value, int extent, int min, int max)

• Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

• JScrollBar s=new JScrollBar();

• s.setBounds(100,100, 50,100);

• s.addAdjustmentListener(new AdjustmentListener() {

• public void adjustmentValueChanged(AdjustmentEvent e) {

• label.setText("Vertical Scrollbar value is:"+ s.getValue());

Page 53: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class.

• JTree(Object[] value) - Creates a JTree with every element of the specified array as the child of a new root node.

• JTree(TreeNode root) - Creates a JTree with the specified TreeNode as its root, which displays the root node.

Page 54: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; public class TreeExample { JFrame f; TreeExample(){ f=new JFrame(); DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style"); DefaultMutableTreeNode color=new DefaultMutableTreeNode("color"); DefaultMutableTreeNode font=new DefaultMutableTreeNode("font"); style.add(color); style.add(font); DefaultMutableTreeNode red=new DefaultMutableTreeNode("red"); DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue"); DefaultMutableTreeNode black=new DefaultMutableTreeNode("black"); DefaultMutableTreeNode green=new DefaultMutableTreeNode("green"); color.add(red); color.add(blue); color.add(black); color.add(green); JTree jt=new JTree(style); f.add(jt); f.setSize(200,200); f.setVisible(true); } public static void main(String[] args) { new TreeExample(); }}

Page 55: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants JTabbedPane(int tabPlacement)-Creates an empty TabbedPane with a specified tab placement. JTabbedPane(int tabPlacement, int tabLayoutPolicy)-Creates an empty TabbedPane with a specified tab placement and tab layout policy.

Page 56: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable() - Creates a table with empty cells.JTable(Object[][] rows, Object[] columns) -Creates a table with the specified data.

import javax.swing.*;

public class TableExample {

JFrame f;

TableExample(){

f=new JFrame();

String data[][]={ {"101","Amit","670000"},

{"102","Jai","780000"},

{"101","Sachin","700000"}};

String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);

jt.setBounds(30,40,200,300);

Page 57: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

JScrollPane sp=new JScrollPane(jt);

f.add(sp);

f.setSize(300,400); f.setVisible(true);

}

public static void main(String[] args) {

new TableExample();

}

}

Page 58: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class

inherits JComponent class. • public class JOptionPane extends JComponent implements Ac

cessible

• JOptionPane() It is used to create a JOptionPane with a test message.

• JOptionPane(Object message)-It is used to create an instance of JOptionPane to display a message.

• JOptionPane(Object message, int messageType)-It is used to create an instance of JOptionPane to display a message with specified message type and default options.

Page 59: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

• JDialog createDialog(String title)-It is used to create and return a new parentless JDialog with the specified title.

• static void showMessageDialog(Component parentComponent, Object message)-It is used to create an information-message dialog titled "Message".

• static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)-It is used to create a message dialog with given title and messageType.

• static int showConfirmDialog(Component parentComponent, Object message)-It is used to create a dialog with the options Yes, No and Cancel; with the title, Select an Option.

• static String showInputDialog(Component parentComponent, Object message)It is used to show a question-message dialog requesting input from the user.

• void setInputValue(Object newValue)It is used to set the input value that was selected or input by the user.

Page 60: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

import javax.swing.*;

public class OptionPaneExample {

JFrame f;

OptionPaneExample(){

f=new JFrame();

JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");

}

public static void main(String[] args) {

new OptionPaneExample();

}

}

Page 61: Title: Introduction Java ProgrammingPG)-4.pdf · Introduction Java Programming Java programming language was originally developed by Sun Microsystems which was initiated by James

Types of dialog boxes • JOptionPane.showMessageDialog(f,"Successfully Updated.","

Alert",JOptionPane.WARNING_MESSAGE); • String name=JOptionPane.showInputDialog(f,"Enter Name");

• JOptionPane.showConfirmDialog(f,"Are you sure?");