+ All Categories
Home > Documents > 108784097 Java Tutorial

108784097 Java Tutorial

Date post: 19-Jan-2016
Category:
Upload: tejashulk
View: 37 times
Download: 0 times
Share this document with a friend
Description:
dfgdfg
149
Javabeginner Tutorial Table of Contents Introduction to Java About Java Platform Independence Java Virtual Machine Object Oriented Programming Java Features Java Applications Getting Started with Java Java Architecture Compiling and Running an Application Java Development Kit javadoc JAR Files PATH and CLASSPATH Introduction to Java 1.5 Basic Language Elements Keywords Comments Variable, Identifiers and Data Types Classes Objects Interface Instance Members Static Members Arrays Java Operators Java Operators Assignment operators Arithmetic operators Relational operators Logical operators Bitwise operators Compound operators Conditional operators Operator Precedence Java Control Statements Introduction to Control Statements Selection Statements Iteration Statements Transfer Statements Java Access Modifiers Introduction to Java Access Modifiers public access modifier private access modifier protected access modifier default access modifier Classes and Objects Class Variables – Static Fields Class Methods – Static Methods Instance Variables Final Variable, Methods and Classes Introduction to Java Objects Method Overloading Created By www.ebooktutorials.blogspot.in Content Downloaded From www.javabeginner.com
Transcript
Page 1: 108784097 Java Tutorial

Javabeginner Tutorial

Table of Contents

Introduction to Java

About JavaPlatform Independence Java Virtual Machine Object Oriented ProgrammingJava Features Java Applications

Getting Started with JavaJava ArchitectureCompiling and Running an ApplicationJava Development KitjavadocJAR FilesPATH and CLASSPATHIntroduction to Java 1.5

Basic Language Elements KeywordsCommentsVariable, Identifiers and Data TypesClassesObjectsInterfaceInstance MembersStatic MembersArrays

Java OperatorsJava OperatorsAssignment operatorsArithmetic operatorsRelational operatorsLogical operatorsBitwise operatorsCompound operatorsConditional operatorsOperator Precedence

Java Control StatementsIntroduction to Control StatementsSelection StatementsIteration StatementsTransfer Statements

Java Access ModifiersIntroduction to Java Access Modifierspublic access modifierprivate access modifierprotected access modifierdefault access modifier

Classes and ObjectsClass Variables – Static FieldsClass Methods – Static MethodsInstance VariablesFinal Variable, Methods and ClassesIntroduction to Java ObjectsMethod Overloading

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 2: 108784097 Java Tutorial

Java ConstructorsOverloaded ConstructorsConstructor Chaining

Object SerializationIntroduction to Object SerializationTransient Fields and SerializationInput and Output Object Streams

Java Class InheritanceJava Class Inheritancethis and super keywords

Java Object CastingObject Reference Type Castinginstanceof Operator

Abstract class and InterfaceAbstract Class in javaJava InterfacePolymorphism

Java Method Overriding

Java String ClassString ClassCreation of StringsString EqualityString Functions

Java toString() MethodJava toString() Method

Java String ComparisonCompare String objects to determine Equality

Java StringBuffer StringBuffer ClassCreation of StringBuffer'sStringBuffer Functions

Java Exception HandlingExceptions in JavaException ClassesException Statement SyntaxRules for try, catch and finally Blockstry, catch and finallyDefining new Exceptionsthrow, throws statementHandling Multiple Exceptions

Java Singleton Design PatternSingletonImplementing the Singleton Pattern

Java Threads TutorialIntroduction to ThreadsThread CreationThread SynchronizationSynchronized MethodsSynchronized BlocksThread StatesThread PriorityThread SchedulerYielding

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 3: 108784097 Java Tutorial

Sleeping and Waking UpWaiting and NotifyingJoiningDeadlock

Java Collections FrameworkCore Collection InterfacesConcrete ClassesStandard utility methods and algorithmsHow are Collections UsedJava ArrayListJava LinkedListJava TreeSetJava HashMapJava VectorJava HashTableJava HashSet

Java Date UtilJava Date APIJava Date Source Code

Java Swing TutorialIntoduction to Java SwingJFrameJInternalFrameJWindowJOptionPaneJLabelJTextFieldJPasswordFieldJTextAreaJButtonJRadioButtonJCheckBoxJComboBoxJListJTabbedPaneJMenuBarScrollable JPopupMenuJToolBarBorderLayoutFlowLayoutGridLayoutGridBagLayoutJava Look and FeelSwing CalculatorSwing Address Book

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 4: 108784097 Java Tutorial

Introduction to Java Programming

Introduction to Computer Science using Java

Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++.Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth,Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independentprogramming language. This site gives you an Introduction to Java Programming accompanied with many javaexamples. Its a complete course in java programming for beginners to advanced java.

Platform independent

Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled intoplatform specific machine, rather into platform independent byte code. This byte code is distributed over the web andinterpreted by virtual Machine (JVM) on whichever platform it is being run.

Java Virtual Machine

What is the Java Virtual Machine? What is its role?

Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role inthis concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on topof real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codesand then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as themachine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can becompiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must beimplemented on a particular platform before compiled programs can run on that platform.

Object Oriented Programming

Since Java is an object oriented programming language it has following features:

Reusability of CodeEmphasis on data rather than procedureData is hidden and cannot be accessed by external functionsObjects can communicate with each other through functionsNew data and functions can be easily addedJava has powerful features. The following are some of them:-

SimpleReusablePortable (Platform Independent)DistributedRobustSecureHigh PerformanceDynamicThreadedInterpreted

Object Oriented Programming is a method of implementation in which programs are organized as cooperativecollection of objects, each of which represents an instance of a class, and whose classes are all members of ahierarchy of classes united via inheritance relationships.

OOP Concepts

Four principles of Object Oriented Programming areAbstractionEncapsulationInheritancePolymorphism

Abstraction

Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thusprovide crisply defined conceptual boundaries, relative to the perspective of the viewer.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 5: 108784097 Java Tutorial

Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure andbehavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.

Encapsulation

* Hides the implementation details of a class.* Forces the user to use an interface to access data* Makes the code more maintainable.

Inheritance

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism

Polymorphism is the existence of the classes or methods in different forms or single name denoting differentimplementations.

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objectsacross net via URLs.

Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrentlywithin the same program A single Java program can have many different threads executing independently andcontinuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of Cand C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory.Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use deleteoperator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is doneautomatically with garbage collector.

Java Applications

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominantenterprise-enabled programming language suitable for developing significant and critical applications. Today, It is usedfor many types of applications including Web based applications, Financial applications, Gaming applications, embeddedsystems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and manymore. This site outlines the building blocks of java by stating few java examples along with some java tutorials.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 6: 108784097 Java Tutorial

Getting Started with Java

Getting Java Basics quickly has become easy with Javabeginner.com. This site is for the java programmers whowant to use the Java programming language to create applications using the Java basics. This site is for absolutebeginners to advanced java programmers who do not require any prerequisite Java knowledge. For getting startedwith Java you’ll have to have some basic understanding of the concepts of programming.

After going through all the tutorials in this site, you would have learnt the essential concepts and features of the JavaProgramming Language which include exceptions, Swing GUI programming, Collections framework etc. A lot of codeexamples are used through out tutorial to make you understand the language better.All the listings and programs in the website are compiled and run using the JDK 1.5.Download : JDK and JRE 1.5

Java Architecture

The Java environment is composed of a number of system components. You use these components at compile time tocreate the Java program and at run time to execute the program. Java achieves its independence by creating programsdesigned to run on the Java Virtual Machine rather than any specific computer system.

After you write a Java program, you use a compiler that reads the statements in the program and translates theminto a machine independent format called bytecode.Bytecode files, which are very compact, are easily transported through a distributed system like the Internet.The compiled Java code (resulting byte code) will be executed at run time.

Java programs can be written and executed in two ways:

Stand-alone application (A Java Swing Application)Applet which runs on a web browser (Example: Internet Explorer)

Java source code

A Java program is a collection of one or more java classes. A Java source file can contain more than one classdefinition and has a .java extension. Each class definition in a source file is compiled into a separate class file. Thename of this compiled file is comprised of the name of the class with .class as an extension. Before we proceed furtherin this section, I would recommend you to go through the ‘Basic Language Elements’.

Below is a java sample code for the traditional Hello World program. Basically, the idea behind this Hello Worldprogram is to learn how to create a program, compile and run it. To create your java source code you can use anyeditor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }//End of main}//End of HelloWorld Class

OutputHello World

ABOUT THE PROGRAM

I created a class named “HelloWorld” containing a simple main function within it. The keyword class specifies that weare defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive). All javaprograms begin execution with the method named main(). main method that gets executed has the following signature: public static void main(String args[]).Declaring this method as public means that it is accessible from outside theclass so that the JVM can find it when it looks for the program to start it. It is necessary that the method is declaredwith return type void (i.e. no arguments are returned from the method). The main method contains a String argumentarray that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class.The program contains a line ‘System.out.println(“Hello World”);’ that tells the computer to print out on one line of textnamely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The double slashes ‘//’ are used for comments that canbe used to describe what a source code is doing. Everything to the right of the slashes on the same line does not getcompiled, as they are simply the comments in a program.

Java Main method Declarations

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

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 7: 108784097 Java Tutorial

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

All the 3 valid main method’s shown above accepts a single String array argument.

Compiling and Running an Application

To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains documentation,examples, installation instructions, class libraries and packages, and tools. Download an editor like Textpad/EditPlus totype your code. You must save your source code with a .java extension. The name of the file must be the name of thepublic class contained in the file.

Steps for Saving, compiling and Running a Java

Step 1:Save the program With .java Extension.Step 2:Compile the file from DOS prompt by typing javac <filename>.Step 3:Successful Compilation, results in creation of .class containing byte codeStep 4:Execute the file by typing java <filename without extension>

Java Development Kit

The Java Developer’s Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installationinstructions, class libraries and packages, and tools

javadoc

The javadoc tool provided by Sun is used to produce documentation for an application or program,

Jar Files

A jar file is used to group together related class files into a single file for more compact storage, distribution, andtransmission.

PATH and CLASSPATH

The following are the general programming errors, which I think every beginning java programmer would come across.Here is a solution on how to solve the problems when running on a Microsoft Windows Machine.

1. ‘javac’ is not recognized as an internal or external command, operable program or batch file

When you get this error, you should conclude that your operating system cannot find the compiler (javac). To solvethis error you need to set the PATH variable.

How to set the PATH Variable?

Firstly the PATH variable is set so that we can compile and execute programs from any directory without having totype the full path of the command. To set the PATH of jdk on your system (Windows XP), add the full path of thejdk<version>\bin directory to the PATH variable. Set the PATH as follows on a Windows machine:

a. Click Start > Right Click “My Computer” and click on “Properties”b. Click Advanced > Environment Variables.c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value forPATH is:

C:\jdk<version>\bin (jdk<version is nothing but the name of the directory where jdk is installed)

If there are already some entries in the PATH variable then you must add a semicolon and then add the above value(Version being replaced with the version of JDK). The new path takes effect in each new command prompt windowyou open after setting the PATH variable.

2. Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld

If you receive this error, java cannot find your compiled byte code file, HelloWorld.class.If both your class files and

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 8: 108784097 Java Tutorial

source code are in the same working directory and if you try running your program from the current working directorythan, your program must get executed without any problems as, java tries to find your .class file is your currentdirectory. If your class files are present in some other directory other than that of the java files we must set theCLASSPATH pointing to the directory that contain your compiled class files.CLASSPATH can be set as follows on aWindows machine:

a. Click Start > Right Click “My Computer” and click on “Properties”b. Click Advanced > Environment Variables.

Add the location of classes’ folder containing all your java classes in User Variables.

If there are already some entries in the CLASSPATH variable then you must add a semicolon and then add the newvalue . The new class path takes effect in each new command prompt window you open after setting the CLASSPATHvariable.

Java 1.5

The Java 1.5 released in September 2004.

Goals

Less code complexityBetter readabilityMore compile-time type safetySome new functionality (generics, scanner)

New Features

Enhanced for loopEnumerated typesAutoboxing & unboxingGeneric typesScannerVariable number of arguments (varargs)Static importsAnnotations

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 9: 108784097 Java Tutorial

Basic Language Elements

(Identifiers, keywords, literals, white spaces and comments)

This part of the java tutorial teaches you the basic language elements and syntax for the java programminglanguage. Once you get these basic language concepts you can continue with the other object oriented programminglanguage concepts.

KeywordsThere are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed todo. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are casesensitive, all characters being lower case.

Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). Allthe keywords are in lowercase.

abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

Keywords are marked in yellow as shown in the sample code below

/** This class is a Hello World Program used to introducethe Java Language*/public class HelloWorld {public static void main(String[] args) {System.out.println(“Hello World”); //Prints output to console

}}

For more information on different Keywords – Java Keywords

Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to

the C programming language. const and goto are Java keywords. The word finalize is the name of a method

of the Object class and hence not a keyword. enum and label are not keywords.

CommentsComments are descriptions that are added to a program to make code easier to understand. The compiler ignorescomments and hence its only for documentation of the program.

Java supports three comment styles.

Block style comments begin with /* and terminate with */ that spans multiple lines.

Line style comments begin with // and terminate at the end of the line. (Shown in the above program)

Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generallycreated using the automatic documentation generation tool, such as javadoc. (Shown in the above program)

name of this compiled file is comprised of the name of the class with .class as an extension.

Variable, Identifiers and Data Types

Variables are used for data that change during program execution. All variables have a name, a type, and a scope.The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope ofthe Java program. Variables have a data type, that indicates the kind of value they can store. Variables declaredinside of a block or method are called local variables; They are not automatically initialized. The compiler will generatean error as a result of the attempt to access the local variables before a value has been assigned.

public class localVariableEx {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 10: 108784097 Java Tutorial

public static int a; public static void main(String[] args) { int b; System.out.println("a : "+a); System.out.println("b : "+b); //Compilation error}}

Note in the above example, a compilation error results in where the variable is tried to be accessed and not at theplace where its declared without any value.

The data type indicates the attributes of the variable, such as the range of values that can be stored and theoperators that can be used to manipulate the variable. Java has four main primitive data types built into the language.You can also create your own composite data types.

Java has four main primitive data types built into the language. We can also create our own data types.

Integer: byte, short, int, and long.Floating Point: float and doubleCharacter: charBoolean: variable with a value of true or false.

The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since Ithought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table.The size for each Java type can be obtained by a simple Google search.

Data Type Default Value (for fields) Rangebyte 0 -127 to +128short 0 -32768 to +32767int 0

long 0Lfloat 0.0f

double 0.0dchar ‘\u0000′ 0 to 65535

String (object) nullboolean false

When we declare a variable we assign it an identifier and a data type.

For Example

String message = “hello world”

In the above statement, String is the data type for the identifier message. If you don’t specify a value when thevariable is declared, it will be assigned the default value for its data type.

Identifier Naming Rules

Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.Must begin with a letter, dollar sign, or an underscoreAre case sensitiveKeywords cannot be used as identifiersWithin a given section of your program or scope, each user defined item must have a unique identifierCan be of any length.

Classes

A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An objectexhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe thebehavior of an object. Methods are nothing but members of a class that provide a service for an object or performsome business logic.

Objects

An object is an instance of a class created using a new operator. The new operator returns a reference to a newinstance of a class. This reference can be assigned to a reference variable of the class. The process of creating objectsfrom a class is called instantiation. An object reference provides a handle to an object that is created and stored inmemory. In Java, objects can only be manipulated via references, which can be stored in variables.

Interface

An Interface is a contract in the form of collection of method and constant declarations. When a class implements aninterface, it promises to implement all of the methods declared in that interface.

Instance Members

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 11: 108784097 Java Tutorial

Each object created will have its own copies of the fields defined in its class called instance variables which representan object’s state. The methods of an object define its behaviour called instance methods. Instance variables andinstance methods, which belong to objects, are collectively called instance members. The dot ‘.’ notation with a objectreference is used to access Instance Members.

Static Members

Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable isinitialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods arecollectively known as static members, and are declared with a keyword static. Static members in the class can beaccessed either by using the class name or by using the object reference, but instance members can only be accessedvia object references.

Below is a program showing the various parts of the basic language syntax that were discussed above.

/** Comment * Displays "Hello World!" to the standard output.

*/public class HelloWorld { String output = ""; static HelloWorld helloObj; //Line 1

public HelloWorld(){ output = "Hello World"; }

public String printMessage(){ return output; }

public static void main (String args[]) { helloObj = new HelloWorld(); //Line 2 System.out.println(helloObj.printMessage()); }

}

Class Name: HelloWorldObject Reference: helloObj (in Line 1)Object Created: helloObj (In Line 2)Member Function: printMessageField: output (String)Static Member: helloObjInstance Member : output (String)

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 12: 108784097 Java Tutorial

Java Operators Tutorial

Java Operators

They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appearbefore (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between itsarguments.

Operators in java fall into 8 different categories:

Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,compound assignment, conditional, and type.

Assignment Operators = Arithmetic Operators - + * / % ++ --

Relational Operators > < >= <= == != Logical Operators && || & | ! ^ Bit wise Operator & | ^ >> >>> Compound Assignment Operators += -= *= /= %=

<<= >>= >>>= Conditional Operator ?:

Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment,conditional, and type.

Assignment operators

The java assignment operator statement has the following syntax:

<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

public class AssignmentOperatorsDemo {

public AssignmentOperatorsDemo() { // Assigning Primitive Values int j, k; j = 10; // j gets the value 10. j = 5; // j gets the value 5. Previous value is overwritten. k = j; // k gets the value 5. System.out.println("j is : " + j); System.out.println("k is : " + k); // Assigning References Integer i1 = new Integer("1"); Integer i2 = new Integer("2"); System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2); i1 = i2; System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2); // Multiple Assignments k = j = 10; // (k = (j = 10)) System.out.println("j is : " + j); System.out.println("k is : " + k); } public static void main(String args[]) { new AssignmentOperatorsDemo(); }}

Download AssignmentOperatorsDemoSource code

Arithmetic operators

Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (orremainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below thatdemonstrates the different arithmetic operators in java.

The binary operator + is overloaded in the sense that the operation performed is determined by the type of theoperands. When one of the operands is a String object, the other operand is implicitly converted to its stringrepresentation and string concatenation is performed.

String message = 100 + "Messages"; //"100 Messages"

public class ArithmeticOperatorsDemo {

public ArithmeticOperatorsDemo() { int x, y = 10, z = 5; x = y + z; System.out.println("+ operator resulted in " + x); x = y - z; System.out.println("- operator resulted in " + x); x = y * z;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 13: 108784097 Java Tutorial

System.out.println("* operator resulted in " + x); x = y / z; System.out.println("/ operator resulted in " + x); x = y % z; System.out.println("% operator resulted in " + x); x = y++; System.out.println("Postfix ++ operator resulted in " + x); x = ++z; System.out.println("Prefix ++ operator resulted in " + x); x = -y; System.out.println("Unary operator resulted in " + x); // Some examples of special Cases int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is // Integer.MIN_VALUE. int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is // Integer.MAX_VALUE. System.out.println("tooBig becomes " + tooBig); System.out.println("tooSmall becomes " + tooSmall); System.out.println(4.0 / 0.0); // Prints: Infinity System.out.println(-4.0 / 0.0); // Prints: -Infinity System.out.println(0.0 / 0.0); // Prints: NaN double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value // 1.0. double d2 = 12.0F / 8; // result: 1.5 System.out.println("d1 is " + d1); System.out.println("d2 iss " + d2); } public static void main(String args[]) { new ArithmeticOperatorsDemo(); }}

Download ArithmeticOperatorsDemo Source code

Relational operators

Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:

greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).

All relational operators are binary operators, and their operands are numeric expressions.

Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value.Relational operators have precedence lower than arithmetic operators, but higher than that of the assignmentoperators. An example program is shown below that demonstrates the different relational operators in java.

public class RelationalOperatorsDemo { public RelationalOperatorsDemo( ) {

int x = 10, y = 5; System.out.println("x > y : "+(x > y)); System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x <= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y)); }

public static void main(String args[]){ new RelationalOperatorsDemo(); } }

Download RelationalOperatorsDemo Source code

Logical operators

Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean,operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logicaloperator must be a boolean data type, and the result is always a boolean data type. An example program is shownbelow that demonstrates the different Logical operators in java.

public class LogicalOperatorsDemo {

public LogicalOperatorsDemo() { boolean x = true; boolean y = false; System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y)); System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("!x : " + (!x)); } public static void main(String args[]) { new LogicalOperatorsDemo(); }}

Download LogicalOperatorsDemo Source code

Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.

x y !x x & y

x && y

x | y

x || y

x ^ y

true true false true true false

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 14: 108784097 Java Tutorial

true false false false true true

false true true false true true

false false true false false false

Bitwise operators

Java provides Bit wise operators to manipulate the contents of variables at the bit level.

These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise

operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. Anexample program is shown below that demonstrates the different Bit wise operators in java.

public class BitwiseOperatorsDemo { public BitwiseOperatorsDemo() { int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1 int z; System.out.println("x & y : " + (x & y)); System.out.println("x | y : " + (x | y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("~x : " + (~x)); System.out.println("x << y : " + (x << y)); System.out.println("x >> y : " + (x >> y)); System.out.println("x >>> y : " + (x >>> y)); //There is no unsigned left shift operator }

public static void main(String args[]) new BitwiseOperatorsDemo();

}

Download BitwiseOperatorsDemo Source code

The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below.

A B ~A A & B A | B A ^ B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

Output

3,0,3

/* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |, ^, & */

public class BitwisePrecedenceEx {

public static void main(String[] args) { int a = 1 | 2 ^ 3 & 5; int b = ((1 | 2) ^ 3) & 5; int c = 1 | (2 ^ (3 & 5)); System.out.print(a + "," + b + "," + c); }}

Downloadad BitwiseOperatorsDemo2 Source code

Compound operators

The compound operators perform shortcuts in common programming operations. Java has eleven compoundassignment operators.

Syntax:

argument1 operator = argument2.

The above statement is the same as, argument1 = argument1 operator argument2. An example program is shownbelow that demonstrates the different Compound operators in java.

public class CompoundOperatorsDemo {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 15: 108784097 Java Tutorial

public CompoundOperatorsDemo() { int x = 0, y = 5; x += 3; System.out.println("x : " + x); y *= x; System.out.println("y : " + y); /*Similarly other operators can be applied as shortcuts. Other

compound assignment operators include boolean logical

, bitwiseand shift operators*/ } public static void main(String args[]) { new CompoundOperatorsDemo(); }}

Download CompoundOperatorsDemo Source code

Conditional operators

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluatesthe first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the thirdargument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditionalexpression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as(a?(b?(c?d:e):f):g)

An example program is shown below that demonstrates the Ternary operator in java.

public class TernaryOperatorsDemo {

public TernaryOperatorsDemo() { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } public static void main(String args[]) { new TernaryOperatorsDemo(); }}

Download TernaryOperatorsDemo Source code

/* * The following programs shows that when no explicit parenthesis is used then the conditional operator * evaluation is from right to left */

public class BooleanEx1 {

static String m1(boolean b) { return b ? "T" : "F"; } public static void main(String[] args) { boolean t1 = false ? false : true ? false : true ? false : true; boolean t2 = false ? false : (true ? false : (true ? false : true)); boolean t3 = ((false ? false : true) ? false : true) ? false : true; System.out.println(m1(t1) + m1(t2) + m1(t3)); }}

Output

FFT

Download TernaryOperatorsDemo2 Source code

Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly,as specified in

the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.

In java Conversions can occur by the following ways:

Using a cast operator (explicit promotion)Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)A value of one type is assigned to a variable of a different type (assignment promotion)

Operator PrecedenceThe order in which operators are applied is known as precedence. Operators with a higher precedence are appliedbefore operators with a lower precedence. The operator precedence order of Java is shown below. Operators at thetop of the table are applied before operators lower down in the table. If two operators have the same precedence,they are applied in the order they appear in a statement.

That is, from left to right. You can use parentheses to override the default precedence.

postfix [] . () expr++ expr--unary ++expr --expr +expr -expr ! ~

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 16: 108784097 Java Tutorial

creation/caste new (type)exprmultiplicative * / %

additive + -shift >> >>>

relational < <= > >= instanceofequality == !=

bitwise AND &bitwise exclusive OR ^bitwise inclusive OR |

logical AND &&logical OR ||ternary ?:

assignment = "op="

Example

In an operation such as,

result = 4 + 5 * 3

First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that '*' takes higherprecedence than '+' according to chart shown above. This kind of precedence of one operator over another applies toall the operators.

QUIZ

1. How to generate a random number between 1 to x, x being a whole number greater than 1

Ans: double result = x * Math.random();

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 17: 108784097 Java Tutorial

Java Control Flow Statements

Java Control statements control the order of execution in a java program, based on data values and conditionallogic. There are three main categories of control flow statements;

· Selection statements: if, if-else and switch.

· Loop statements: while, do-while and for.

· Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Selection Statements

The If Statement

The if statement executes a block of code only if the specified expression is true. If the value is false, then the if blockis skipped and execution continues with the rest of the program. You can either have a single statement or a block ofcode within an if statement. Note that the conditional expression must be a Boolean expression.

The simple if statement has the following syntax:

if (<conditional expression>)<statement action>

Below is an example that demonstrates conditional execution based on if statement condition.

public class IfStatementDemo {

public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); }}

Output

b > a

Download IfStatementDemo.java

The If-else Statement

The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements inthe else block are executed. You can either have a single statement or a block of code within if-else blocks. Note thatthe conditional expression must be a Boolean expression.

The if-else statement has the following syntax:

if (<conditional expression>)<statement action>else<statement action>

Below is an example that demonstrates conditional execution based on if else statement condition.

public class IfElseStatementDemo {

public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } }}

Output

b > a

Download IfElseStatementDemo.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 18: 108784097 Java Tutorial

Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a seriesof if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression isa code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, itcompares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controllingexpression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code blockwill be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.

Its general form is as follows:

switch (<non-long integral expression>) {

case label1: <statement1>case label2: <statement2>…case labeln: <statementn>default: <statement>} // end switch

When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you mustinsert a break statement, which causes the program to continue executing after the current code block.

Below is a java example that demonstrates conditional execution based on nested if else statement condition to findthe greatest of 3 numbers.

public class SwitchCaseStatementDemo {

public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } }}

Output

c is the greatest

Download SwitchCaseStatementDemo.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 19: 108784097 Java Tutorial

Control statements control the order of execution in a java program, based on data values and conditional logic.There are three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Iteration Statements

While Statement

The while statement is a looping construct control statement that executes a block of code while a condition is true.You can either have a single statement or a block of code within the while loop. The loop will never be executed if thetesting expression evaluates to false. The loop condition must be a boolean expression.

The syntax of the while loop is

while (<loop condition>)<statements>

Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10.

public class WhileLoopDemo {

public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); } }}

Output

Printing Numbers from 1 to 1012345678910

Download WhileLoopDemo.java

Do-while Loop Statement

The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at thebeginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do,followed by the statements that make up the body of the loop. Finally, the keyword while and the test expressioncompletes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continueswith the statement immediately following the loop. You can either have a single statement or a block of code withinthe do-while loop.

The syntax of the do-while loop is

do<loop body>while (<loop condition>);

Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to10.

public class DoWhileLoopDemo {

public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 20: 108784097 Java Tutorial

System.out.println(count++); } while (count <= 10); }}

Output

Printing Numbers from 1 to 1012345678910

Download DoWhileLoopDemo.java

Below is an example that creates A Fibonacci sequence controlled by a do-while loop

public class Fibonacci {

public static void main(String args[]) { System.out.println("Printing Limited set of Fibonacci Sequence"); double fib1 = 0; double fib2 = 1; double temp = 0; System.out.println(fib1); System.out.println(fib2); do { temp = fib1 + fib2; System.out.println(temp); fib1 = fib2; //Replace 2nd with first number fib2 = temp; //Replace temp number with 2nd number } while (fib2 < 5000); }}

Output

Printing Limited set of Fibonacci Sequence

0.01.01.02.03.05.08.013.021.034.055.089.0144.0233.0377.0610.0987.01597.02584.04181.06765.0

Download Fibonacci.java

For Loops

The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a countercontrolled loop.

The syntax of the loop is as follows:

for (<initialization>; <loop condition>; <increment expression>)<loop body>

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 21: 108784097 Java Tutorial

The first part of a for statement is a starting initialization, which executes once before the loop begins. The<initialization> section can also be a comma-separated list of expression statements. The second part of a forstatement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluatedas false the first time, the loop will never be executed. The third part of the for statement is the body of the loop.These are the instructions that are repeated each time the program executes the loop. The final part of the forstatement is an increment expression that automatically executes after each repetition of the loop body. Typically, thisstatement changes the value of the counter, which is then tested to see if the loop should continue.All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons aremandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of forloop is commonly used to construct an infinite loop.

Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.

public class ForLoopDemo {

public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.println(count); } }}

Output

Printing Numbers from 1 to 1012345678910

Download ForLoopDemo.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 22: 108784097 Java Tutorial

Control statements control the order of execution in a java program, based on data values and conditional logic. Thereare three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Transfer Statements

Continue Statement

A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of thenearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements inthe loop, but you do not want to exit the loop itself.

The syntax of the continue statement is

continue; // the unlabeled formcontinue <label>; // the labeled form

You can also provide a loop with a label and then use the label in your continue statement. The label name is optional,and is usually only used when you wish to return to the outermost loop in a series of nested loops.

Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.

public class ContinueExample {

public static void main(String[] args) { System.out.println("Odd Numbers"); for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // Rest of loop body skipped when i is even System.out.println(i + "\t"); } }}

Output

Odd Numbers13579

Download ContinueExample.java

Break Statement

The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a breakstatement when you want to jump immediately to the statement following the enclosing control structure. You can alsoprovide a loop with a label, and then use the label in your break statement. The label name is optional, and is usuallyonly used when you wish to terminate the outermost loop in a series of nested loops.

The Syntax for break statement is as shown below;

break; // the unlabeled formbreak <label>; // the labeled form

Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.

public class BreakExample {

public static void main(String[] args) { System.out.println("Numbers 1 - 10"); for (int i = 1;; ++i) { if (i == 11) break; // Rest of loop body skipped when i is even System.out.println(i + "\t");

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 23: 108784097 Java Tutorial

} }}

Output

Numbers 1 – 1012345678910

Download BreakExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 24: 108784097 Java Tutorial

Introduction to Java Access Modifiers

Java Access SpecifiersThe access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can controlwhat information or data can be accessible by other classes. To take advantage of encapsulation, you should minimizeaccess whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as well as thefields, methods and constructors in your classes. A member has package or default accessibility when no accessibilitymodifier is specified.

Access Modifiers

1. private2. protected3. default4. public

public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in theJava program, whether these classes are in the same package or in another package.

private access modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used forfields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, whichmeans they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make allfields private and provide public getter methods for them.

protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields andmethods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed onlyby subclasses in other packages. Classes in the same package can also access protected fields, methods andconstructors as well, even if they are not a subclass of the protected member’s class.

default access modifier

Java provides a default specifier which is used when no access modifier is present. Any class, field, method orconstructor that has no declared access modifier is accessible only by classes in the same package. The defaultmodifier is not used for fields and methods within an interface.

Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessingfields and methods. The output of each of these java files depict the Java access specifiers.

The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Baseclass and a subclass within the enclosing class that belongs to the same class as shown below.

package pckage1;

class BaseClass {

public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; }}

public class SubclassInSamePackage extends BaseClass {

public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 25: 108784097 Java Tutorial

SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); }}

Output

Value of x is : 10Value of x is : 20Value of z is : 10Value of z is : 30Value of x is : 10Value of x is : 20

The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. Thisjava class extends First class (SubclassInSamePackage.java).

import pckage1.*;

public class SubClassInDifferentPackage extends SubclassInSamePackage {

public int getZZZ() { return z; }

public static void main(String args[]) { SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage(); SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access specifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access specifiers - Private // if we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/ //Access specifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected. /* System.out.println("Value of z is : "+subClassObj.z);

subClassObj.setZ(30);

System.out.println("Value of z is : "+subClassObj.z);*/ System.out.println("Value of z is : " + subClassDiffObj.getZZZ()); //Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default. /*

System.out.println("Value of a is : "+subClassObj.a);

subClassObj.setA(20);

System.out.println("Value of a is : "+subClassObj.a);*/ }}

Output

Value of x is : 10Value of x is : 30Value of z is : 10

The third class is ClassInDifferentPackage.java which is present in a different package then the first one.

import pckage1.*;

public class ClassInDifferentPackage {

public static void main(String args[]) { SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Private // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected. /* System.out.println("Value of z is : "+subClassObj.z);

subClassObj.setZ(30);

System.out.println("Value of z is : "+subClassObj.z);*/

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 26: 108784097 Java Tutorial

//Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default. /* System.out.println("Value of a is : "+subClassObj.a);

subClassObj.setA(20);

System.out.println("Value of a is : "+subClassObj.a);*/ }}

Output

Value of x is : 10Value of x is : 30

Download all the 3 source files

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 27: 108784097 Java Tutorial

Java Classes and Objects

Introduction to Java Classes

A class is nothing but a blueprint or a template for creating different objects which defines its properties andbehaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields andmethods to describe the behavior of an object.

Methods are nothing but members of a class that provide a service for an object or perform some business logic. Javafields and member functions names are case sensitive. Current states of a class’s corresponding object are stored inthe object’s instance variables. Methods define the operations that can be performed in java programming.

A class has the following general syntax:

<class modifiers>class<class name><extends clause> <implements clause>{

// Dealing with Classes (Class body)<field declarations (Static and Non-Static)><method declarations (Static and Non-Static)><Inner class declarations><nested interface declarations><constructor declarations><Static initializer blocks>}

Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadthand height. Also the class contains a member function getVolume().

public class Cube {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); }}

How do you reference a data member/function?

This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name ofthe member inside the object.( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followedby the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example:

cubeObject.length = 4;cubeObject.breadth = 4;cubeObject.height = 4;cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within aclass. When you declare a field to be static, only a single instance of the associated variable is created common to allthe objects of that class. Hence when one object changes the value of a class variable, it affects all objects of theclass. We can access a class variable by using the name of the class, and not necessarily using a reference to anindividual object within the class. Static variables can be accessed even though no objects of that class exist. It isdeclared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods areoften used to provide global functions for Java programs. For example, methods in the java.lang.Math package areclass methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object hasa state that is determined by the values stored in the object. An object is said to have changed its state when one ormore data values stored in the object have been modified. When an object responds to a message, it will usuallyperform an action, change its state etc. An object that has the ability to store values is often said to have persistence.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 28: 108784097 Java Tutorial

Consider this simple Java program showing the use of static fields and static methods

// Class and Object initialization showing the Object Oriented concepts in Javaclass Cube {

int length = 10; int breadth = 10; int height = 10; public static int numOfCubes = 0; // static variable public static int getNoOfCubes() { //static method return numOfCubes; } public Cube() { numOfCubes++; // }}

public class CubeStaticTest {

public static void main(String args[]) { System.out.println("Number of Cube objects = " + Cube.numOfCubes); System.out.println("Number of Cube objects = " + Cube.getNoOfCubes()); }}

Download CubeStaticTest.java

Output

Number of Cube objects = 0Number of Cube objects = 0

Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.

Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A finalclass can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes likeString and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier toachieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final methodwill result in a compiler error.

Introduction to Java Objects

The Object Class is the super class for all classes in Java.

Some of the object class methods are

equalstoString()wait()notify()notifyAll()hashcode()clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a newinstance of a class. This reference can be assigned to a reference variable of the class. The process of creating objectsfrom a class is called instantiation. An object encapsulates state and behavior.

An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only bemanipulated via references, which can be stored in variables.

Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float.Each time you create an object, a new set of instance variables comes into existence which defines the characteristicsof that object. If you want to create an object of the class and have the reference variable associated with this object,you must also allocate memory for the object by using the new operator. This process is called instantiating anobject or creating an object instance.

When you create a new object, you use the new operator to instantiate the object. The new operator returns thelocation of the object which you assign o a reference type.

Below is an example showing the creation of Cube objects by using the new operator.

public class Cube {

int length = 10; int breadth = 10; int height = 10; public int getVolume() {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 29: 108784097 Java Tutorial

return (length * breadth * height); } public static void main(String[] args) { Cube cubeObj; // Creates a Cube Reference cubeObj = new Cube(); // Creates an Object of Cube System.out.println("Volume of Cube is : " + cubeObj.getVolume()); }}

Download Cube.java

Method Overloading

Method overloading results when two or more methods in the same class have the same name but differentparameters. Methods with the same name must differ in their types or number of parameters. This allows the compilerto match parameters and choose the correct method when a number of choices exist. Changing just the return type isnot enough to overload a method, and will be a compile-time error. They must have a different signature. When nomethod matching the input parameters is found, the compiler attempts to convert the input parameters to types ofgreater precision. A match may then be found without error. At compile time, the right implementation is chosen basedon the signature of the method call

Below is an example of a class demonstrating Method Overloading

public class MethodOverloadDemo {

void sumOfParams() { // First Version System.out.println("No parameters"); } void sumOfParams(int a) { // Second Version System.out.println("One parameter: " + a); } int sumOfParams(int a, int b) { // Third Version System.out.println("Two parameters: " + a + " , " + b); return a + b; } double sumOfParams(double a, double b) { // Fourth Version System.out.println("Two double parameters: " + a + " , " + b); return a + b; } public static void main(String args[]) { MethodOverloadDemo moDemo = new MethodOverloadDemo(); int intResult; double doubleResult; moDemo.sumOfParams(); System.out.println(); moDemo.sumOfParams(2); System.out.println(); intResult = moDemo.sumOfParams(10, 20); System.out.println("Sum is " + intResult); System.out.println(); doubleResult = moDemo.sumOfParams(1.1, 2.2); System.out.println("Sum is " + doubleResult); System.out.println(); }}

Download MethodOverloadDemo.java

Output

No parameters

One parameter: 2

Two parameters: 10 , 20Sum is 30

Two double parameters: 1.1 , 2.2Sum is 3.3000000000000003

Below is a code snippet to shows the interfaces that a Class Implements:

Class cls = java.lang.String.class;Class[] intfs = cls.getInterfaces();// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]// The interfaces for a primitive type is an empty arraycls = int.class;intfs = cls.getInterfaces(); // []

Below is a code snippet to show whether a Class Object Represents a Class or Interface:

Class cls = java.lang.String.class;boolean isClass = !cls.isInterface(); // truecls = java.lang.Cloneable.class;isClass = !cls.isInterface(); // false

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 30: 108784097 Java Tutorial

Java Constructors

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does notinclude a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, thetypes must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, whenno explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call.Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); }}

Download Cube1.java

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.If such a class requires a default constructor, its implementation must be provided. Any attempt to call the defaultconstructor will be a compile time error if an explicit default constructor is not provided in such a case.

Java Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as theclass, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1constructor is overloaded one being the default constructor and the other being a parameterized constructor.

It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in aconstructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling thedefault constructor to create a Cube object results in the second and third parameterized constructors being called aswell. Java requires that any this() call must occur as the first statement in a constructor.

Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructorscontext

public class Cube2 {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube2() { this(10, 10); System.out.println("Finished with Default Constructor"); } Cube2(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params"); } Cube2(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params"); } public static void main(String[] args) {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 31: 108784097 Java Tutorial

Cube2 cubeObj1, cubeObj2; cubeObj1 = new Cube2(); cubeObj2 = new Cube2(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume()); }}

public class Cube2 {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube2() { this(10, 10); System.out.println("Finished with Default Constructor"); } Cube2(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params"); } Cube2(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params"); } public static void main(String[] args) { Cube2 cubeObj1, cubeObj2; cubeObj1 = new Cube2(); cubeObj2 = new Cube2(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume()); }}

Output

Finished with Parameterized Constructor having 3 paramsFinished with Parameterized Constructor having 2 paramsFinished with Default ConstructorFinished with Parameterized Constructor having 3 paramsVolume of Cube1 is : 1000Volume of Cube2 is : 6000

Download Cube2.java

Constructor Chaining

Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor whichdoes not include either the this() function or an explicit super() call as its first statement. The super() statementinvokes a constructor of the super class.The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of theconstructor.The explicit super allows parameter values to be passed to the constructor of its superclass and must have matchingparameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from thesuperclass, based on the signature of the call. This is called constructor chaining.

Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube() { this(10, 10); System.out.println("Finished with Default Constructor of Cube"); } Cube(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params of Cube"); } Cube(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params of Cube"); }}

public class SpecialCube extends Cube {

int weight; SpecialCube() { super(); weight = 10; } SpecialCube(int l, int b) {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 32: 108784097 Java Tutorial

this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params of SpecialCube"); } SpecialCube(int l, int b, int h) { super(l, b, h); weight = 20; System.out.println("Finished with Parameterized Constructor having 3 params of SpecialCube"); } public static void main(String[] args) { SpecialCube specialObj1 = new SpecialCube(); SpecialCube specialObj2 = new SpecialCube(10, 20); System.out.println("Volume of SpecialCube1 is : " + specialObj1.getVolume()); System.out.println("Weight of SpecialCube1 is : " + specialObj1.weight); System.out.println("Volume of SpecialCube2 is : " + specialObj2.getVolume()); System.out.println("Weight of SpecialCube2 is : " + specialObj2.weight); }}

Download SpecialCube.java

Output

Finished with Parameterized Constructor having 3 params of SpecialCubeFinished with Parameterized Constructor having 2 params of SpecialCubeVolume of SpecialCube1 is : 1000Weight of SpecialCube1 is : 10Volume of SpecialCube2 is : 2000Weight of SpecialCube2 is : 20

The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it canonly be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the sameconstructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leadsto chaining of subclass constructors to superclass constructors.if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the defaultconstructor in the superclass is inserted.

Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. Thiswill be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using thesuper() construct with the right arguments to match the appropriate constructor of the superclass.

Below is an example of a class demonstrating constructor chaining using explicit super() call.

class Cube {

int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params of Cube"); }}

public class SpecialCube1 extends Cube {

int weight; SpecialCube1() { super(10, 20, 30); //Will Give a Compilation Error without this line weight = 10; } public static void main(String[] args) { SpecialCube1 specialObj1 = new SpecialCube1(); System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume()); }}

Output

Finished with Parameterized Constructor having 3 params of CubeVolume of SpecialCube1 is : 6000

Download SpecialCube1.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 33: 108784097 Java Tutorial

Java Serialization

Introduction to Object Serialization

Java object serialization is used to persist Java objects to a file, database, network, process or any other system.Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then beread at a later time, or in another environment, to recreate the original objects.

Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state frombeing written to the stream and from being restored during deserialization. Java provides classes to support writingobjects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface orthe java.io.Externalizable interface can be written to streams.public interface Serializable

The Serializable interface has no methods or fields. (Marker Interface)Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

Transient Fields and Java Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part ofthe persistent state of the object and thus never saved during serialization.

You can use the transient keyword to describe temporary variables, or variables that contain local information,such as a process ID or a time lapse.

Input and Output Object Streams

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializingobjects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface fordeserializing objects.

These high-level streams are each chained to a low-level stream, such as FileInputStream or FileOutputStream.The low-level streams handle the bytes of data. The writeObject method saves the state of the class by writing theindividual fields to the ObjectOutputStream. The readObject method is used to deserialize the object fromthe object input stream.

Case 1: Below is an example that demonstrates object Serialization into a File

PersonDetails is the bean class that implements the Serializable interface

import java.io.Serializable;

public class PersonDetails implements Serializable {

private String name; private int age; private String sex; public PersonDetails(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; }}

GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).

import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.util.ArrayList;import java.util.List;

public class GetPersonDetails {

public static void main(String[] args) { String filename = "person.txt"; List pDetails = null;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 34: 108784097 Java Tutorial

FileInputStream fis = null; ObjectInputStream in = null; try { fis = new FileInputStream(filename); in = new ObjectInputStream(fis); pDetails = (ArrayList) in.readObject(); in.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } // print out the size System.out.println("Person Details Size: " + pDetails.size()); System.out.println(); }}

PersonPersist is the class that is used to serialize object into the File (person.txt).

public class PersonPersist {

public static void main(String[] args) { String filename = "person.txt"; PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); List list = new ArrayList(); list.add(person1); list.add(person2); list.add(person3); FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(list); out.close(); System.out.println("Object Persisted"); } catch (IOException ex) { ex.printStackTrace(); } }}

——————————————————————————–

Case 2: Below is an example that demonstrates object Serialization into the database

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(name BLOB,viewname VARCHAR2(30));

PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;

public class PersonPersist {

static String userid = "scott", password = "tiger"; static String url = "jdbc:odbc:bob"; static int count = 0; static Connection con = null; public static void main(String[] args) { Connection con = getOracleJDBCConnection(); PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); PreparedStatement ps; try { ps = con .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)"); write(person1, ps); ps.execute(); write(person2, ps); ps.execute(); write(person3, ps); ps.execute(); ps.close(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM SerialTest"); while (rs.next()) { Object obj = read(rs, "Name"); PersonDetails p = (PersonDetails) obj; System.out.println(p.getName() + "\t" + p.getAge() + "\t" + p.getSex()); } rs.close(); st.close(); } catch (Exception e) {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 35: 108784097 Java Tutorial

} } public static void write(Object obj, PreparedStatement ps) throws SQLException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(obj); oout.close(); ps.setBytes(1, baos.toByteArray()); ps.setInt(2, ++count); } public static Object read(ResultSet rs, String column) throws SQLException, IOException, ClassNotFoundException { byte[] buf = rs.getBytes(column); if (buf != null) { ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(buf)); return objectIn.readObject(); } return null; } public static Connection getOracleJDBCConnection() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } return con; }}

——————————————————————————–

Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(name BLOB,viewname VARCHAR2(30));

PersonPersist is the class that is used to serialize object into the Database Table SerialTest

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;

public class PersonPersist {

static String userid = "scott", password = "tiger"; static String url = "jdbc:odbc:bob"; static int count = 0; static Connection con = null; static String s; public static void main(String[] args) { Connection con = getOracleJDBCConnection(); PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); PreparedStatement ps; try { ps = con .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)"); write(person1, ps); ps.execute(); write(person2, ps); ps.execute(); write(person3, ps); ps.execute(); ps.close(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM SerialTest"); while (rs.next()) { Object obj = read(rs, "Name"); PersonDetails p = (PersonDetails) obj; System.out.println(p.getName() + "\t" + p.getAge() + "\t" + p.getSex()); } rs.close(); st.close(); } catch (Exception e) { } } public static void write(Object obj, PreparedStatement ps) throws SQLException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(obj); oout.close(); byte[] buf = baos.toByteArray(); s = new sun.misc.BASE64Encoder().encode(buf); ps.setString(1, s); // ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray())); ps.setBytes(1, baos.toByteArray());

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 36: 108784097 Java Tutorial

ps.setInt(2, ++count); } public static Object read(ResultSet rs, String column) throws SQLException, IOException, ClassNotFoundException { byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s); // byte[] buf = Base64.base64ToByteArray(new // String(rs.getBytes(column))); if (buf != null) { ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(buf)); Object obj = objectIn.readObject(); // Contains the object PersonDetails p = (PersonDetails) obj; System.out.println(p.getName() + "\t" + p.getAge() + "\t" + p.getSex()); } return null; } public static Connection getOracleJDBCConnection() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } return con; }}

Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As beforetheobject to be serialized must implement the Serializable interface. PersonDetails is the bean class that implementsthe Serializable interface

import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;

public class ObjectSerializationExample {

public static void main(String args[]) { try { Object object = new javax.swing.JButton("Submit"); // Serialize to a file namely "filename.dat" ObjectOutput out = new ObjectOutputStream( new FileOutputStream("filename.dat")); out.writeObject(object); out.close(); // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); out = new ObjectOutputStream(bos); out.writeObject(object); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } }}

Download Object Serialization Source code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 37: 108784097 Java Tutorial

Java Inheritance

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of asubclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism isused to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y,then a class z, which extends class x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find that the base class isthe vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive froma super class which must be written in the header of the subclass definition. The subclass inherits members of thesuperclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. Thejava.lang.Object class is always at the top of any Class inheritance hierarchy.

class Box {

double width; double height; double depth; Box() { } Box(double w, double h, double d) { width = w; height = h; depth = d; } void getVolume() { System.out.println("Volume is : " + width * height * depth); }}

public class MatchBox extends Box {

double weight; MatchBox() { } MatchBox(double w, double h, double d, double m) { super(w, h, d); weight = m; } public static void main(String args[]) { MatchBox mb1 = new MatchBox(10, 10, 10, 10); mb1.getVolume(); System.out.println("width of MatchBox 1 is " + mb1.width); System.out.println("height of MatchBox 1 is " + mb1.height); System.out.println("depth of MatchBox 1 is " + mb1.depth); System.out.println("weight of MatchBox 1 is " + mb1.weight); }}

Output

Volume is : 1000.0width of MatchBox 1 is 10.0height of MatchBox 1 is 10.0depth of MatchBox 1 is 10.0weight of MatchBox 1 is 10.0

Download MatchBox.java

What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, asthese members are only accessible by their simple names in subclasses within the same package as the superclass.3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.4. A subclass can extend only one superclass

class Vehicle {

// Instance fields int noOfTyres; // no of tyres private boolean accessories; // check if accessorees present or not protected String brand; // Brand of the car // Static fields private static int counter; // No of Vehicle objects created // Constructor Vehicle() { System.out.println("Constructor of the Super class called"); noOfTyres = 5; accessories = true; brand = "X"; counter++; } // Instance methods public void switchOn() { accessories = true; } public void switchOff() { accessories = false; } public boolean isPresent() { return accessories; } private void getBrand() { System.out.println("Vehicle Brand: " + brand); } // Static methods

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 38: 108784097 Java Tutorial

public static void getNoOfVehicles() { System.out.println("Number of Vehicles: " + counter); }}

class Car extends Vehicle {

private int carNo = 10; public void printCarInfo() { System.out.println("Car number: " + carNo); System.out.println("No of Tyres: " + noOfTyres); // Inherited. // System.out.println("accessories: " + accessories); // Not Inherited. System.out.println("accessories: " + isPresent()); // Inherited. // System.out.println("Brand: " + getBrand()); // Not Inherited. System.out.println("Brand: " + brand); // Inherited. // System.out.println("Counter: " + counter); // Not Inherited. getNoOfVehicles(); // Inherited. }}

public class VehicleDetails { // (3)

public static void main(String[] args) { new Car().printCarInfo(); }}

Output

Constructor of the Super class calledCar number: 10No of Tyres: 5accessories: trueBrand: XNumber of Vehicles: 1

Download VehicleDetails.java

this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and superyou have full control on whether to call a method or field present in the same class or to call from the immediatesuperclass. This keyword is used as a reference to the current object which is an instance of the current class. Thekeyword super also references the current object, but as an instance of the current class’s super class.

The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with thesame name. If a method needs to pass the current object to another method, it can do so using the this reference.Note that the this reference cannot be used in a static context, as static code is not executed in the context of anyobject.

class Counter {

int i = 0; Counter increment() { i++; return this; } void print() { System.out.println("i = " + i); }}

public class CounterDemo extends Counter {

public static void main(String[] args) { Counter x = new Counter(); x.increment().increment().increment().print(); }}

Output

Volume is : 1000.0width of MatchBox 1 is 10.0height of MatchBox 1 is 10.0depth of MatchBox 1 is 10.0weight of MatchBox 1 is 10.0

Download CounterDemo.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 39: 108784097 Java Tutorial

Java Object Typecasting

Object Reference Type Casting

In java object typecasting one object reference can be type cast into another object reference. The cast can beto its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules andruntime rules for casting in java.

How to Typecast Objects with a dynamically loaded Class ? – The casting of object references depends on therelationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variableof the type Object, because the Object class is a superclass of every Java class.There can be 2 casting java scenarios

· Upcasting· Downcasting

When we cast a reference along the class hierarchy in a direction from the root class towards the children orsubclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classestowards the root, it is an upcast. We need not use a cast operator in this case.

The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when wetry to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the newtype it is being cast to.

Below is an example showing when a ClassCastException can occur during object casting

//X is a supper class of Y and Z which are sibblings.public class RunTimeCastDemo {

public static void main(String args[]) { X x = new X(); Y y = new Y(); Z z = new Z(); X xy = new Y(); // compiles ok (up the hierarchy) X xz = new Z(); // compiles ok (up the hierarchy) // Y yz = new Z(); incompatible type (siblings) // Y y1 = new X(); X is not a Y // Z z1 = new X(); X is not a Z X x1 = y; // compiles ok (y is subclass of X) X x2 = z; // compiles ok (z is subclass of X) Y y1 = (Y) x; // compiles ok but produces runtime error Z z1 = (Z) x; // compiles ok but produces runtime error Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y) Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z) // Y y3 = (Y) z; inconvertible types (siblings) // Z z3 = (Z) y; inconvertible types (siblings) Object o = z; Object o1 = (Y) o; // compiles ok but produces runtime error }}

Download ClassCastException example Source Code

Casting Object References: Implicit Casting using a Compiler

In general an implicit cast is done when an Object reference is assigned (cast) to:

* A reference variable whose type is the same as the class from which the object was instantiated.An Object as Object is a super class of every Class.* A reference variable whose type is a super class of the class from which the object was instantiated.* A reference variable whose type is an interface that is implemented by the class from which the object wasinstantiated.* A reference variable whose type is an interface that is implemented by a super class of the class from which theobject was instantiated.

Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the automaticconversion of object references handled by the compiler

interface Vehicle {}class Car implements Vehicle {}

class Ford extends Car {}

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 40: 108784097 Java Tutorial

Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign theFord reference to the Car variable:I.e. we can do the following

Example 1c = f; //Ok Compiles fine

Where c = new Car();And, f = new Ford();The compiler automatically handles the conversion (assignment) since the types are compatible (sub class – superclass relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.

Example 2v = c; //Ok Compiles finec = v; // illegal conversion from interface type to class type results in compilation error

Where c = new Car();And v is a Vehicle interface reference (Vehicle v)

The compiler automatically handles the conversion (assignment) since the types are compatible (class – interfacerelationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is aVehicle).

Casting Object References: Explicit Casting

Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario. Theexplicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. As before, we considerthe same Car and Ford Class

class Car {void carMethod(){}}

class Ford extends Car {void fordMethod () {}}

We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter.The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford object,it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.

public void breakingSystem (Car obj) {obj.carMethod();if (obj instanceof Ford)

((Ford)obj).fordMethod ();}

To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if itis a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot befound in the Car definition.

The following program shown illustrates the use of the cast operator with references.

Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. BothCar and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class willautomatically extends the Object by default. This code instantiates an object of the class Ford and assigns the object’sreference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In order to usea reference of a class type to invoke a method, the method must be defined at or above that class in the classhierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod isnot present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by castingthe Car object reference to the Ford Class Object reference as done in the program. Also an attempt to cast an objectreference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happenswithout any error.

class Car extends Object {

void carMethod() { }}

class HeavyVehicle extends Object {}

class Ford extends Car {

void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }}

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 41: 108784097 Java Tutorial

class Honda extends Car {

void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }}

public class ObjectCastingEx {

public static void main(String[] args) { Car obj = new Ford(); // Following will result in compilation error // obj.fordMethod(); //As the method fordMethod is undefined for the Car Type // Following will result in compilation error // ((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in the HeavyVehicle Type // Following will result in compilation error ((Ford) obj).fordMethod(); //Following will compile and run // Honda hondaObj = (Ford)obj; Cannot convert as they are sibblings }}

Download Object Reference Casting Source Code

One common casting that is performed when dealing with collections is, you can cast an object reference into a String.

import java.util.Vector;

public class StringCastDemo {

public static void main(String args[]) { String username = "asdf"; String password = "qwer"; Vector v = new Vector(); v.add(username); v.add(password); // String u = v.elementAt(0); Cannot convert from object to String Object u = v.elementAt(0); //Cast not done System.out.println("Username : " + u); String uname = (String) v.elementAt(0); // cast allowed String pass = (String) v.elementAt(1); // cast allowed System.out.println(); System.out.println("Username : " + uname); System.out.println("Password : " + pass); }}

Download Object String Casting Source Code

Output

Username : asdfUsername : asdfPassword : qwer

instanceof OperatorThe instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specificclass, or implements a specific interface. It returns true if an object is an instance of the class or if the objectimplements the interface, otherwise it returns false.

Below is an example showing the use of instanceof operator

class Vehicle {

String name; Vehicle() { name = "Vehicle"; }}

class HeavyVehicle extends Vehicle {

HeavyVehicle() { name = "HeavyVehicle"; }}

class Truck extends HeavyVehicle {

Truck() { name = "Truck"; }}

class LightVehicle extends Vehicle {

LightVehicle() { name = "LightVehicle"; }}

public class InstanceOfExample {

static boolean result; static HeavyVehicle hV = new HeavyVehicle(); static Truck T = new Truck(); static HeavyVehicle hv2 = null; public static void main(String[] args) { result = hV instanceof HeavyVehicle; System.out.print("hV is an HeavyVehicle: " + result + "\n"); result = T instanceof HeavyVehicle; System.out.print("T is an HeavyVehicle: " + result + "\n"); result = hV instanceof Truck; System.out.print("hV is a Truck: " + result + "\n"); result = hv2 instanceof HeavyVehicle; System.out.print("hv2 is an HeavyVehicle: " + result + "\n"); hV = T; //Sucessful Cast form child to parent T = (Truck) hV; //Sucessful Explicit Cast form parent to child }

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 42: 108784097 Java Tutorial

}

Download instanceof operator Source Code

Output

hV is an HeavyVehicle: trueT is an HeavyVehicle: truehV is a Truck: falsehv2 is an HeavyVehicle: false

Note: hv2 does not yet reference an HeavyVehicle object, instanceof returns false. Also we can’t use instanceofoperator with siblings

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 43: 108784097 Java Tutorial

Java Abstract class and Interface

Abstract Class in java

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot beinstantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes aredeclared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclassesdown the inheritance tree.

Like any other class, an abstract class can contain fields that describe the characteristics and methods that describethe actions that a class can perform. An abstract class can include methods that contain no implementation. These arecalled abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If aclass has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstractmethods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for theabstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object musthave an implementation for all of its methods. You need to create a subclass that provides an implementation for theabstract method.

A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creatinginstances of the class would not be meaningful.

abstract class Vehicle {

int numofGears; String color; abstract boolean hasDiskBrake(); abstract int getNoofGears();}

Example of a shape class as an abstract class

abstract class Shape {

public String color; public Shape() { } public void setColor(String c) { color = c; } public String getColor() { return color; } abstract public double area();}

We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc.All shapes have some common fields and methods, but each can, of course, add more fields and methods. Theabstract class guarantees that each shape will have the same set of basic properties. We declare this class abstractbecause there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles,triangles etc.

public class Point extends Shape {

static int x, y; public Point() { x = 0; y = 0; } public double area() { return 0; } public double perimeter() { return 0; } public static void print() { System.out.println("point: " + x + "," + y); } public static void main(String args[]) { Point p = new Point(); p.print(); }}

Output

point: 0, 0

Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methodsof the Shape class must be implemented by the Point class.

The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itselfwill also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.

A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extendsan abstract class, it can’t extend any other class.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 44: 108784097 Java Tutorial

Java Interface

In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be usedto define a generic template and then one or more abstract classes to define partial implementations of the interface.Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which areimplicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstractclass cannot be instantiated.

Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces.Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.

If a class that implements an interface does not define all the methods of the interface, then it must be declaredabstract and the method definitions must be provided by the subclass that extends the abstract class.

Example 1: Below is an example of a Shape interface

interface Shape {

public double area(); public double volume();}

Below is a Point class that implements the Shape interface.

public class Point implements Shape {

static int x, y; public Point() { x = 0; y = 0; } public double area() { return 0; } public double volume() { return 0; } public static void print() { System.out.println("point: " + x + "," + y); } public static void main(String args[]) { Point p = new Point(); p.print(); }}

Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.

Example 2: Below is a java interfaces program showing the power of interface programming in java

Listing below shows 2 interfaces and 4 classes one being an abstract class.Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. Theclasses B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of theimplemented interface I2, the class D1 is declared abstract.Also,i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present.Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies toi1.methodA1(), which is again resolved by a downcast.

When we invoke the toString() method which is a method of an Object, there does not seem to be any problem asevery interface or class extends Object and any class can override the default toString() to suit your application needs.((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does nothave any relationship with C1 except they are “siblings”. You can’t cast siblings into one another.

When a given interface method is invoked on a given reference, the behavior that results will be appropriate to theclass from which that particular object was instantiated. This is runtime polymorphism based on interfaces andoverridden methods.

interface I1 {

void methodI1(); // public static by default}

interface I2 extends I1 {

void methodI2(); // public static by default}

class A1 {

public String methodA1() { String strA1 = "I am in methodC1 of class A1"; return strA1; } public String toString() { return "toString() method of class A1"; }}

class B1 extends A1 implements I2 {

public void methodI1() { System.out.println("I am in methodI1 of class B1"); } public void methodI2() { System.out.println("I am in methodI2 of class B1");

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 45: 108784097 Java Tutorial

}}

class C1 implements I2 {

public void methodI1() { System.out.println("I am in methodI1 of class C1"); } public void methodI2() { System.out.println("I am in methodI2 of class C1"); }}

// Note that the class is declared as abstract as it does not// satisfy the interface contractabstract class D1 implements I2 {

public void methodI1() { } // This class does not implement methodI2() hence declared abstract.}

public class InterFaceEx {

public static void main(String[] args) { I1 i1 = new B1(); i1.methodI1(); // OK as methodI1 is present in B1 // i1.methodI2(); Compilation error as methodI2 not present in I1 // Casting to convert the type of the reference from type I1 to type I2 ((I2) i1).methodI2(); I2 i2 = new B1(); i2.methodI1(); // OK i2.methodI2(); // OK // Does not Compile as methodA1() not present in interface reference I1 // String var = i1.methodA1(); // Hence I1 requires a cast to invoke methodA1 String var2 = ((A1) i1).methodA1(); System.out.println("var2 : " + var2); String var3 = ((B1) i1).methodA1(); System.out.println("var3 : " + var3); String var4 = i1.toString(); System.out.println("var4 : " + var4); String var5 = i2.toString(); System.out.println("var5 : " + var5); I1 i3 = new C1(); String var6 = i3.toString(); System.out.println("var6 : " + var6); // It prints the Object toString() method Object o1 = new B1(); // o1.methodI1(); does not compile as Object class does not define // methodI1() // To solve the probelm we need to downcast o1 reference. We can do it // in the following 4 ways ((I1) o1).methodI1(); // 1 ((I2) o1).methodI1(); // 2 ((B1) o1).methodI1(); // 3 /* * * B1 does not have any relationship with C1 except they are "siblings". * * Well, you can't cast siblings into one another. * */ // ((C1)o1).methodI1(); Produces a ClassCastException }}

Output

I am in methodI1 of class B1I am in methodI2 of class B1I am in methodI1 of class B1I am in methodI2 of class B1var2 : I am in methodC1 of class A1var3 : I am in methodC1 of class A1var4 : toString() method of class A1var5 : toString() method of class A1var6 : C1@190d11I am in methodI1 of class B1I am in methodI1 of class B1I am in methodI1 of class B1

Download Java Interface Program Example

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 46: 108784097 Java Tutorial

PolymorphismPolymorphism means one name, many forms. There are 3 distinct forms of Java Polymorphism;

Method overloading (Compile time polymorphism)Method overriding through inheritance (Run time polymorphism)Method overriding through the Java interface (Run time polymorphism)

Polymorphism allows a reference to denote objects of different types at different times during execution. A supertype reference exhibits polymorphic behavior, since it can denote objects of its subtypes.

interface Shape {

public double area(); public double volume();}

class Cube implements Shape {

int x = 10; public double area( ) {

return (6 * x * x); }

public double volume() { return (x * x * x); }

}

class Circle implements Shape {

int radius = 10; public double area() { return (Math.PI * radius * radius); } public double volume() { return 0; }}

public class PolymorphismTest {

public static void main(String args[]) { Shape[] s = { new Cube(), new Circle() }; for (int i = 0; i < s.length; i++) { System.out.println("The area and volume of " + s[i].getClass() + " is " + s[i].area() + " , " + s[i].volume()); } }}

Output

The area and volume of class Cube is 600.0 , 1000.0The area and volume of class Circle is 314.1592653589793 , 0.0

Download Java Polymorphism Program Example

The methods area() and volume() are overridden in the implementing classes. The invocation of the both methodsarea and volume is determined based on run time polymorphism of the current object as shown in the output.

Interface vs Abstract Class

Interface vs Abstract Class

Taken from http://interview-questions-java.com/abstract-class-interface.htm

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes.An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A JavaInterface can contain only method declarations and public static final constants and doesn’t contain theirimplementation. The classes which implement the Interface must provide the method definition for all the methodspresent.

2. Abstract class definition begins with the keyword “abstract” keyword followed by Class definition. An Interfacedefinition begins with the keyword “interface”.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 47: 108784097 Java Tutorial

3. Abstract classes are useful in a situation when some general methods should be implemented and specializationbehavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to beimplemented by subclasses

4. All variables in an Interface are by default – public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. Insuch situations its not possible to have multiple inheritance of classes. An interface on the other hand can be usedwhen it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereasan Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protectedmembers.

7. A class implementing an interface must implement all of the methods defined in the interface, while a classextending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUSTimplement those method in all of the classes which implement that interface. However, in the case of an abstract class,the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstractclasses are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. anAutomobile class mightimplement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are publicstatic final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a commonbase class. If all theyshare is a set of method signatures, then tend towards an interface.

Similarities:

Neither Abstract classes nor Interface can be instantiated.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 48: 108784097 Java Tutorial

Java Method Overriding

Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following whichthe new method implementation in the subclass that is executed.

The new method definition must have the same method signature (i.e., method name and parameters) and returntype. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass hasits method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The newmethod definition cannot narrow the accessibility of the method, but it can widen it. The new method definition canonly specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clauseof the overridden method in the super class

A program to explain the different concepts of Java Method Overridding

class CustomException extends Exception {

}

class SuperClassWithDifferentMethods {

protected int field1 = 10; protected static int field2 = 20; public void method1() { System.out.println("SuperClassWithDifferentMethods.method1()"); } public final void method2() { System.out.println("SuperClassWithDifferentMethods.method2()"); } private void method3() { System.out.println("SuperClassWithDifferentMethods.method3()"); } private final void method4() { System.out.println("SuperClassWithDifferentMethods.method4()"); } public static void method5() { System.out.println("SuperClassWithDifferentMethods.method5()"); } public void method6() throws Exception { System.out.println("SuperClassWithDifferentMethods.method6()"); } private void method7() { System.out.println("SuperClassWithDifferentMethods.method7()"); } private void method8(int x) { System.out.println("SuperClassWithDifferentMethods.method8()"); } public static void method9() { System.out.println("SuperClassWithDifferentMethods.method9()"); }}

class OverridingClass extends SuperClassWithDifferentMethods {

public int field1 = 30; public static int field2 = 40; public void method1() { System.out.println("OverridingClass.method1()"); } //We can't override a public final method /* public final void method2(){

System.out.println("OverridingClass.method2()");

}*/ private void method3() { System.out.println("OverridingClass.method3()"); } private final void method4() { System.out.println("OverridingClass.method4()"); } public static void method5() { System.out.println("OverridingClass.method5()"); } public void method6() throws CustomException { System.out.println("OverridingClass.method6()"); } public void method7() { System.out.println("OverridingClass.method7()"); } public void method8(final int x) { System.out.println("OverridingClass.method8()"); } //A static method cannot be overridden to be non-static instance method /*public void method9() {

System.out.println("OverridingClass.method9()");

}*/}

public class MethodOverridingDemo {

public static void main(String[] args) { OverridingClass oc1 = new OverridingClass(); SuperClassWithDifferentMethods sc3 = new OverridingClass(); oc1.method1(); oc1.method2(); // Since its private, the below 2 methods are not visible /* oc1.method3();

oc1.method4();*/ oc1.method5(); try { oc1.method6(); } catch (CustomException e) { e.printStackTrace(); } oc1.method7(); oc1.method8(100); System.out.println("oc1.field1 : " + oc1.field1); System.out.println("oc1.field2 : " + oc1.field2); System.out.println("sc3.field1 : " + sc3.field1);

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 49: 108784097 Java Tutorial

System.out.println("sc3.field2 : " + sc3.field2); sc3.method5(); OverridingClass overClass = new OverridingClass(); SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass; supClass.method5(); supClass.method1(); }}

Output

OverridingClass.method1()SuperClassWithDifferentMethods.method2()OverridingClass.method5()OverridingClass.method6()OverridingClass.method7()OverridingClass.method8()oc1.field1 : 30oc1.field2 : 40sc3.field1 : 10sc3.field2 : 20SuperClassWithDifferentMethods.method5()SuperClassWithDifferentMethods.method5()OverridingClass.method1()

Download MethodOverridingDemo.java

The new method definitions in the subclass OverridingClass have the same signature and the same return type as themethods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition specifies a subsetof the exceptions (CustomException). The new overridden method7 definition also widens the accessibility to publicfrom private. The overriding method8 also declares the parameter to be final, which is not a part of the methodsignature and Method Overriding holds good. A static method cannot be overridden to be non-static instance methodas shown in the overridden method declaration of method9. A static method is class-specific and not part of anyobject, while overriding methods are invoked on behalf of objects of the subclass. There are no such restrictions on thefields, as for fields only the field names matter. A final method cannot be overridden, an attempt to which will result ina compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a subclasscannot override it.

A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. A subclass cannotoverride fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to accessmembers, including hidden fields.

The following distinction between invoking instance methods on an object and accessing fields of an object must benoted. When an instance method is invoked on an object using a reference, it is the class of the current objectdenoted by the reference, not the type of the reference, that determines which method implementation will beexecuted. When a field of an object is accessed using a reference, it is the type of the reference, not the class of thecurrent object denoted by the reference, that determines which field will actually be accessed. This is demonstrated inthe above program

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 50: 108784097 Java Tutorial

Java toString Method

Implementing toString method in java is done by overriding the Object’s toString method. The java toString()method is used when we need a string representation of an object. It is defined in Object class. This method can beoverridden to customize the String representation of the Object. Below is a program showing the use of the Object’sDefault toString java method.

class PointCoordinates {

private int x, y; public PointCoordinates(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; }}

public class ToStringDemo {

public static void main(String args[]) { PointCoordinates point = new PointCoordinates(10, 10); // using the Default Object.toString() Method System.out.println("Object toString() method : " + point); // implicitly call toString() on object as part of string concatenation String s = point + " testing"; System.out.println(s); }}

Download ToStringDemo.java

When you run the ToStringDemo program, the output is:Object toString() method : PointCoordinates@119c082PointCoordinates@119c082 testing

In the above example when we try printing PointCoordinates object, it internally calls the Object’s toString() method aswe have not overridden the java toString() method. Since out example has no toString method, the default one inObject is used. The format of the default toString method of the Object is as shown below.

Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string.The default hashCode method in Object is typically implemented by converting the memory address of the object intoan integer.

Below is an example shown of the same program by Overriding the default Object toString() method. The toString()method must be descriptive and should generally cover all the contents of the object.

class PointCoordinates {

private int x, y; public PointCoordinates(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } // Custom toString() Method. public String toString() { return "X=" + x + " " + "Y=" + y; }}

public class ToStringDemo2 {

public static void main(String args[]) { PointCoordinates point = new PointCoordinates(10, 10); System.out.println(point); String s = point + " testing"; System.out.println(s); }}

Download ToStringDemo2.java

When you run the ToStringDemo2 program, the output is:

X=10 Y=10X=10 Y=10 testing

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 51: 108784097 Java Tutorial

Java String Class

Strings in javaJava String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the samereference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differsfrom other classes, one difference being that the String objects can be used with the += and + operators forconcatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whethertwo Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation

A simple String can be created using a string literal enclosed inside double quotes as shown;

String str1 = “My name is bob”;

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of astring literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference inmemory. Below illustrates this phenomenon.

String str1 = “My name is bob”;String str2 = “My name is bob”;String str3 = “My name ”+ “is bob”; //Compile time expressionString name = “bob”;String str4 = “My name is” + name;String str5 = new String(“My name is bob”);

In the above code all the String references str1, str2 and str3 denote the same String object, initialized with thecharacter string: “My name is bob”. But the Strings str4 and str5 denote new String objects.

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple wayto convert any primitive value to its string representation is by concatenating it with the empty string (“”), using thestring concatenation operator (+).

public class StringsDemo {

public static void main(String[] args) {

byte[] bytes = {2, 4, 6, 8};

char[] characters = {'a', 'b', 'C', 'D'};

StringBuffer strBuffer = new StringBuffer("abcde");

// Examples of Creation of Strings

String byteStr = new String(bytes);

String charStr = new String(characters);

String buffStr = new String(strBuffer);

System.out.println("byteStr : "+byteStr);

System.out.println("charStr : "+charStr);

System.out.println("buffStr : "+buffStr);

}

}

Download StringDemo1.java

Output

byteStr : charStr : abCDbuffStr : abcde

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 52: 108784097 Java Tutorial

String Equality

public class StringsDemo2 {

public static void main(String[] args) { String str1 = "My name is bob"; String str2 = "My name is bob"; String str3 = "My name " + "is bob"; //Compile time expression String name = "bob"; String str4 = "My name is " + name; String str5 = new String("My name is bob"); System.out.println("str1 == str2 : " + (str1 == str2)); System.out.println("str2 == str3 : " + (str2 == str3)); System.out.println("str3 == str1 : " + (str3 == str1)); System.out.println("str4 == str5 : " + (str4 == str5)); System.out.println("str1 == str4 : " + (str1 == str4)); System.out.println("str1 == str5 : " + (str1 == str5)); System.out.println("str1.equals(str2) : " + str1.equals(str2)); System.out.println("str2.equals(str3) : " + str2.equals(str3)); System.out.println("str3.equals(str1) : " + str3.equals(str1)); System.out.println("str4.equals(str5) : " + str4.equals(str5)); System.out.println("str1.equals(str4) : " + str1.equals(str4)); System.out.println("str1.equals(str5) : " + str1.equals(str5)); }}

Download StringDemo2.java

Output

str1 == str2 : truestr2 == str3 : truestr3 == str1 : truestr4 == str5 : falsestr1 == str4 : falsestr1 == str5 : falsestr1.equals(str2) : truestr2.equals(str3) : truestr3.equals(str1) : truestr4.equals(str5) : truestr1.equals(str4) : truestr1.equals(str5) : true

Java String Functions

The following program explains the usage of the some of the basic String methods like ;

1. compareTo(String anotherString)Compares two strings lexicographically.

2. charAt(int index)Returns the character at the specified index.

3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character array.

4. length()Returns the length of this string.

5. equals(Object anObject)Compares this string to the specified object.

6. equalsIgnoreCase(String anotherString)Compares this String to another String, ignoring case considerations.

7. toUpperCase()Converts all of the characters in this String to upper case using the rules of the default locale.

7. toLowerCase()Converts all of the characters in this String to upper case using the rules of the default locale.

9. concat(String str)Concatenates the specified string to the end of this string.

10. indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 53: 108784097 Java Tutorial

11. indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specifiedindex.

12. indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

13. indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

14. lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

15. lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching backward starting at thespecified index.

16. lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

17. lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at thespecified index.

18. substring(int beginIndex)

Returns a new string that is a substring of this string.

19. substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

20. replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

21. trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

22. toString()

This object (which is already a string!) is itself returned.

public class StringsDemo3 {

public static void main(String[] args) { String str1 = "My name is bob"; char str2[] = new char[str1.length()]; String str3 = "bob"; String str4 = "cob"; String str5 = "BoB"; String str6 = "bob"; System.out.println("Length of the String str1 : " + str1.length()); System.out.println("Character at position 3 is : " + str1.charAt(3)); str1.getChars(0, str1.length(), str2, 0); System.out.print("The String str2 is : "); for (int i = 0; i < str2.length; i++) { System.out.print(str2[i]); } System.out.println(); System.out.print("Comparision Test : "); if (str3.compareTo(str4) < 0) { System.out.print(str3 + " < " + str4); } else if (str3.compareTo(str4) > 0) { System.out.print(str3 + " > " + str4); } else { System.out.print(str3 + " equals " + str4); } System.out.println(); System.out.print("Equals Test"); System.out.println("str3.equalsIgnoreCase(5) : " + str3.equalsIgnoreCase(str5)); System.out.println("str3.equals(6) : " + str3.equals(str6)); System.out.println("str1.equals(3) : " + str1.equals(str3)); str5.toUpperCase(); //Strings are immutable System.out.println("str5 : " + str5); String temp = str5.toUpperCase(); System.out.println("str5 Uppercase: " + temp); temp = str1.toLowerCase();

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 54: 108784097 Java Tutorial

System.out.println("str1 Lowercase: " + str1); System.out.println("str1.concat(str4): " + str1.concat(str4)); String str7temp = " \t\n Now for some Search and Replace Examples "; String str7 = str7temp.trim(); System.out.println("str7 : " + str7); String newStr = str7.replace('s', 'T'); System.out.println("newStr : " + newStr); System.out.println("indexof Operations on Strings"); System.out.println("Index of p in " + str7 + " : " + str7.indexOf('p')); System.out.println("Index of for in " + str7 + " : " + str7.indexOf("for")); System.out.println("str7.indexOf(for, 30) : " + str7.indexOf("for", 30)); System.out.println("str7.indexOf('p', 30) : " + str7.indexOf('p', 30)); System.out.println("str7.lastIndexOf('p') : " + str7.lastIndexOf('p')); System.out.println("str7.lastIndexOf('p', 4) : " + str7.lastIndexOf('p', 4)); System.out.print("SubString Operations on Strings"); String str8 = "SubString Example"; String sub5 = str8.substring(5); // "ring Example" String sub3_6 = str8.substring(3, 6); // "Str" System.out.println("str8 : " + str8); System.out.println("str8.substring(5) : " + sub5); System.out.println("str8.substring(3,6) : " + sub3_6); }}

Download StringDemo3.java

Output

Length of the String str1 : 14Character at position 3 is : nThe String str2 is : My name is bobComparision Test : bob < cobEquals Teststr3.equalsIgnoreCase(5) : truestr3.equals(6) : truestr1.equals(3) : falsestr5 : BoBstr5 Uppercase: BOBstr1 Lowercase: My name is bobstr1.concat(str4): My name is bobcobstr7 : Now for some Search and Replace ExamplesnewStr : Now for Tome Search and Replace ExampleTIndexof Operations on StringsIndex of p in Now for some Search and Replace Examples : 26Index of for in Now for some Search and Replace Examples : 4str7.indexOf(for, 30) : -1str7.indexOf(‘p’, 30) : 36str7.lastIndexOf(‘p’) : 36str7.lastIndexOf(‘p’, 4) : -1SubString Operations on Stringsstr8 : SubString Examplestr8.substring(5) : ring Examplestr8.substring(3,6) : Str

Below is a program to check for Alpha Numeric character’s in the string.

public class TestAlphaNumericCharacters {

private void isAlphaNumeric(final String input) { boolean isCharFlag = false; boolean isNumberFlag = false; final char[] chars = input.toCharArray(); for (int x = 0; x < chars.length; x++) { char c = chars[x]; // lowercase && uppercase alphabet if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) { isCharFlag = true; continue; } if ((c >= '0') && (c <= '9')) { // numeric isNumberFlag = true; continue; } } System.out.println("characters are present:" + isCharFlag); System.out.println("Numbers are present :" + isNumberFlag); } public static void main(String[] args) { TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters(); tANC.isAlphaNumeric("beginn3ers"); }}

Download TestAlphaNumericCharacters.java

Output

characters are present:trueNumbers are present :true

Below is a java program to Reverse a string (Reverse by words / characters)

import java.util.*;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 55: 108784097 Java Tutorial

public class StringReverse {

public static void main(String[] args) { String input = "beginner java tutorial"; Stack stack = new Stack(); //A Stack is a Last In First Out Data Structure StringTokenizer stringTokenizer = new StringTokenizer(input); while (stringTokenizer.hasMoreTokens()) { stack.push(stringTokenizer.nextElement()); } System.out.println("Original String: " + input); System.out.print("Reversed String by Words: "); while (!stack.empty()) { System.out.print(stack.pop()); System.out.print(" "); } System.out.println(); System.out.print("Reversed String by characters: "); StringBuffer rev = new StringBuffer(input).reverse(); System.out.print(rev); }}

Download StringReverse.java

Output

Original String: beginner java tutorialReversed String by Words: tutorial java beginnerReversed String by characters: lairotut avaj rennigeb

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 56: 108784097 Java Tutorial

Java String Comparison

Java String compare to determine Equality

java string compare can be done in many ways as shown below. Depending on the type of java string compare youneed, each of them is used.

* == Operator* equals method* compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to thesame object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’operator does not compare the content of the text present in the String objects. It only compares the references the 2Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The stringsare equal” in the second case.

public class StringComparision1 {

public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob"); String name3 = "Bob"; // 1st case if (name1 == name2) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1 == name3) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } }}

Download StringComparision1.java

Comparing using the equals Method

The equals method is used when we need to compare the content of the text present in the String objects. Thismethod returns true when two String objects hold the same content (i.e. the same values). The following Programwould print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision2 {

public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob1"); String name3 = "Bob"; // 1st case if (name1.equals(name2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1.equals(name3)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } }}

Download StringComparision2.java

Comparing using the compareTo Method

The compareTo method is used when we need to determine the order of Strings lexicographically. It compares charvalues similar to the equals method. The compareTo method returns a negative integer if the first String objectprecedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if thefirst String object follows the second string. The following Program would print “name2 follows name1” In the first caseand “name1 follows name3” in the second case.

public class StringComparision3 {

public static void main(String[] args) { String name1 = "bob"; String name2 = new String("cob"); String name3 = "Bob"; // 1st case if (name1.compareTo(name2) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name2) < 0) { System.out.println("name2 follows name1"); } else {

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 57: 108784097 Java Tutorial

System.out.println("name1 follows name2"); } // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case if (name1.compareTo(name3) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name3) < 0) { System.out.println("name3 follows name1"); } else { System.out.println("name1 follows name3"); } }}

Download StringComparision3.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 58: 108784097 Java Tutorial

Java StringBuffer

StringBuffer ClassStringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character stringof a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modificationof character strings is involved (appending, inserting, deleting, modifying etc).

Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method fromthe Object class, contents of string buffers should be converted to String objects for string comparison.A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffermanipulations

Creation of StringBuffers

StringBuffer Constructors

public class StringBufferDemo {

public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bob"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf2 capacity : " + strBuf2.capacity()); System.out.println("strBuf3 capacity : " + strBuf3.capacity()); }}

Download StringBufferDemo.java

Output

strBuf1 : BobstrBuf2 capacity : 100strBuf3 capacity : 16

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity()Returns the current capacity of the String buffer.

2. length()Returns the length (character count) of this string buffer.

3. charAt(int index)The specified character of the sequence currently represented by the string buffer, as indicated by the index argument,is returned.

4. setCharAt(int index, char ch)The character at the specified index of this string buffer is set to ch

5. toString()Converts to a string representing the data in this string buffer

6. insert(int offset, char c)Inserts the string representation of the char argument into this string buffer.Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the applicationneed.

7. delete(int start, int end)Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str)Replaces the characters in a substring of this StringBuffer with characters in the specified String.

9. reverse()The character sequence contained in this string buffer is replaced by the reverse of the sequence.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 59: 108784097 Java Tutorial

10. append(String str)Appends the string to this string buffer.Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on theapplication need.

11. setLength(int newLength)Sets the length of this String buffer.

public class StringBufferFunctionsDemo {

public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bobby"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf1 capacity : " + strBuf1.capacity()); System.out.println("strBuf2 capacity : " + strBuf2.capacity()); System.out.println("strBuf3 capacity : " + strBuf3.capacity()); System.out.println("strBuf1 length : " + strBuf1.length()); System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2)); // A StringIndexOutOfBoundsException is thrown if the index is not valid. strBuf1.setCharAt(1, 't'); System.out.println("strBuf1 after setCharAt 1 to t is : " + strBuf1); System.out .println("strBuf1 toString() is : " + strBuf1.toString()); strBuf3.append("beginner-java-tutorial"); System.out.println("strBuf3 when appended with a String : " + strBuf3.toString()); strBuf3.insert(1, 'c'); System.out.println("strBuf3 when c is inserted at 1 : " + strBuf3.toString()); strBuf3.delete(1, 'c'); System.out.println("strBuf3 when c is deleted at 1 : " + strBuf3.toString()); strBuf3.reverse(); System.out.println("Reversed strBuf3 : " + strBuf3); strBuf2.setLength(5); strBuf2.append("jdbc-tutorial"); System.out.println("strBuf2 : " + strBuf2); // We can clear a StringBuffer using the following line strBuf2.setLength(0); System.out.println("strBuf2 when cleared using setLength(0): " + strBuf2); }}

Download StringBufferFunctionsDemo.java

Output

strBuf1 : BobbystrBuf1 capacity : 21strBuf2 capacity : 100strBuf3 capacity : 16strBuf1 length : 5strBuf1 charAt 2 : bstrBuf1 after setCharAt 1 to t is : BtbbystrBuf1 toString() is : BtbbystrBuf3 when appended with a String : beginner-java-tutorialstrBuf3 when c is inserted at 1 : bceginner-java-tutorialstrBuf3 when c is deleted at 1 : bReversed strBuf3 : bstrBuf2 :

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 60: 108784097 Java Tutorial

Understanding Java Exceptions

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime.They could be file not found exception, unable to get connection exception and so on. On such conditions java throwsan exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action.Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire groupof exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program arecaught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Javaexceptions are raised with the throw keyword and handled within a catch block.

A Program Showing How the JVM throws an Exception at runtime

public class DivideException {

public static void main(String[] args) { division(100,4); // Line 1 division(100,0); // Line 2 System.out.println("Exit main()."); }

public static void division(int totalSum, int totalNumber) { System.out.println("Computing Division."); int average = totalSum/totalNumber; System.out.println("Average : "+ average); }}

Download DivideException.java

An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegaloperation. The “Exit main()” message is never reached in the main method

Output

Computing Division.java.lang.ArithmeticException: / by zeroAverage : 25Computing Division.at DivideException.division(DivideException.java:11)at DivideException.main(DivideException.java:5)Exception in thread “main”

Exceptions in Java

Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message thatprovides more information of the exception occurred. All classes of throwables define a one-parameter constructor thattakes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method toprint the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description ofthe exception. For more information on what is printed when the following messages are invoked, please refer the javadocs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions duringexecution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 61: 108784097 Java Tutorial

Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds,NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of theException class. These are basically business logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are directsubclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. CheckedExceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When achecked exception occurs in a method, the method must either catch the exception and take the appropriate action, orpass the exception on to its caller

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also areunchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exceptionor declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown.Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should notattempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must becaught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {<code>} catch (<exception type1> <parameter1>) { // 0 or more<statements>}} finally { // finally block<statements>}

try BlockThe java code that you think may produce an exception is placed within a try block for asuitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for thematching catch block to handle the error. Again if the matching catch handler is not found executionproceeds with the finally block and the default exception handler throws an exception.. If an exception isgenerated within the try block, the remaining statements in the try block are not executed.

catch BlockExceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catchblock, normal execution continues and the finally block is executed(Though the catch block throws an exception).

finally BlockA finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block wasexecuted. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clockexecutes a control transfer statement such as a return or a break statement, then this controlstatement determines how the execution will proceed regardless of any return or control statement present in the tryor catch.

The following program illustrates the scenario.

try { <code>} catch (<exception type1> <parameter1>) { // 0 or more <statements>

}} finally { // finally block <statements>}

Download DivideException2.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 62: 108784097 Java Tutorial

Output

Computing Division.Exception : / by zeroFinally Block Executes. Exception Occurredresult : -1

Below is a program showing the Normal Execution of the Program.

Please note that no NullPointerException is generated as was expected by most people

public class DivideException2 {

public static void main(String[] args) { int result = division(100,0); // Line 2 System.out.println("result : "+result); }

public static int division(int totalSum, int totalNumber) { int quotient = -1; System.out.println("Computing Division."); try{ quotient = totalSum/totalNumber;

} catch(Exception e){ System.out.println("Exception : "+ e.getMessage()); } finally{ if(quotient != -1){ System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{ System.out.println("Finally Block Executes. Exception Occurred"); return quotient; }

} return quotient; }}

Output

null (And not NullPointerException)

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 63: 108784097 Java Tutorial

Rules for try, catch and finally Blocks1. For each try block there can be zero or more catch blocks, but only one finally block.

2. The catch blocks and finally block must always appear in conjunction with a try block.

3. A try block must be followed by either at least one catch block or one finally block.

4. The order exception handlers in the catch block must be from the most specific exception

Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be Anexception consists of a block of code called a try block, a block of code called a catch block, and the finally block. Let’sexamine each of these in detail.

public class DivideException1 {

public static void main(String[] args) { division(100,0); // Line 2 System.out.println("Main Program Terminating"); }

public static void division(int totalSum, int totalNumber) { int quotient = -1; System.out.println("Computing Division."); try{ quotient = totalSum/totalNumber; System.out.println("Result is : "+quotient); } catch(Exception e){ System.out.println("Exception : "+ e.getMessage()); } finally{ if(quotient != -1){ System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{ System.out.println("Finally Block Executes. Exception Occurred"); }

} }}

Download DivideException1.javaOutput

Output

Computing Division.Exception : / by zeroFinally Block Executes. Exception OccurredMain Program Terminating

As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and programexecution is transferred to the catch statement. Because the exception is thrown from the try block, the remainingstatements of the try blockare skipped. The finally block executes.

Defining new EXCEPTIONS!!We can have our own custom Exception handler to deal with special exception conditions instead of using existingexception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (makingit checked).The super() call can be used to set a detail message in the throwable. Below is an example that shows the use ofCustom exception’s along with how the throw and throws clause are used.

class BadTemperature extends Exception{ BadTemperature( String reason ){ super ( reason ); }}

class TooHot extends BadTemperature{

TooHot(){ super ("Default messaeg : Hot"); }

TooHot(String message){ super (message); }}

class TooCold extends BadTemperature{

TooCold(){ super ("Default messaeg : Cold"); }

TooCold(String message){ super (message); }}

class TempertureObject{

int temperature;

TempertureObject( int temp ) { temperature = temp; }

void test() throws TooHot, TooCold { if ( temperature < 70 ) throw new TooCold("Very Cold"); if ( temperature > 80 ) throw new TooHot("Very Hot"); }}

public class ExceptionExample1{

private static void temperatureReport( TempertureObject batch ){ try{ batch.test(); System.out.println( "Perfect Temperature" ); } catch ( BadTemperature bt ){ System.out.println( bt.getMessage( ) ); } }

public static void main( String[] args ){

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 64: 108784097 Java Tutorial

temperatureReport( new TempertureObject( 100 ) ); temperatureReport( new TempertureObject( 50 ) ); temperatureReport( new TempertureObject( 75 ) ); }}

Download ExceptionExample.javaOutput

Output

Very HotVery ColdPerfect Temperature

throw, throws statement

A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.

The general format of the throw statement is as follows:

throw <exception reference>;

The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed tothe constructor when the exception object is created.

throw new TemperatureException(“Too hot”);

A throws clause can be used in the method prototype.

Method() throws <ExceptionType1>,…, <ExceptionTypen> {

}

Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The exception typespecified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Alsoan overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catchblock that can handle the exception. Any associated finally block of a try block encountered along the search path isexecuted. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If ahandler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throwsand a throw statement.

public class DivideException3 {

public static void main(String[] args) { try{ int result = division(100,10); result = division(100,0); System.out.println("result : "+result); } catch(ArithmeticException e){ System.out.println("Exception : "+ e.getMessage()); } }

public static int division(int totalSum, int totalNumber) throws ArithmeticException { int quotient = -1; System.out.println("Computing Division."); try{ if(totalNumber == 0){ throw new ArithmeticException("Division attempt by 0"); } quotient = totalSum/totalNumber;

} finally{ if(quotient != -1){ System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{ System.out.println("Finally Block Executes. Exception Occurred"); }

} return quotient; }}

Download DivideException3.javaOutput

Output

Computing Division.Finally Block ExecutesResult : 10Computing Division.Finally Block Executes. Exception OccurredException : Division attempt by 0

Using break and return with Exceptions

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 65: 108784097 Java Tutorial

This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finallyblock is executed always except when the return statement is executed.

public class ExceptionExample6 {

public static void main(String[] args) {

int x = 10, y = 2; int counter = 0; boolean flag = true; while (flag) { start: try { if ( y > 1 ) break start; if ( y < 0 ) return; x = x / y; System.out.println ( "x : " + x + " y : "+y ); } catch ( Exception e ) { System.out.println ( e.getMessage() ); } finally { ++counter; System.out.println ( "Counter : " + counter ); } --y; } }}

Download ExceptionExample6.javaOutput

Output

Counter : 1x : 10 y : 1Counter : 2/ by zeroCounter : 3Counter : 4

Handling Multiple Exceptions

It should be known by now that we can have multiple catch blocks for a particular try block to handle many differentkind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks.

import java.io.DataInputStream;import java.io.IOException;

import javax.swing.JOptionPane;public class ExceptionExample7{ static int numerator, denominator;

public ExceptionExample7( int t, int b ){ numerator = t; denominator = b; }

public int divide( ) throws ArithmeticException{ return numerator/denominator; }

public static void main( String args[] ){

String num, denom;

num = JOptionPane.showInputDialog(null, "Enter the Numerator"); denom = JOptionPane.showInputDialog(null, "Enter the Denominator");

try{ numerator = Integer.parseInt( num ); denominator = Integer.parseInt( denom ); } catch ( NumberFormatException nfe ){ System.out.println( "One of the inputs is not an integer" ); return; } catch ( Exception e ){ System.out.println( "Exception: " + e.getMessage( ) ); return; }

ExceptionExample7 d = new ExceptionExample7( numerator, denominator ); try{ double result = d.divide( ); JOptionPane.showMessageDialog(null, "Result : " + result); } catch ( ArithmeticException ae ){ System.out.println( "You can't divide by zero" ); } finally{ System.out.println( "Finally Block is always Executed" ); } }}

Download ExceptionExample7.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 66: 108784097 Java Tutorial

Java Singleton Design Pattern

Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongsto the family of design patterns, that govern the instantiation process. This design pattern proposes that at any timethere can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (OtherClasses). A static modifier is applied to the instance method that returns the object as it then makes this method aclass level method that can be accessed without creating an object.

One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is anextensible, platform-independent help system that enables authors and developers to incorporate online help intoapplications.

Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class thatrequires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain asingle connection object which can be used throughout the application.

Implementing Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

public class SingletonObjectDemo {

// Note that the constructor is private private SingletonObjectDemo() { // Optional Code }}

Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo {

private static SingletonObject singletonObject; // Note that the constructor is private private SingletonObjectDemo() { // Optional Code } public static SingletonObjectDemo getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonObjectDemo(); } return singletonObject; }}

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time theobject is created inside this method as it is null. Subsequent calls to this method returns the same object created asthe object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence morethan one object being created. This could violate the design patter principle. In order to prevent the simultaneousinvocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to themethod declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done asshown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clonemethod which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {throw new CloneNotSupportedException();}

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 67: 108784097 Java Tutorial

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 stepsmentioned above.

class SingletonClass {

private static SingletonClass singletonObject; /** A private Constructor prevents any other class from instantiating. */ private SingletonClass() { // Optional Code } public static synchronized SingletonClass getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonClass(); } return singletonObject; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }}

public class SingletonObjectDemo {

public static void main(String args[]) { // SingletonClass obj = new SingletonClass();

//Compilation error not allowed SingletonClass obj = SingletonClass.getSingletonObject(); // Your Business Logic System.out.println("Singleton object obtained"); }}

Download SingletonObjectDemo.java

Another approach

We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can alsomake the singleton class final to avoid sub classing that may cause other problems.

public class SingletonClass {

private static SingletonClass ourInstance = new SingletonClass(); public static SingletonClass getInstance() { return singletonObj; } private SingletonClass() { }}

In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type atany given time. Depending on your implementation, your class and all of its data might be garbage collected. Hencewe must ensure that at any point there must be a live reference to the class when the application is running.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 68: 108784097 Java Tutorial

Java Threads Tutorial

Introduction to ThreadsMultithreading refers to two or more tasks executing concurrently within a single program. A thread is an independentpath of execution within a program. Many threads can run concurrently within a program. Every thread in Java iscreated and controlled by the java.lang.Thread class. A Java program can have many threads, and these threadscan run concurrently, either asynchronously or synchronously.

Multithreading has several advantages over Multiprocessing such as;

Threads are lightweight compared to processesThreads share the same address space and therefore can share both data and codeContext switching between threads is usually less expensive than between processesCost of thread intercommunication is relatively low that that of process intercommunicationThreads allow different tasks to be performed concurrently.

The following figure shows the methods that are members of the Object and Thread Class.

Thread Creation

There are two ways to create thread in java;

Implement the Runnable interface (java.lang.Runnable)By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface

The Runnable Interface Signature

public interface Runnable {

void run();

}

One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class.We need to override the run() method into our class which is the only method that needs to be implemented. Therun() method contains the logic of the thread.

The procedure for creating threads based on the Runnable interface is as follows:

1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. Anobject of this class is a Runnable object.

2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. TheThread object now has a Runnable object that implements the run() method.

3. The start() method is invoked on the Thread object created in the previous step. The start() method returnsimmediately after a thread has been spawned.

4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

Below is a program that illustrates instantiation and running of threads using the runnable interface instead ofextending the Thread class. To start the thread you need to invoke the start() method on your object.

class RunnableThread implements Runnable {

Thread runner; public RunnableThread() { } public RunnableThread(String threadName) { runner = new Thread(this, threadName); // (1) Create a new thread. System.out.println(runner.getName());

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 69: 108784097 Java Tutorial

runner.start(); // (2) Start the thread. } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread()); }}

public class RunnableExample {

public static void main(String[] args) { Thread thread1 = new Thread(new RunnableThread(), "thread1"); Thread thread2 = new Thread(new RunnableThread(), "thread2"); RunnableThread thread3 = new RunnableThread("thread3"); //Start the threads thread1.start(); thread2.start(); try { //delay for one second Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); }}

Output

thread3Thread[thread1,5,main]Thread[thread2,5,main]Thread[thread3,5,main]Thread[main,5,main]private

Download Runnable Thread Program Example

This approach of creating a thread by implementing the Runnable Interface must be used whenever the class beingused to instantiate the thread object is required to extend some other class.

Extending Thread Class

The procedure for creating threads based on extending the Thread is as follows:

1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed bythe thread.

2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super()call.

3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligiblefor running.

Below is a program that illustrates instantiation and running of threads by extending the Thread class instead ofimplementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

class XThread extends Thread {

XThread() { } XThread(String threadName) { super(threadName); // Initialize thread. System.out.println(this); start(); } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread().getName()); }}

public class ThreadExample {

public static void main(String[] args) { Thread thread1 = new Thread(new XThread(), "thread1"); Thread thread2 = new Thread(new XThread(), "thread2"); // The below 2 threads are assigned default names Thread thread3 = new XThread(); Thread thread4 = new XThread(); Thread thread5 = new XThread("thread5"); //Start the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); try { //The sleep() method is invoked on the main thread to cause a one second delay. Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); }}

Output

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 70: 108784097 Java Tutorial

Thread[thread5,5,main]thread1thread5thread2Thread-3Thread-2Thread[main,5,main]

Download Java Thread Program Example

When creating threads, there are two reasons why implementing the Runnable interface may be preferable toextending the Thread class:

Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementingthe Runnable interfacehas this option.A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread classwould be excessive.

An example of an anonymous class below shows how to create a thread and start it:

( new Thread() {

public void run() {

for(;;) System.out.println(“Stop the world!”);

}

}

).start();

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 71: 108784097 Java Tutorial

Thread Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by themultiple threads in such a manner that only one thread can access a particular resource at a time.

In non synchronized multithreaded application, it is possible for one thread to modify a shared object whileanother thread is in the process of using or updating the object’s value. Synchronization prevents such typeof data corruption which may otherwise lead to dirty reads and significant errors.Generally critical sections of the code are usually marked with synchronized keyword.

Examples of using Thread Synchronization is in “The Producer/Consumer Model”.

Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.A lock thus implements mutual exclusion.

The object lock mechanism enforces the following rules of synchronization:

A thread must acquire the object lock associated with a shared resource, before it can enter the sharedresource. The runtime system ensures that no other thread can enter a shared resource if another threadalready holds the object lock associated with the shared resource. If a thread cannot immediately acquirethe object lock, it is blocked, that is, it must wait for the lock to become available.When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain accessto the shared resource.

Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually alock on the java.lang.Class object associated with the class. Given a class A, the reference A.classdenotes this unique Class object. The class lock can be used in much the same way as an object lock toimplement mutual exclusion.

There can be 2 ways through which synchronized can be implemented in Java:

synchronized methodssynchronized blocks

Synchronized statements are same as synchronized methods. A synchronized statement can only beexecuted after a thread has acquired the lock on the object/class referenced in the synchronized statement.

Synchronized Methods

Synchronized methods are methods that are used to control access to an object. A thread only executes asynchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held byanother thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronizedmethod, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations wheremethods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This iscalled a race condition. It occurs when two or more threads simultaneously update the same value, and as aconsequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method ofan object, all other threads that wish to execute this synchronized method or any other synchronized method of theobject will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock andis executing a synchronized method of the object. Such a method can invoke other synchronized methods of the objectwithout being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.

Below is an example shows how synchronized methods and object locks are used to coordinate access to a commonobject by multiple threads. If the ‘synchronized’ keyword is removed, the message is displayed in random fashion.

public class SyncMethodsExample extends Thread {

static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com", "is", "the", "best" }; public SyncMethodsExample(String id) { super(id); } public static void main(String[] args) { SyncMethodsExample thread1 = new SyncMethodsExample("thread1: "); SyncMethodsExample thread2 = new SyncMethodsExample("thread2: "); thread1.start(); thread2.start(); boolean t1IsAlive = true;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 72: 108784097 Java Tutorial

boolean t2IsAlive = true; do { if (t1IsAlive && !thread1.isAlive()) { t1IsAlive = false; System.out.println("t1 is dead."); } if (t2IsAlive && !thread2.isAlive()) { t2IsAlive = false; System.out.println("t2 is dead."); } } while (t1IsAlive || t2IsAlive); } void randomWait() { try { Thread.currentThread().sleep((long) (3000 * Math.random())); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } public synchronized void run() { SynchronizedOutput.displayList(getName(), msg); }}

class SynchronizedOutput {

// if the 'synchronized' keyword is removed, the message // is displayed in random fashion public static synchronized void displayList(String name, String list[]) { for (int i = 0; i < list.length; i++) { SyncMethodsExample t = (SyncMethodsExample) Thread .currentThread(); t.randomWait(); System.out.println(name + list[i]); } }}

Output

thread1: Beginnerthread1: javathread1: tutorial,thread1: .,thread1: comthread1: isthread1: thethread1: bestt1 is dead.thread2: Beginnerthread2: javathread2: tutorial,thread2: .,thread2: comthread2: isthread2: thethread2: bestt2 is dead.

Download Synchronized Methods Thread Program Example

Class Locks

Synchronized BlocksStatic methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute astatic synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A threadacquires the class lock before it can proceed with the execution of any static synchronized method in the class,blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply tostatic, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class isindependent from the synchronization of instance methods on objects of the class. A subclass decides whether the newdefinition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allowsexecution of arbitrary code to be synchronized on the lock of an arbitrary object.The general form of the synchronized block is as follows:

synchronized (<object reference expression>) {<code block>}

A compile-time error occurs if the expression produces a value of any primitive type. If execution of the blockcompletes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statementswith identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, aNullPointerException is thrown.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 73: 108784097 Java Tutorial

The code block is usually related to the object on which the synchronization is being done. This is the case withsynchronized methods, where the execution of the method is synchronized on the lock of the current object:

public Object method() {synchronized (this) { // Synchronized block on current object// method block}}

Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be ableto execute the code block, or any other code requiring the same object lock, until the lock is relinquished. Thishappens when the execution of the code block completes normally or an uncaught exception is thrown.

Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of apart of a method, by using the this reference and putting the relevant part of the method in the synchronized block.The braces of the block cannot be left out, even if the code block has just one statement.

class SmartClient {BankAccount account;// …public void updateTransaction() {synchronized (account) { // (1) synchronized blockaccount.update(); // (2)}}}

In the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. Ifseveral threads were to concurrently execute the method updateTransaction() on an object of SmartClient, thestatement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount objectassociated with this particular instance of SmartClient.

Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associatedouter object, in order to ensure integrity of data in the latter. This is illustrated in the following code where thesynchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated withan object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can onlyaccess the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associatedouter object. If another thread has the lock of the associated outer object, the thread in the inner object has to waitfor the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However,synchronizing on an inner object and on its associated outer object are independent of each other, unless enforcedexplicitly, as in the following code:

class Outer { // (1) Top-level Classprivate double myPi; // (2)protected class Inner { // (3) Non-static member Classpublic void setPi() { // (4)synchronized(Outer.this) { // (5) Synchronized block on outer objectmyPi = Math.PI; // (6)}}}}

Below example shows how synchronized block and object locks are used to coordinate access to shared objects bymultiple threads.

public class SyncBlockExample extends Thread {

static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com", "is", "the", "best" }; public SyncBlockExample(String id) { super(id); } public static void main(String[] args) { SyncBlockExample thread1 = new SyncBlockExample("thread1: "); SyncBlockExample thread2 = new SyncBlockExample("thread2: "); thread1.start(); thread2.start(); boolean t1IsAlive = true; boolean t2IsAlive = true; do { if (t1IsAlive && !thread1.isAlive()) { t1IsAlive = false; System.out.println("t1 is dead."); } if (t2IsAlive && !thread2.isAlive()) { t2IsAlive = false; System.out.println("t2 is dead."); } } while (t1IsAlive || t2IsAlive); }

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 74: 108784097 Java Tutorial

void randomWait() { try { Thread.currentThread().sleep((long) (3000 * Math.random())); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } public void run() { synchronized (System.out) { for (int i = 0; i < msg.length; i++) { randomWait(); System.out.println(getName() + msg[i]); } } }}

Output

thread1: Beginnerthread1: javathread1: tutorial,thread1: .,thread1: comthread1: isthread1: thethread1: bestt1 is dead.thread2: Beginnerthread2: javathread2: tutorial,thread2: .,thread2: comthread2: isthread2: thethread2: bestt2 is dead.

Synchronized blocks can also be specified on a class lock:

synchronized (<class name>.class) { <code block> }

The block synchronizes on the lock of the object denoted by the reference <class name>.class. A static synchronizedmethodclassAction() in class A is equivalent to the following declaration:

static void classAction() {

synchronized (A.class) { // Synchronized block on class A

// …

}

}

In summary, a thread can hold a lock on an object

by executing a synchronized instance method of the objectby executing the body of a synchronized block that synchronizes on the objectby executing a synchronized static method of a class

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 75: 108784097 Java Tutorial

Thread StatesA Java thread is always in one of several states which could be running, sleeping, dead, etc.

A thread can be in any of the following states:

New Thread state (Ready-to-run state)Runnable state (Running state)Not Runnable stateDead state

New Thread

A thread is in this state when the instantiation of a Thread object creates a new thread but does notstart it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()methods when the thread is in this state. Calling any method besides start() or stop() causes anIllegalThreadStateException.

Runnable

When the start() method is invoked on a New Thread() it gets to the runnable state or running state bycalling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.

Not Runnable

A thread becomes Not Runnable when one of the following four events occurs:

When sleep() method is invoked and it sleeps for a specified amount of timeWhen suspend() method is invokedWhen the wait() method is invoked and the thread waits for notification of a free resource or waits forthe completion of another thread or waits to acquire a lock of an object.The thread is blocking on I/O and waits for its completion

Example: Thread.currentThread().sleep(1000);

Note: Thread.currentThread() may return an output like Thread[threadA,5,main]

The output shown in bold describes

the name of the thread,the priority of the thread, andthe name of the group to which it belongs.

Here, the run() method put itself to sleep for one second and becomes Not Runnable during that period.A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end ofthe period of time for sleep is over. Whether or not it will actually start running depends on its priority and theavailability of the CPU.

Hence I hereby list the scenarios below to describe how a thread switches form a non runnable to a runnable state:

If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must beinterrupted).If a thread has been suspended, then its resume() method must be invokedIf a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by callingeither notify() or notifyAll().If a thread is blocked on I/O, then the I/O must complete.

Dead State

A thread enters this state when the run() method has finished executing or when the stop() method is invoked.Once in this state, the thread cannot ever run again.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 76: 108784097 Java Tutorial

Thread PriorityIn Java we can specify the priority of each thread relative to other threads. Those threads having higherpriority get greater access to available resources then lower priority threads. A Java thread inherits its priorityfrom the thread that created it. Heavy reliance on thread priorities for the behavior of a program can make theprogram non portable across platforms, as thread scheduling is host platform–dependent.

You can modify a thread’s priority at any time after its creation using the setPriority() method and retrievethe thread priority value using getPriority() method.

The following static final integer constants are defined in the Thread class:

MIN_PRIORITY (0) Lowest PriorityNORM_PRIORITY (5) Default PriorityMAX_PRIORITY (10) Highest Priority

The priority of an individual thread can be set to any integer value between and including the above defined constants.

When two or more threads are ready to be executed and system resource becomes available to execute a thread, theruntime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.

“If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a >round-robin fashion. The chosen thread will run until one of the following conditions is true:

a higher priority thread becomes Runnable. (Pre-emptive scheduling)it yields, or its run() method exitson systems that support time-slicing, its time allotment has expired

Thread Scheduler

Schedulers in JVM implementations usually employ one of the two following strategies:

Preemptive scheduling

If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler willpreempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.

Time-Slicing or Round-Robin scheduling

A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to), after which it moves tothe Ready-to-run state (runnable) to await its turn to run again.

A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled isunpredictable across different platforms.

Yielding

A call to the static method yield(), defined in the Thread class, will cause the current thread in the Running state tomove to the Runnable state, thus relinquishing the CPU. The thread is then at the mercy of the thread scheduler as towhen it will run again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. Ifthere are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The yield()method gives other threads of the same priority a chance to run. If there are no equal priority threads in the“Runnable” state, then the yield is ignored.

Sleeping and Waking Up

The thread class contains a static method named sleep() that causes the currently running thread to pause itsexecution and transit to the Sleeping state. The method does not relinquish any lock that the thread might have. Thethread will sleep for at least the time specified in its argument, before entering the runnable state where it takes itsturn to run again. If a thread is interrupted while sleeping, it will throw an InterruptedException when it awakes andgets to execute. The Thread class has several overloaded versions of the sleep() method.

Waiting and Notifying

Waiting and notifying provide means of thread inter-communication that synchronizes on the same object. The threads

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 77: 108784097 Java Tutorial

execute wait() and notify() (or notifyAll()) methods on the shared object for this purpose. The notifyAll(), notify() andwait() are methods of the Object class. These methods can be invoked only from within a synchronized context(synchronized method or synchronized block), otherwise, the call will result in an IllegalMonitorStateException. ThenotifyAll() method wakes up all the threads waiting on the resource. In this situation, the awakened threads competefor the resource. One thread gets the resource and the others go back to waiting.

wait() method signatures

final void wait(long timeout) throws InterruptedExceptionfinal void wait(long timeout, int nanos) throws InterruptedExceptionfinal void wait() throws InterruptedException

The wait() call can specify the time the thread should wait before being timed out. An another thread can invoke aninterrupt() method on a waiting thread resulting in an InterruptedException. This is a checked exception and hence thecode with the wait() method must be enclosed within a try catch block.

notify() method signatures

final void notify()final void notifyAll()

A thread usually calls the wait() method on the object whose lock it holds because a condition for its continuedexecution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There itwaits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of theshared object by the thread allows other threads to run and execute synchronized code on the same object afteracquiring its lock.The wait() method causes the current thread to wait until another thread notifies it of a condition change.

A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these three incidents:

1. Another thread invokes the notify() method on the object of the waiting thread, and the waiting thread is selectedas the thread to be awakened.2. The waiting thread times out.3. Another thread interrupts the waiting thread.

Notify

Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object.A call to the notify() method has no consequences if there are no threads in the wait set of the object.The notifyAll() method wakes up all threads in the wait set of the shared object.

Below program shows three threads, manipulating the same stack. Two of them are pushing elements on the stack,while the third one is popping elements off the stack. This example illustrates how a thread waiting as a result ofcalling the wait() method on an object, is notified by another thread calling the notify() method on the same object

class StackClass {

private Object[] stackArray; private volatile int topOfStack; StackClass(int capacity) { stackArray = new Object[capacity]; topOfStack = -1; } public synchronized Object pop() { System.out.println(Thread.currentThread() + ": popping"); while (isEmpty()) { try { System.out.println(Thread.currentThread() + ": waiting to pop"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Object obj = stackArray[topOfStack]; stackArray[topOfStack--] = null; System.out.println(Thread.currentThread() + ": notifying after pop"); notify(); return obj; } public synchronized void push(Object element) { System.out.println(Thread.currentThread() + ": pushing"); while (isFull()) { try { System.out.println(Thread.currentThread() + ": waiting to push"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } stackArray[++topOfStack] = element; System.out.println(Thread.currentThread() + ": notifying after push"); notify(); } public boolean isFull() { return topOfStack >= stackArray.length - 1;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 78: 108784097 Java Tutorial

} public boolean isEmpty() { return topOfStack < 0; }}

abstract class StackUser extends Thread {

protected StackClass stack; StackUser(String threadName, StackClass stack) { super(threadName); this.stack = stack; System.out.println(this); setDaemon(true); start(); }}

class StackPopper extends StackUser { // Stack Popper

StackPopper(String threadName, StackClass stack) { super(threadName, stack); } public void run() { while (true) { stack.pop(); } }}

class StackPusher extends StackUser { // Stack Pusher

StackPusher(String threadName, StackClass stack) { super(threadName, stack); } public void run() { while (true) { stack.push(new Integer(1)); } }}

public class WaitAndNotifyExample {

public static void main(String[] args) { StackClass stack = new StackClass(5); new StackPusher("One", stack); new StackPusher("Two", stack); new StackPopper("Three", stack); System.out.println("Main Thread sleeping."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Exit from Main Thread."); }}

Download Wait Notify methods Thread Program Example

The field topOfStack in class StackClass is declared volatile, so that read and write operations on this variable willaccess the master value of this variable, and not any copies, during runtime.Since the threads manipulate the same stack object and the push() and pop() methods in the class StackClassaresynchronized, it means that the threads synchronize on the same object.

How the program uses wait() and notify() for inter thread communication.

(1) The synchronized pop() method – When a thread executing this method on the StackClass object finds that thestack is empty, it invokes the wait() method in order to wait for some other thread to fill the stack by using thesynchronized push. Once an other thread makes a push, it invokes the notify method.(2)The synchronized push() method – When a thread executing this method on the StackClass object finds that thestack is full, i t invokes the wait() method to await some other thread to remove an element to provide space for thenewly to be pushed element.Once an other thread makes a pop, it invokes the notify method.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 79: 108784097 Java Tutorial

JoiningA thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has alreadycompleted. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.

Below is a program showing how threads invoke the overloaded thread join method.

public class ThreadJoinDemo {

public static void main(String[] args) { Thread t1 = new Thread("T1"); Thread t2 = new Thread("T2"); try { System.out.println("Wait for the child threads to finish."); t1.join(); if (!t1.isAlive()) System.out.println("Thread T1 is not alive."); t2.join(); if (!t2.isAlive()) System.out.println("Thread T2 is not alive."); } catch (InterruptedException e) { System.out.println("Main Thread interrupted."); } System.out.println("Exit from Main Thread."); }}

Download Java Thread Join Method Program Example

Output

Wait for the child threads to finish.Thread T1 is not alive.Thread T2 is not alive.Exit from Main Thread.

Deadlock

There are situations when programs become deadlocked when each thread is waiting on a resource that cannotbecome available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked bythe other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waitingforever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.

Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. Itsynchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.

Below is a program that illustrates deadlocks in multithreading applications

public class DeadLockExample {

String o1 = "Lock "; String o2 = "Step "; Thread t1 = (new Thread("Printer1") {

public void run() { while (true) { synchronized (o1) { synchronized (o2) { System.out.println(o1 + o2); } } } } }); Thread t2 = (new Thread("Printer2") {

public void run() { while (true) { synchronized (o2) { synchronized (o1) { System.out.println(o2 + o1); } } } } }); public static void main(String[] args) { DeadLockExample dLock = new DeadLockExample(); dLock.t1.start(); dLock.t2.start(); }}

Download Java Thread deadlock Program Example

Note: The following methods namely join, sleep and wait name the InterruptedException in its throws clause andcan have a timeout argument as a parameter. The following methods namely wait, notify and notifyAll should onlybe called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start methodcauses a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares therun method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield methodwill not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 80: 108784097 Java Tutorial

inherits its daemon status from the thread that created it

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 81: 108784097 Java Tutorial

Java Collections Framework

A collection represents a group of objects, known as its elements. This framework is provided in the java.util package.Objects can be stored, retrieved, and manipulated as elements of collections. Collection is a Java Interface. Collectionscan be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically usedto group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Somecollections are ordered and others are not.

A Collections Framework mainly contains the following 3 parts

A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfacesand a set of standard utility methods and algorithms. In addition, the framework also provides several abstractimplementations, which are designed to make it easier for you to create new and different implementations forhandling collections of data.

Core Collection Interfaces

The core interfaces that define common functionality and allow collections to be manipulated independent of theirimplementation.The 6 core Interfaces used in the Collection framework are:

CollectionSetListIterator (Not a part of the Collections Framework)SortedSetMapSortedMap

Note: Collection and Map are the two top-level interfaces.

Collection Interface

Map Interface

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 82: 108784097 Java Tutorial

Concrete Classes

The concrete classes that are specific implementations of the core interfaces, providing data structures that a javaprogram can use.

Note: Concrete Classes for the Map is shown in the previous section.Standard utility methods and algorithms

Standard utility methods and algorithms

that can be used to perform various operations on collections, such as sorting, searching or creating customizedcollections.

How are Collections Used

The collections stores object references, rather than objects themselves. Hence primitive values cannot be storedin a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior to storing theminto a Collection (such as HashSet, HashMap etc).The references are always stored as type Object. Thus, when you retrieve an element from a collection, you getan Object rather then the actual type of the collection stored in the database. Hence we need to downcast it tothe Actual Type while retrieving an element from a collection.One of the capabilities of the Collection Framework is to create a new Collection object and populate it with thecontents of an existing Collection object of a same or different actual type.

Below is an example program showing the storing and retrieving of a few Collection Types

import java.util.*;

public class CollectionsDemo {

public static void main(String[] args) { List a1 = new ArrayList(); a1.add("Beginner"); a1.add("Java"); a1.add("tutorial");

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 83: 108784097 Java Tutorial

System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Beginner"); l1.add("Java"); l1.add("tutorial"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); Set s1 = new HashSet(); // or new TreeSet() will order the elements; s1.add("Beginner"); s1.add("Java"); s1.add("Java"); s1.add("tutorial"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); Map m1 = new HashMap(); // or new TreeMap() will order based on keys m1.put("Windows", "98"); m1.put("Win", "XP"); m1.put("Beginner", "Java"); m1.put("Tutorial", "Site"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); }}

Output

ArrayList Elements[Beginner, Java, tutorial]LinkedList Elements[Beginner, Java, tutorial]Set Elements[tutorial, Beginner, Java]Map Elements{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}

Download CollectionsDemo.java

Java Collections Source Code Examples

On the following pages in this tutorial I have described how elements can be manipulated by different collectionsnamely;

Java ArrayListJava LinkedListJava TreeSetJava HashMapJava VectorJava HashTableJava HashSet

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 84: 108784097 Java Tutorial

JavaLinked List

A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.A LinkedList is based on a double linked list where elements of the List are typically accessed through add() andremove() methods.

Below is an LinkedList Example showing how collections are manipulated using an LinkedList

import java.util.List;import java.util.LinkedList;import java.util.Iterator;import java.util.ListIterator;import java.util.Collections;import java.util.Random;

public class LinkedListExample {

public static void main(String[] args) { // LinkedList Creation List linkedListA = new LinkedList(); List linkedListB = new LinkedList(); // Adding elements to the LinkedList for (int i = 0; i < 5; i++) { linkedListA.add(new Integer(i)); } linkedListB.add("beginner"); linkedListB.add("java"); linkedListB.add("tutorial"); linkedListB.add("."); linkedListB.add("com"); linkedListB.add("java"); linkedListB.add("site"); // Iterating through the LinkedList to display the Contents. Iterator i1 = linkedListA.iterator(); System.out.print("LinkedList linkedListA --> "); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.print("LinkedList linkedListA --> "); for (int j = 0; j < linkedListA.size(); j++) { System.out.print(linkedListA.get(j) + " , "); } System.out.println(); Iterator i2 = linkedListB.iterator(); System.out.println("LinkedList linkedListB --> "); while (i2.hasNext()) { System.out.print(i2.next() + " , "); } System.out.println(); System.out.println(); System.out .println("Using ListIterator to retrieve LinkedList Elements"); System.out.println(); ListIterator li1 = linkedListA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("LinkedList linkedListA --> "); while (li1.hasNext()) { System.out.print(li1.next() + " , "); } System.out.println(); // Searching for an element in the LinkedList int index = linkedListB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = linkedListB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex + " from the last"); System.out.println(); // Getting the subList from the original List List subList = linkedListA.subList(3, linkedListA.size()); System.out.println("New Sub-List(linkedListA) from index 3 to " + linkedListA.size() + ": " + subList); System.out.println(); // Sort an LinkedList System.out.print("Sorted LinkedList linkedListA --> "); Collections.sort(linkedListA); System.out.print(linkedListA); System.out.println(); // Reversing an LinkedList System.out.print("Reversed LinkedList linkedListA --> "); Collections.reverse(linkedListA); System.out.println(linkedListA); System.out.println(); // Checking emptyness of an LinkedList System.out.println("Is linkedListA empty? " + linkedListA.isEmpty()); System.out.println(); // Checking for Equality of LinkedLists LinkedList LinkedListC = new LinkedList(linkedListA); System.out.println("linkedListA.equals(LinkedListC)? " + linkedListA.equals(LinkedListC)); System.out.println(); // Shuffling the elements of an LinkedList in Random Order Collections.shuffle(linkedListA, new Random()); System.out .print("LinkedList linkedListA after shuffling its elements--> "); i1 = linkedListA.iterator(); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.println(); // Converting an LinkedList to an Array Object[] array = linkedListA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing LinkedList Elements linkedListA.clear(); System.out.println("linkedListA after clearing : " + linkedListA); System.out.println(); }}

Output

LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,LinkedList linkedListB –>beginner , java , tutorial , . , com , java , site ,

Using ListIterator to retrieve LinkedList Elements

LinkedList linkedListA –>0 , 1 , 2 , 3 , 4 ,‘java’ was found at : 1‘java’ was found at : 5 from the last

New Sub-List(linkedListA) from index 3 to 5: [3, 4]

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 85: 108784097 Java Tutorial

Sorted LinkedList linkedListA –> [0, 1, 2, 3, 4]Reversed LinkedList linkedListA –> [4, 3, 2, 1, 0]

Is linkedListA empty? false

linkedListA.equals(LinkedListC)? true

LinkedList linkedListA after shuffling its elements–> 3 , 2 , 4 , 0 , 1 ,

Array Element [0] = 3Array Element [1] = 2Array Element [2] = 4Array Element [3] = 0Array Element [4] = 1

linkedListA after clearing : []

Download LinkedListExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 86: 108784097 Java Tutorial

Java TreeSet

public class TreeSet<E>extends AbstractSet<E>implements SortedSet<E>, Cloneable, Serializable

This class implements the Set interface and guarantees that the sorted set will be in ascending element order,sorted according to the natural order of the elements or by the comparator provided at set creation time,depending on which constructor is used.This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, removeand contains).

To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..));

Below is a TreeSet Example showing how collections are manipulated using a TreeSet

import java.util.Set;import java.util.TreeSet;import java.util.Iterator;

public class TreeSetExample {

public static void doTreeSetExample() { } public static void main(String[] args) { Set treeSet = new TreeSet(); // the treeset stores Integer objects into the TreeSet for (int i = 0; i < 5; i++) { treeSet.add(new Integer(i)); } // Since its a Integer Object Set adding any other elements in the Same // set will produce a // ClassCastException exception at runtime. // treeSet.add("a string"); System.out.print("The elements of the TreeSet are : "); Iterator i = treeSet.iterator(); while (i.hasNext()) { System.out.print(i.next() + "\t"); } }}

Output

The elements of the TreeSet are : 0 1 2 3 4

Download TreeSetExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 87: 108784097 Java Tutorial

Java HashMap

The java HashMap class does not guarantee that the order will remain constant over time.This implementation provides constant-time performance for the basic operations (get and put), assuming thehash function disperses the elements properly among the buckets.The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at leastone of the threads modifies the map structurally, it must be synchronized externally.

To prevent unsynchronized access to the Map: Map m = Collections.synchronizedMap(new HashMap(…));

Below is a HashMap Example used to store the number of words that begin with a given letter

/* * Using a HashMap to store the number of words that begin with a given letter. */

import java.util.HashMap;

public class HashMapExample {

static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" }; private static HashMap counter = new HashMap(); private static Integer cnt = null; public static void main(String args[]) { for (int i = 0; i < names.length; i++) { cnt = (Integer) (counter.get(new Character(names[i].charAt(0)))); if (cnt == null) { counter.put(new Character(names[i].charAt(0)),new Integer("1")); } else { counter.put(new Character(names[i].charAt(0)), new Integer(cnt.intValue() + 1)); } } System.out.println("\nnumber of words beginning with each letter is shown below "); System.out.println(counter.toString()); }}

Output

number of words beginning with each letter is shown below{s=3, b=1, k=1, h=2}

Download HashMapExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 88: 108784097 Java Tutorial

Java Vector

public class Vector<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, Serializable

The Vector class implements a growable array of objects where the size of the vector can grow or shrink asneeded dynamically.Like an array, it contains components that can be accessed using an integer index.An application can increase the capacity of a vector before inserting a large number of components; this reducesthe amount of incremental reallocation.

Below is a Vector Example showing how collections are manipulated using a Vector

import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.Enumeration;import java.util.NoSuchElementException;import java.util.Vector;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;

public class VectorDemo extends JFrame {

private JLabel jlbString = new JLabel("Enter a string"); public VectorDemo() { super("Vector class demo"); // Made final as it can be accessed by inner classes final JLabel jlbStatus = new JLabel(); Container contentPane = getContentPane(); final Vector vector = new Vector(1); contentPane.setLayout(new FlowLayout()); contentPane.add(jlbString); final JTextField jtfInput = new JTextField(10); contentPane.add(jtfInput); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { vector.addElement(jtfInput.getText().trim()); jlbStatus.setText("Appended to end: " + jtfInput.getText().trim()); jtfInput.setText(""); } }); contentPane.add(jbnAdd); JButton jbnRemove = new JButton("Remove"); jbnRemove.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { // Returns true if element in vector if (vector.removeElement(jtfInput.getText().trim())) jlbStatus.setText("Removed: " + jtfInput.getText()); else jlbStatus.setText(jtfInput.getText().trim() + " not in vector"); } }); contentPane.add(jbnRemove); JButton jbnFirst = new JButton("First"); jbnFirst.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("First element: " + vector.firstElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnFirst); JButton jbnLast = new JButton("Last"); jbnLast.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("Last element: " + vector.lastElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnLast); JButton jbnEmpty = new JButton("Is Empty?"); jbnEmpty.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jlbStatus.setText(vector.isEmpty() ? "Vector is empty" : "Vector is not empty"); } }); contentPane.add(jbnEmpty); JButton jbnContains = new JButton("Contains"); jbnContains.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { String searchKey = jtfInput.getText().trim(); if (vector.contains(searchKey)) { jlbStatus.setText("Vector contains " + searchKey); } else { jlbStatus.setText("Vector does not contain " + searchKey); }

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 89: 108784097 Java Tutorial

} }); contentPane.add(jbnContains); JButton jbnFindElement = new JButton("Find"); jbnFindElement.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jlbStatus.setText("Element found at location " + vector.indexOf(jtfInput.getText().trim())); } }); contentPane.add(jbnFindElement); JButton jbnTrim = new JButton("Trim"); jbnTrim.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { vector.trimToSize(); jlbStatus.setText("Vector trimmed to size"); } }); contentPane.add(jbnTrim); JButton jbnSize = new JButton("Size/Capacity"); jbnSize.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jlbStatus.setText("Size = " + vector.size() + "; Capacity = " + vector.capacity()); } }); contentPane.add(jbnSize); JButton jbnDisplay = new JButton("Display"); jbnDisplay.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { Enumeration enum1 = vector.elements(); StringBuffer buf = new StringBuffer(); while (enum1.hasMoreElements()) buf.append(enum1.nextElement()).append(" "); JOptionPane.showMessageDialog(null, buf.toString(), "Contents of Vector", JOptionPane.PLAIN_MESSAGE); } }); contentPane.add(jbnDisplay); contentPane.add(jlbStatus); setSize(300, 200); setVisible(true); } public static void main(String args[]) { VectorDemo vectorDemo = new VectorDemo(); vectorDemo.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); }}

Output

Download VectorExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 90: 108784097 Java Tutorial

Java HashTable

HashTable is synchronized.Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.Hashtable doesn’t allow nulls

Below is a HashTable Example showing how collections are manipulated using a HashTable

Please Note that It must be Compiled in Java 1.4.

// Demonstrates the Hashtable class of the java.util package.

public class HashTableDemo extends JFrame {

public HashTableDemo() { super(" Hashtable Sourcecode Example"); final JLabel jlbStatus = new JLabel(); final Hashtable hashTable = new Hashtable(); final JTextArea display = new JTextArea(4, 20); display.setEditable(false); JPanel jplNorth = new JPanel(); jplNorth.setLayout(new BorderLayout()); JPanel jplNorthSub = new JPanel(); jplNorthSub.add(new JLabel("Name (Key)")); final JTextField jtfFirstName = new JTextField(8); jplNorthSub.add(jtfFirstName); jplNorthSub.add(new JLabel("Phone No")); final JTextField jtfPhone = new JTextField(8); jplNorthSub.add(jtfPhone); jplNorth.add(jplNorthSub, BorderLayout.NORTH); jplNorth.add(jlbStatus, BorderLayout.SOUTH); JPanel jplSouth = new JPanel(); jplSouth.setLayout(new GridLayout(2, 5)); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { String strNum = jtfPhone.getText().trim(); String strName = jtfFirstName.getText().trim(); if ((strNum != null && strNum.equals("")) || (strName != null && strName.equals(""))) { JOptionPane.showMessageDialog(HashTableDemo.this, "Please enter both Name and Phone No"); return; } int num = 0; try { num = Integer.parseInt(strNum); } catch (NumberFormatException ne) { ne.printStackTrace(); } EmployeeDetails emp = new EmployeeDetails(strName, num); Object val = hashTable.put(strName, emp); if (val == null) jlbStatus.setText("Added: " + emp.toString()); else jlbStatus.setText("Added: " + emp.toString() + "; Replaced: " + val.toString()); } }); jplSouth.add(jbnAdd); JButton jbnGet = new JButton("Get"); jbnGet.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { Object val = hashTable.get(jtfFirstName.getText().trim()); if (val != null) jlbStatus.setText("Get: " + val.toString()); else jlbStatus.setText("Get: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnGet); JButton jbnRemove = new JButton("Remove Name"); jbnRemove.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { Object val = hashTable.remove(jtfFirstName.getText() .trim()); if (val != null) jlbStatus.setText("Remove: " + val.toString()); else jlbStatus.setText("Remove: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnRemove); JButton jbnIsEmpty = new JButton("Empty ?"); jbnIsEmpty.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jlbStatus.setText("Empty: " + hashTable.isEmpty()); } }); jplSouth.add(jbnIsEmpty); JButton jbnContains = new JButton("Contains key"); jbnContains.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jlbStatus.setText("Contains key: "+ hashTable.containsKey(jtfFirstName.getText().trim())); } }); jplSouth.add(jbnContains); JButton jbnClear = new JButton("Clear table"); jbnClear.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { hashTable.clear();

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 91: 108784097 Java Tutorial

jlbStatus.setText("HashTable Emptied"); } }); jplSouth.add(jbnClear); JButton jbnDisplay = new JButton("List objects"); jbnDisplay.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.elements(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); display.setText(buf.toString()); } }); jplSouth.add(jbnDisplay); JButton jbnKeys = new JButton("List keys"); jbnKeys.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.keys(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); JOptionPane.showMessageDialog(null, buf.toString(), "Display Keys of HashTable ",JOptionPane.PLAIN_MESSAGE); } }); jplSouth.add(jbnKeys); Container c = getContentPane(); c.add(jplNorth, BorderLayout.NORTH); c.add(new JScrollPane(display), BorderLayout.CENTER); c.add(jplSouth, BorderLayout.SOUTH); setSize(540, 300); setVisible(true); }

public static void main(String args[]) { HashTableDemo hashTableDemo = new HashTableDemo(); hashTableDemo.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); }}

class EmployeeDetails {

private String name; private int phoneNp; public EmployeeDetails(String fName, int phNo) { name = fName; phoneNp = phNo; } public String toString() { return name + " " + phoneNp; }}

Output

Download HashTableDemo.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 92: 108784097 Java Tutorial

Java HashSet

The HashSet class implements the Set interface.It makes no guarantee that the order of elements will remain constant over time.This class is not synchronized and permits a null element.This class offers constant time performance for the basic operations (add, remove, contains and size), assumingthe hash function disperses the elements properly among the buckets.To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…));

Below is a HashSet Example showing how collections are manipulated using a HashSet

import java.util.*;

public class HashSetExample {

private static String names[] = { "bob", "hemanth", "hhh", "hero", "shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike", "undertaker" }; public static void main(String args[]) { ArrayList aList; aList = new ArrayList(Arrays.asList(names)); System.out.println("The names elements " + aList); HashSet ref = new HashSet(aList); // create a HashSet Iterator i = ref.iterator(); System.out.println(); System.out.print("Unique names are: "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); }}

Output

The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker]

Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 93: 108784097 Java Tutorial

Java ArrayList

public class ArrayList<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, Serializable

Resizable-array implementation of the List interface. A java ArrayList is used to store an “ordered” group ofelements where duplicates are allowed.Implements all optional list operations, and permits all elements, including null.This class is similar to Vector, except that it is unsynchronized.The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList’s give greatperformance on get() and set() methods, but do not perform well on add() and remove() methods whencompared to a LinkedList.An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to anArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can beaccessed directly through get() method.

To prevent unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(…));

Below is an ArrayList Example showing how collections are manipulated using an ArrayList

import java.util.List;import java.util.ArrayList;import java.util.Iterator;import java.util.ListIterator;import java.util.Collections;import java.util.Random;

public class ArrayListExample {

public static void main(String[] args) { // ArrayList Creation List arraylistA = new ArrayList(); List arraylistB = new ArrayList(); // Adding elements to the ArrayList for (int i = 0; i < 5; i++) { arraylistA.add(new Integer(i)); } arraylistB.add("beginner"); arraylistB.add("java"); arraylistB.add("tutorial"); arraylistB.add("."); arraylistB.add("com"); arraylistB.add("java"); arraylistB.add("site"); // Iterating through the ArrayList to display the Contents. Iterator i1 = arraylistA.iterator(); System.out.print("ArrayList arraylistA --> "); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.print("ArrayList arraylistA --> "); for (int j = 0; j < arraylistA.size(); j++) { System.out.print(arraylistA.get(j) + " , "); } System.out.println(); Iterator i2 = arraylistB.iterator(); System.out.println("ArrayList arraylistB --> "); while (i2.hasNext()) { System.out.print(i2.next() + " , "); } System.out.println(); System.out.println(); System.out .println("Using ListIterator to retrieve ArrayList Elements"); System.out.println(); ListIterator li1 = arraylistA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("ArrayList arraylistA --> "); while (li1.hasNext()) { System.out.print(li1.next() + " , "); } System.out.println(); // Searching for an element in the ArrayList int index = arraylistB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = arraylistB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex + " from the last"); System.out.println(); // Getting the subList from the original List List subList = arraylistA.subList(3, arraylistA.size()); System.out.println("New Sub-List(arraylistA) from index 3 to " + arraylistA.size() + ": " + subList); System.out.println(); // Sort an ArrayList System.out.print("Sorted ArrayList arraylistA --> "); Collections.sort(arraylistA); System.out.print(arraylistA); System.out.println(); // Reversing an ArrayList System.out.print("Reversed ArrayList arraylistA --> "); Collections.reverse(arraylistA); System.out.println(arraylistA); System.out.println(); // Checking emptyness of an ArrayList System.out.println("Is arraylistA empty? " + arraylistA.isEmpty()); System.out.println(); // Checking for Equality of ArrayLists ArrayList arraylistC = new ArrayList(arraylistA); System.out.println("arraylistA.equals(arraylistC)? "

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 94: 108784097 Java Tutorial

+ arraylistA.equals(arraylistC)); System.out.println(); // Shuffling the elements of an ArrayList in Random Order Collections.shuffle(arraylistA, new Random()); System.out .print("ArrayList arraylistA after shuffling its elements--> "); i1 = arraylistA.iterator(); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.println(); // Converting an ArrayList to an Array Object[] array = arraylistA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing ArrayList Elements arraylistA.clear(); System.out.println("arraylistA after clearing : " + arraylistA); System.out.println(); }}

Output

ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,ArrayList arraylistB –>beginner , java , tutorial , . , com , java , site ,

Using ListIterator to retrieve ArrayList Elements

ArrayList arraylistA –>0 , 1 , 2 , 3 , 4 ,‘java’ was found at : 1‘java’ was found at : 5 from the last

New Sub-List(arraylistA) from index 3 to 5: [3, 4]

Sorted ArrayList arraylistA –> [0, 1, 2, 3, 4]Reversed ArrayList arraylistA –> [4, 3, 2, 1, 0]

Is arraylistA empty? false

arraylistA.equals(arraylistC)? true

ArrayList arraylistA after shuffling its elements–> 3 , 2 , 1 , 0 , 4 ,

Array Element [0] = 3Array Element [1] = 2Array Element [2] = 1Array Element [3] = 0Array Element [4] = 4

arraylistA after clearing : []

Download ArrayListExample.java

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 95: 108784097 Java Tutorial

Java Date Utility

Java Date APIjava.util.Class Date

java.lang.Objectextended by java.util.Date

All Implemented Interfaces:Cloneable, Comparable, Serializable

Direct Known Subclasses:Date, Time, Timestamp

public class Date extends Objectimplements Serializable, Cloneable, Comparable

The class Date represents a specific instant in time, with millisecond precision.

Java Date Source Codeimport java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;

public class DateUtility {

/* Add Day/Month/Year to a Date add() is used to add values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). */

public static final String DATE_FORMAT = "dd-MM-yyyy"; //See Java DOCS for different date formats // public static final String DATE_FORMAT = "yyyy-MM-dd";

public static void addToDate() { System.out.println("1. Add to a Date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); //Gets a calendar using the default time zone and locale. Calendar c1 = Calendar.getInstance(); Date d1 = new Date(); // System.out.println("Todays date in Calendar Format : "+c1); System.out.println("c1.getTime() : " + c1.getTime()); System.out.println("c1.get(Calendar.YEAR): "+ c1.get(Calendar.YEAR)); System.out.println("Todays date in Date Format : " + d1); c1.set(1999, 0, 20); //(year,month,date) System.out.println("c1.set(1999,0 ,20) : " + c1.getTime()); c1.add(Calendar.DATE, 20); System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); }

/*Substract Day/Month/Year to a Date

roll() is used to substract values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument. roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result. Hence add() is preferred even for subtraction by using a negative element.

*/

public static void subToDate() {

System.out.println("2. Subtract to a date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); // roll down, substract 1 month c1.roll(Calendar.MONTH, false); System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime())); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); c1.add(Calendar.MONTH, -1); // substract 1 month System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); }

public static void daysBetween2Dates() {

System.out.println("3. No of Days between 2 dates\n"); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); Calendar c2 = Calendar.getInstance(); //new GregorianCalendar(); c1.set(1999, 0, 20); c2.set(1999, 0, 22); System.out.println("Days Between " + c1.getTime() + " and "

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 96: 108784097 Java Tutorial

+ c2.getTime() + " is"); System.out.println((c2.getTime().getTime() - c1.getTime() .getTime()) / (24 * 3600 * 1000)); System.out.println(); System.out.println("-------------------------------------"); }

public static void daysInMonth() {

System.out.println("4. No of Days in a month for a given date\n"); Calendar c1 = Calendar.getInstance(); // new GregorianCalendar(); c1.set(1999, 6, 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); // int days = c1.get(Calendar.DATE); int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 }; daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0; System.out.println("Days in " + month + "th month for year" + year + "is " + daysInMonths[c1.get(Calendar.MONTH)]); System.out.println(); System.out.println("-------------------------------------"); }

public static void validateAGivenDate() {

System.out.println("5. Validate a given date\n"); String dt = "20011223"; String invalidDt = "20031315"; String dateformat = "yyyyMMdd"; Date dt1 = null, dt2 = null; try { SimpleDateFormat sdf = new SimpleDateFormat(dateformat); sdf.setLenient(false); dt1 = sdf.parse(dt); dt2 = sdf.parse(invalidDt); System.out.println("Date is ok = " + dt1 + "(" + dt + ")"); } catch (ParseException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("Invalid date"); } System.out.println(); System.out.println("-------------------------------------"); }

public static void compare2Dates() {

System.out.println("6. Comparision of 2 dates\n"); SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2000, 02, 15); c2.set(2001, 02, 15); System.out.print(fm.format(c1.getTime()) + " is "); if (c1.before(c2)) { System.out.println("less than " + fm.format(c2.getTime())); } else if (c1.after(c2)) { System.out.println("greater than " + fm.format(c2.getTime())); } else if (c1.equals(c2)) { System.out.println("is equal to " + fm.format(c2.getTime())); } System.out.println(); System.out.println("-------------------------------------"); }

public static void getDayofTheDate() {

System.out.println("7. Get the day for a given date\n"); Date d1 = new Date(); String day = null; DateFormat f = new SimpleDateFormat("EEEE"); try { day = f.format(d1); } catch (Exception e) { e.printStackTrace(); } System.out.println("The day for " + d1 + " is " + day); System.out.println(); System.out.println("-------------------------------------"); }

//Utility Method to find whether an Year is a Leap year or Not public static boolean isLeapYear(int year) {

if ((year % 100 != 0) || (year % 400 == 0)) { return true; } return false; }

public static void main(String args[]) { addToDate(); //Add day, month or year to a date field. subToDate(); //Subtract day, month or year to a date field. daysBetween2Dates(); //The "right" way would be to compute the Julian day number of //both dates and then do the subtraction. daysInMonth();//Find the number of days in a month for a date validateAGivenDate();//Check whether the date format is proper compare2Dates(); //Compare 2 dates getDayofTheDate(); }}

Output

1. Add to a Date Operation

c1.getTime() : Sat Mar 31 10:47:54 IST 2007c1.get(Calendar.YEAR): 2007Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999Date + 20 days is : 09-02-1999

——————————————————-2. Subtract to a date Operation

Date is : 20-01-1999

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 97: 108784097 Java Tutorial

Date roll down 1 month : 20-12-1999Date is : 20-01-1999Date minus 1 month : 20-12-1998

——————————————————-3. No of Days between 2 dates

Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is2

——————————————————-4. No of Days in a month for a given date

Days in 6th month for year 1999 is 31

——————————————————-5. Validate a given date

Unparseable date: “20031315″

——————————————————-6. Comparision of 2 dates

15-03-2000 is less than 15-03-2001

——————————————————-7. Get the day for a given date

The day for Sat Mar 31 10:47:54 IST 2007 is Saturday

——————————————————-

Download Date Utility Source Code

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 98: 108784097 Java Tutorial

Java Swing Tutorial

This site contains brief tutorials for java swing programming along with java swing examples and source code.

Java Swings Tutorial

What is Swings in java ?

A part of The JFCSwing Java consists ofLook and feelAccessibilityJava 2DDrag and Drop, etc

Compiling & running programs

‘javac <program.java>’ && ‘java <program>’Or JCreator / IDE

if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when thecontainer appears on the screen.

Swing, which is an extension library to the AWT, includes new and improved components that enhance the lookand functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets.It employs a model/view design architecture. Swing is more portable and more flexible than AWT.

Swing Model/view design: The “view part” of the MV design is implemented with a component object and the UIobject. The “model part” of the MV design is implemented by a model object and a change listener object.

Swing is built on top of AWT and is entirely written in Java, using AWT’s lightweight component support. In particular,unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior.Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs.For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program withstandard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listenerclasses without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.

100% Java implementation of componentsPluggable Look & FeelLightweight componentsUses MVC ArchitectureModel represents the dataView as a visual representation of the dataController takes input and translates it to changes in dataThree parts Component set (subclasses of JComponent)Support classesInterfaces

In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton,JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as inAWT.

Java Swing class hierarchy

The class JComponent, descended directly from Container, is the root class for most of Swing’s user interfacecomponents.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 99: 108784097 Java Tutorial

Swing contains components that you’ll use to build a GUI. I am listing you some of the commonly used Swingcomponents. To learn and understand these swing programs, AWT Programming knowledge is not required.

Java Swing Examples

Below is a java swing code for the traditional Hello World program.

Basically, the idea behind this Hello World program is to learn how to create a java program, compile and run it. Tocreate your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE likeEclipse.

import javax.swing.JFrame;import javax.swing.JLabel;

//import statements//Check if window closes automatically. Otherwise add suitable codepublic class HelloWorldFrame extends JFrame {

public static void main(String args[]) { new HelloWorldFrame(); } HelloWorldFrame() { JLabel jlbHelloWorld = new JLabel("Hello World"); add(jlbHelloWorld); this.setSize(100, 100); // pack(); setVisible(true); }}

Output

Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programmingswing.

JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel isdescended directly from JComponent.JFrame is Swing’s version of Frame and is descended directly from that class. The components added to theframe are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame,we must use its contentPane instead.JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized andlayered.JWindow is Swing’s version of Window and is descended directly from that class. Like Window, it usesBorderLayout by default.JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout bydefault. Like JFrame and JWindow,JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogsare modal, which means the currentthread is blocked until user interaction with it has been completed. JDialog class is intended as the basis forcreating custom dialogs; however, someof the most common dialogs are provided through static methods in the class JOptionPane.JLabel, descended from JComponent, is used to create text labels.The abstract class AbstractButton extends class JComponent and provides a foundation for a family of buttonclasses, including

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 100: 108784097 Java Tutorial

JButton.

JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, orcenter, and to set the text’s font.JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character enteredcan be replaced by an echo character.This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane toachieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical orhorizontal scrollbar;JButton is a component the user clicks to trigger a specific action.JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can beassociated as a group in which onlyone button at a time can be selected.JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it alsodisplays its current state.JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. Forexample, when the component has focus,pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbaris used for longer lists.JList provides a scrollable set of items from which one or more may be selected. JList can be populated from anArray or Vector. JList does notsupport scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-definedborder. JList actions are handled using ListSelectionListener.JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and animage.JToolbar contains a number of components whose type is usually some kind of button which can also includeseparators to group related componentswithin the toolbar.FlowLayout when used arranges swing components from left to right until there’s no more space available. Thenit begins a new row below it and movesfrom left to right again. Each component in a FlowLayout gets as much space as it needs and no more.BorderLayout places swing components in the North, South, East, West and center of a container. You can addhorizontal and vertical gaps betweenthe areas.GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container isdivided into equal-sized rectangles,and one component is placed in each rectangle.GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with eachcomponent occupying one or more cells,called its display area. The display area aligns components vertically and horizontally, without requiring that thecomponents be of the same size.JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ‘s that you canselect. Swing provides support forpull-down and popup menus.Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in apopup menu that exceeds the screen visible height.

Java Swing Projects

Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program sourcecode.Java Swing Address Book demonstrates how to create a simple free address book program using java swingand jdbc. Also you will learn to usethe following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 101: 108784097 Java Tutorial

Java JFrame class example

JFrameJava Swing Tutorial Explaining the JFrame class. The components added to the frame are referred to as its contents;these are managed by the contentPane. To add a component to a JFrame, we must use its contentPaneinstead.JFrame is a Window with border, title and buttons. When JFrame is set visible, an event dispatching thread isstarted. JFrame objects store several objects including a Container object known as the content pane. To add acomponent to a JFrame, add it to the content pane.

JFrame Features

It’s a window with title, border, (optional) menu bar and user-specified components.It can be moved, resized, iconified.It is not a subclass of JComponent.Delegates responsibility of managing user-specified components to a content pane, an instance of JPanel.

Centering JFrame’s

By default, a Jframe is displayed in the upper-left corner of the screen. To display a frameat a specified location, you can use the setLocation(x, y) method in the JFrame class. Thismethod places the upper-left corner of a frame at location (x, y).

The Swing API keeps improving with abstractions such as the setDefaultCloseOperation methodfor the JFrame

Crating a JFrame Window

Step 1: Construct an object of the JFrame class.

Step 2: Set the size of the Jframe.

Step 3: Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set).

Step 4: Set the default close operation. When the user clicks the close button, the program stops running.

Step 5: Make the Jframe visible.

How to position JFrame on Screen?

frame.setLocationRelativeTo( null );

JFrame Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JFrameDemo {

public static void main(String s[]) { JFrame frame = new JFrame("JFrame Source Demo"); // Add a window listner for close button frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); // This is an empty content area in the frame JLabel jlbempty = new JLabel(""); jlbempty.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(jlbempty, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

Output

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 102: 108784097 Java Tutorial

Download jFrame Source Code

Java JFrame Hierarchy

javax.swingClass JFramejava.lang.Objectjava.awt.Componentjava.awt.Containerjava.awt.Windowjava.awt.Framejavax.swing.JFrameAll Implemented Interfaces:Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants

JFrame Constructor

JFrame()Constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc)Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.

JFrame(String title)Creates a new, initially invisible Frame with the specified title.

JFrame(String title, GraphicsConfiguration gc)Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 103: 108784097 Java Tutorial

Java JInternalFrame class example

JInternalFrameJava Swing Tutorial Explaining the JInternalFrame class. A JInternalFrame is confined to a visible area of a container itis placed in. JInternalFrame a top level swing component that has a contentpane.

It can be iconified — in this case the icon remains in the main application container.It can be maximized — Frame consumes the main applicationIt can be closed using standard popup window controlsIt can be layered

JInternalFrame Source Codeimport javax.swing.JInternalFrame;import javax.swing.JDesktopPane;import javax.swing.JMenu;import javax.swing.JMenuItem;import javax.swing.JMenuBar;import javax.swing.JFrame;import java.awt.event.*;import java.awt.*;

public class JInternalFrameDemo extends JFrame {

JDesktopPane jdpDesktop; static int openFrameCount = 0; public JInternalFrameDemo() { super("JInternalFrame Usage Demo"); // Make the main window positioned as 50 pixels from each edge of the // screen. int inset = 50; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height - inset * 2); // Add a Window Exit Listener addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); // Create and Set up the GUI. jdpDesktop = new JDesktopPane(); // A specialized layered pane to be used with JInternalFrames createFrame(); // Create first window setContentPane(jdpDesktop); setJMenuBar(createMenuBar()); // Make dragging faster by setting drag mode to Outline jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline"); } protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Frame"); menu.setMnemonic(KeyEvent.VK_N); JMenuItem menuItem = new JMenuItem("New IFrame"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { createFrame(); } }); menu.add(menuItem); menuBar.add(menu); return menuBar; } protected void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); // Every JInternalFrame must be added to content pane using JDesktopPane jdpDesktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) { } } public static void main(String[] args) { JInternalFrameDemo frame = new JInternalFrameDemo(); frame.setVisible(true); } class MyInternalFrame extends JInternalFrame {

static final int xPosition = 30, yPosition = 30; public MyInternalFrame() { super("IFrame #" + (++openFrameCount), true, // resizable true, // closable true, // maximizable true);// iconifiable setSize(300, 300); // Set the window's location. setLocation(xPosition * openFrameCount, yPosition * openFrameCount); } }}

Output

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 104: 108784097 Java Tutorial

Download JInternalFrame Source Code

Java JInternalFrame Hierarchy

javax.swingClass JInternalFrame java.lang.Object|+–java.awt.Component|+–java.awt.Container|+–javax.swing.JComponent|+–javax.swing.JInternalFrameAll Implemented Interfaces: Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants

JInternalFrame Constructor

JInternalFrame()Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with no title.JInternalFrame(String title)Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title.

JInternalFrame(String title, boolean resizable)Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title and resizability.

JInternalFrame(String title, boolean resizable, boolean closable)Creates a non-maximizable, non-iconifiable JInternalFrame with the specified title, resizability, and closability.

JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable)Creates a non-iconifiable JInternalFrame with the specified title, resizability, closability, and maximizability.

JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable)Creates a JInternalFrame with the specified title, resizability, closability, maximizability

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 105: 108784097 Java Tutorial

Java JWindow class example

JWindowJava Swing Tutorial Explaining the JWindow Component. JWindow is Swing’s version of Window and is descendeddirectly from that class. Like Window, it uses BorderLayout by default. Almost all Swing components are lightweightexcept JApplet, JFrame, JDialog, and JWindow.

JWindow Source Codepublic class JWindowDemo extends JWindow {

private int X = 0; private int Y = 0; public JWindowDemo() { setBounds(60, 60, 100, 100); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); // An Exit Listener } }); // Print (X,Y) coordinates on Mouse Click addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) { X = e.getX(); Y = e.getY(); System.out.println("The (X,Y) coordinate of window is (" + X + "," + Y + ")"); } }); addMouseMotionListener(new MouseMotionAdapter() {

public void mouseDragged(MouseEvent e) { setLocation(getLocation().x + (e.getX() - X), getLocation().y + (e.getY() - Y)); } }); setVisible(true); } public static void main(String[] args) { new JWindowDemo(); }}

Output

Download JWindow Source Code

Java JWindow Hierarchy

javax.swingClass JWindow java.lang.Objectjava.awt.Componentjava.awt.Containerjava.awt.Window

All Implemented Interfaces:Accessible, ImageObserver, MenuContainer, SerializableDirect Known Subclasses: BasicToolBarUI.DragWindow, Dialog, Frame, JWindow

JWindow Constructor

Window(Frame owner)Constructs a new invisible window with the specified Frame as its owner.

Window(Window owner)Constructs a new invisible window with the specified Window as its owner.

Window(Window owner, GraphicsConfiguration gc)Constructs a new invisible window with the specified window as its owner and a GraphicsConfiguration of a screen

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 106: 108784097 Java Tutorial

device.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 107: 108784097 Java Tutorial

Java JLabel class example

JLabelsJava Swing Tutorial Explaining the JLabel Component. JLabel, descended from JComponent, is used tocreate text labels.A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image orboth text and image.We use a Swing JLabel when we need a user interface component that displays a message or an image.JØLabels

Provide text instructions on a GUIlRead-only textlPrograms rarely change a label’s contentslClass JLabel (subclass of JComponent)

JLabel Source Codeimport java.awt.GridLayout;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JFrame;import javax.swing.ImageIcon;

public class JlabelDemo extends JPanel {

JLabel jlbLabel1, jlbLabel2, jlbLabel3; public JlabelDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG", "My Website"); // Creating an Icon setLayout(new GridLayout(3, 1)); // 3 rows, 1 column Panel having Grid Layout jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER); // We can position of the text, relative to the icon: jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM); jlbLabel1.setHorizontalTextPosition(JLabel.CENTER); jlbLabel2 = new JLabel("Text Only Label"); jlbLabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlbLabel1); add(jlbLabel2); add(jlbLabel3); } public static void main(String[] args) { JFrame frame = new JFrame("jLabel Usage Demo"); frame.addWindowListener(new WindowAdapter() {

// Shows code to Add Window Listener public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JlabelDemo()); frame.pack(); frame.setVisible(true); }}

Output

Download jLabel Source Code

Java JLabel Hierarchy

javax.swingClass JLabeljava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JLabel

All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Serializable, SwingConstantsDirect Known Subclasses: BasicComboBoxRenderer, DefaultListCellRenderer, DefaultTableCellRenderer, DefaultTreeCellRenderer

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 108: 108784097 Java Tutorial

JLabel Constructor

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

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

JLabel(Icon image, int horizontalAlignment)Creates a JLabel instance with the specified image and horizontal alignment.

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

JLabel(String text, Icon icon, int horizontalAlignment)Creates a JLabel instance with the specified text, image, and horizontal alignment.

JLabel(String text, int horizontalAlignment)Creates a JLabel instance with the specified text and horizontal alignment.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 109: 108784097 Java Tutorial

Java JTextField class example

JTextFieldJava Swing Tutorial Explaining the JTextField Component. JTextField allows editing/displaying of a single line of text.New features include the ability to justify the text left, right, or center, and to set the text’s font. When the user typesdata into them and presses the Enter key, an action event occurs. If the program registers an event listener, thelistener processes the event and can use the data in the text field at the time of the event in the program. JTextField isan input area where the user can type in characters. If you want to let the user enter multiple lines of text, you cannotuse Jtextfield’s unless you create several of them. The solution is to use JTextArea, which enables the user to entermultiple lines of text.

JTextField Source Code// A program to demonstrate the use of JTextFields's//Import Statementsimport javax.swing.*;import java.awt.*;import java.awt.event.*;

public class JTextFieldDemo extends JFrame {

//Class Declarations JTextField jtfText1, jtfUneditableText; String disp = ""; TextHandler handler = null; //Constructor public JTextFieldDemo() { super("TextField Test Demo"); Container container = getContentPane(); container.setLayout(new FlowLayout()); jtfText1 = new JTextField(10); jtfUneditableText = new JTextField("Uneditable text field", 20); jtfUneditableText.setEditable(false); container.add(jtfText1); container.add(jtfUneditableText); handler = new TextHandler(); jtfText1.addActionListener(handler); jtfUneditableText.addActionListener(handler); setSize(325, 100); setVisible(true); } //Inner Class TextHandler private class TextHandler implements ActionListener {

public void actionPerformed(ActionEvent e) { if (e.getSource() == jtfText1) { disp = "text1 : " + e.getActionCommand(); } else if (e.getSource() == jtfUneditableText) { disp = "text3 : " + e.getActionCommand(); } JOptionPane.showMessageDialog(null, disp); } } //Main Program that starts Execution public static void main(String args[]) { JTextFieldDemo test = new JTextFieldDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}// End of class TextFieldTest

Output

Download jTextField Source Code

Another Example: JTextField Source Codepublic class JTextFieldDemo2 extends JFrame implements ActionListener {

JTextField jtfInput; JTextArea jtAreaOutput; String newline = "\n"; public JTextFieldDemo2() { createGui(); } public void createGui() { jtfInput = new JTextField(20); jtfInput.addActionListener(this); jtAreaOutput = new JTextArea(5, 20); jtAreaOutput.setEditable(false); JScrollPane scrollPane = new JScrollPane(jtAreaOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagLayout gridBag = new GridBagLayout(); Container contentPane = getContentPane(); contentPane.setLayout(gridBag); GridBagConstraints gridCons1 = new GridBagConstraints(); gridCons1.gridwidth = GridBagConstraints.REMAINDER; gridCons1.fill = GridBagConstraints.HORIZONTAL; contentPane.add(jtfInput, gridCons1); GridBagConstraints gridCons2 = new GridBagConstraints(); gridCons2.weightx = 1.0; gridCons2.weighty = 1.0;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 110: 108784097 Java Tutorial

contentPane.add(scrollPane, gridCons2); } public void actionPerformed(ActionEvent evt) { String text = jtfInput.getText(); jtAreaOutput.append(text + newline); jtfInput.selectAll(); } public static void main(String[] args) { JTextFieldDemo2 jtfTfDemo = new JTextFieldDemo2(); jtfTfDemo.pack(); jtfTfDemo.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfTfDemo.setVisible(true); }}

Output

Download jTextField Source Code

Java JTextField Hierarchy

javax.swingjava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.text.JTextComponentjavax.swing.JTextFieldAll Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable, SwingConstantsDirect Known Subclasses: DefaultTreeCellEditor.DefaultTextField, JFormattedTextField, JPasswordField

JTextField Constructor

JTextField()Constructs a new TextField.

JTextField(Document doc, String text, int columns)Constructs a new JTextField that uses the given text storage model and the given number of columns.

JTextField(int columns)Constructs a new empty TextField with the specified number of columns.

JTextField(String text)Constructs a new TextField initialized with the specified text.

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

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 111: 108784097 Java Tutorial

Java JPasswordField class example

JPasswordFieldJava Swing Tutorial Explaining the JPasswordField Component. JPasswordField (a direct subclass of JTextField) you cansuppress the display of input. Each character entered can be replaced by an echo character. This allows confidentialinput for passwords, for example. By default, the echo character is the asterisk, *. When the user types data into themand presses the Enter key, an action event occurs. If the program registers an event listener, the listener processes theevent and can use the data in the text field at the time of the event in the program. If you need to provide an editabletext field that doesn’t show the characters the user types – use the JPasswordField class.

JPasswordField Source Codepublic class JPasswordFieldDemo {

public static void main(String[] argv) { final JFrame frame = new JFrame("JPassword Usage Demo"); JLabel jlbPassword = new JLabel("Enter the password: "); JPasswordField jpwName = new JPasswordField(10); jpwName.setEchoChar('*'); jpwName.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { JPasswordField input = (JPasswordField) e.getSource(); char[] password = input.getPassword(); if (isPasswordCorrect(password)) { JOptionPane.showMessageDialog(frame, "Correct password."); } else { JOptionPane.showMessageDialog(frame, "Sorry. Try again.", "Error Message", JOptionPane.ERROR_MESSAGE); } } }); JPanel jplContentPane = new JPanel(new BorderLayout()); jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); jplContentPane.add(jlbPassword, BorderLayout.WEST); jplContentPane.add(jpwName, BorderLayout.CENTER); frame.setContentPane(jplContentPane); frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } private static boolean isPasswordCorrect(char[] inputPassword) { char[] actualPassword = { 'h', 'e', 'm', 'a', 'n', 't', 'h' }; if (inputPassword.length != actualPassword.length) return false; // Return false if lengths are unequal for (int i = 0; i < inputPassword.length; i++) if (inputPassword[i] != actualPassword[i]) return false; return true; }}

Output

Download JPasswordField Source Code

Java JPasswordField Hierarchy

javax.swingClass JPasswordFieldjava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.text.JTextComponentjavax.swing.JTextFieldjavax.swing.JPasswordFieldAll Implemented Interfaces:ImageObserver, MenuContainer, Serializable, Accessible, Scrollable, SwingConstants

JPasswordField Constructor

JPasswordField()Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.

JPasswordField(Document doc, String txt, int columns)Constructs a new JPasswordField that uses the given text storage model and the given number of columns.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 112: 108784097 Java Tutorial

JPasswordField(int columns)Constructs a new empty JPasswordField with the specified number of columns.

JPasswordField(String text)Constructs a new JPasswordField initialized with the specified text.

JPasswordField(String text, int columns)Constructs a new JPasswordField initialized with the specified text and columns.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 113: 108784097 Java Tutorial

Java JTextArea class example

JTextArea

Java Swing Tutorial Explaining the JTextArea Component. JTextArea allows editing of multiple lines of text. JTextAreacan be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced toalways or never have either the vertical or horizontal scrollbar.

JTextArea Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JTextAreaDemo extends JFrame implements ActionListener {

JTextField jtfInput; JTextArea jtAreaOutput; String newline = "\n"; public JTextAreaDemo() { createGui(); } public void createGui() { jtfInput = new JTextField(20); jtfInput.addActionListener(this); jtAreaOutput = new JTextArea(5, 20); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument() .getLength()); jtAreaOutput.setEditable(false); JScrollPane scrollPane = new JScrollPane(jtAreaOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagLayout gridBag = new GridBagLayout(); Container contentPane = getContentPane(); contentPane.setLayout(gridBag); GridBagConstraints gridCons1 = new GridBagConstraints(); gridCons1.gridwidth = GridBagConstraints.REMAINDER; gridCons1.fill = GridBagConstraints.HORIZONTAL; contentPane.add(jtfInput, gridCons1); GridBagConstraints gridCons2 = new GridBagConstraints(); gridCons2.weightx = 1.0; gridCons2.weighty = 1.0; contentPane.add(scrollPane, gridCons2); } public void actionPerformed(ActionEvent evt) { String text = jtfInput.getText(); jtAreaOutput.append(text + newline); jtfInput.selectAll(); } public static void main(String[] args) { JTextAreaDemo jtfTfDemo = new JTextAreaDemo(); jtfTfDemo.pack(); jtfTfDemo.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfTfDemo.setVisible(true); }}

Output

Download JTextArea Source Code

Java JTextArea Hierarchy

javax.swingClass JTextArea java.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.text.JTextComponentjavax.swing.JTextFieldAll Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable, SwingConstantsDirect Known Subclasses: DefaultTreeCellEditor.DefaultTextField, JFormattedTextField, JPasswordField

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 114: 108784097 Java Tutorial

JTextArea Constructor

JTextArea()Constructs a new TextArea.

JTextArea(Document doc)Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).

JTextArea(Document doc, String text, int rows, int columns)Constructs a new JTextArea with the specified number of rows and columns, and the given model.

JTextArea(int rows, int columns)Constructs a new empty TextArea with the specified number of rows and columns.

JTextArea(String text)Constructs a new TextArea with the specified text displayed.

JTextArea(String text, int rows, int columns)Constructs a new TextArea with the specified text and number of rows and columns.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 115: 108784097 Java Tutorial

Java JButton class example

JButtonJava Swing Tutorial Explaining the JButton Component. The abstract class AbstractButton extends class JComponentand provides a foundation for a family of button classes, including JButton. A button is a component the user clicks totrigger a specific action.

There are several types of buttons in Java, all are subclasses of AbstractButton.

command buttons: is created with class JButton. It generates ActionEvent.toggle buttons: have on/off or true/false values.check boxes: a group of buttons. It generates ItemEvent.radio buttons: a group of buttons in which only one can be selected. It generates ItemEvent.

JButton Source Codeimport java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.net.URL;import javax.swing.AbstractButton;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;

public class JButtonDemo extends JPanel implements ActionListener {

protected static JButton jbnLeft, jbnMiddle, jbnRight; public JButtonDemo() { // Create Icons that can be used with the jButtons ImageIcon leftButtonIcon = createImageIcon("rightarrow.JPG"); ImageIcon middleButtonIcon = createImageIcon("java-swing-tutorial.JPG"); ImageIcon rightButtonIcon = createImageIcon("leftarrow.JPG"); jbnLeft = new JButton("Disable centre button", leftButtonIcon); jbnLeft.setVerticalTextPosition(AbstractButton.CENTER); jbnLeft.setHorizontalTextPosition(AbstractButton.LEADING); jbnLeft.setMnemonic(KeyEvent.VK_D); // Alt-D clicks the button jbnLeft.setActionCommand("disable"); jbnLeft.setToolTipText("disable the Centre button."); // Adding Tool // tips jbnMiddle = new JButton("Centre button", middleButtonIcon); jbnMiddle.setVerticalTextPosition(AbstractButton.BOTTOM); jbnMiddle.setHorizontalTextPosition(AbstractButton.CENTER); jbnMiddle.setMnemonic(KeyEvent.VK_M); // Alt-M clicks the button jbnMiddle.setToolTipText("Centre button"); jbnRight = new JButton("Enable centre button", rightButtonIcon); // Use the default text position of CENTER, TRAILING (RIGHT). jbnRight.setMnemonic(KeyEvent.VK_E); // Alt-E clicks the button jbnRight.setActionCommand("enable"); jbnRight.setEnabled(false); // Disable the Button at creation time // Listen for actions on Left and Roght Buttons jbnLeft.addActionListener(this); jbnRight.addActionListener(this); jbnRight.setToolTipText("Enable the Centre button."); // Add Components to the frame, using the default FlowLayout. add(jbnLeft); add(jbnMiddle); add(jbnRight); } public void actionPerformed(ActionEvent e) { if ("disable".equals(e.getActionCommand())) { jbnMiddle.setEnabled(false); jbnLeft.setEnabled(false); jbnRight.setEnabled(true); } else { jbnMiddle.setEnabled(true); jbnLeft.setEnabled(true); jbnRight.setEnabled(false); } } // Returns an ImageIcon, or null if the path was invalid. protected static ImageIcon createImageIcon(String path) { URL imgURL = JButtonDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find image in system: " + path); return null; } } // Create the GUI and show it. private static void createGUI() { JFrame.setDefaultLookAndFeelDecorated(true); // Create and set up the frame. JFrame frame = new JFrame("jButton usage demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JButtonDemo buttonContentPane = new JButtonDemo(); buttonContentPane.setOpaque(true); // content panes must be opaque frame.getRootPane().setDefaultButton(jbnLeft); frame.setContentPane(buttonContentPane); // Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() { createGUI(); } }); }}

Output

Download jButton Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 116: 108784097 Java Tutorial

Another Example: JButton Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JButtonDemo2 {

JFrame jtfMainFrame; JButton jbnButton1, jbnButton2; JTextField jtfInput; JPanel jplPanel; public JButtonDemo2() { jtfMainFrame = new JFrame("Which Button Demo"); jtfMainFrame.setSize(50, 50); jbnButton1 = new JButton("Button 1"); jbnButton2 = new JButton("Button 2"); jtfInput = new JTextField(20); jplPanel = new JPanel(); jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys jbnButton1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 1!"); } }); jbnButton2.setMnemonic(KeyEvent.VK_I); jbnButton2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 2!"); } }); jplPanel.setLayout(new FlowLayout()); jplPanel.add(jtfInput); jplPanel.add(jbnButton1); jplPanel.add(jbnButton2); jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER); jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jtfMainFrame.pack(); jtfMainFrame.setVisible(true); } public static void main(String[] args) { // Set the look and feel to Java Swing Look try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } JButtonDemo2 application = new JButtonDemo2(); }}

Output

Download jButton Source Code

Java JButton Hierarchy

javax.swingClass JButton java.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.AbstractButtonjavax.swing.JButtonAll Implemented Interfaces: Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstantsDirect Known Subclasses:BasicArrowButton, MetalComboBoxButton

JButton Constructor

JButton()Creates a button with no set text or icon.

JButton(Action a)Creates a button where properties are taken from the Action supplied.

JButton(Icon icon)Creates a button with an icon.

JButton(String text)Creates a button with text.

JButton(String text, Icon icon)

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 117: 108784097 Java Tutorial

Creates a button with initial text and an icon.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 118: 108784097 Java Tutorial

Java JCheckBox class example

JCheckBox

Java Swing Tutorial Explaining the JCheckBox Component. JCheckBox is not a member of a checkbox group. Acheckbox can be selected and deselected, and it also displays its current state.

JCheckBox Source CodeNote: Help for getting the below source code is taken from Java Sun Website

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JCheckBoxDemo extends JPanel {

//Four accessory choices provide for 16 different combinations JCheckBox jcbChin; JCheckBox jcbGlasses; JCheckBox jcbHair; JCheckBox jcbTeeth;

/* The image for each combination is contained in a separate image file whose name indicates the accessories. The filenames are "geek-XXXX.gif" where XXXX can be one * of the following 16 choices. */

StringBuffer choices; JLabel jlbPicture; CheckBoxListener myListener = null;

public JCheckBoxDemo() {

// Add an item listener for each of the check boxes. // This is the listener class which contains business logic myListener = new CheckBoxListener();

// Create check boxes with default selection true

jcbChin = new JCheckBox("Chin"); jcbChin.setMnemonic(KeyEvent.VK_C);

//Alt+C Checks/Unchecks the check Box jcbChin.setSelected(true); jcbChin.addItemListener(myListener);

jcbGlasses = new JCheckBox("Glasses"); jcbGlasses.setMnemonic(KeyEvent.VK_G);

//Alt+G Checks/Unchecks the check Box jcbGlasses.setSelected(true); jcbGlasses.addItemListener(myListener);

jcbHair = new JCheckBox("Hair"); jcbHair.setMnemonic(KeyEvent.VK_H);

//Alt+H Checks/Unchecks the check Box jcbHair.setSelected(true); jcbHair.addItemListener(myListener);

jcbTeeth = new JCheckBox("Teeth"); jcbTeeth.setMnemonic(KeyEvent.VK_T);

//Alt+T Checks/Unchecks the check Box jcbTeeth.setSelected(true); jcbTeeth.addItemListener(myListener);

// Indicates what's on the geek. choices = new StringBuffer("cght");//Default Image has all the parts.

// Set up the picture label jlbPicture = new JLabel(new ImageIcon("geek-" + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString().trim());

// Put the check boxes in a column in a panel JPanel jplCheckBox = new JPanel(); jplCheckBox.setLayout(new GridLayout(0, 1)); //0 rows, 1 Column jplCheckBox.add(jcbChin); jplCheckBox.add(jcbGlasses); jplCheckBox.add(jcbHair); jplCheckBox.add(jcbTeeth);

setLayout(new BorderLayout()); add(jplCheckBox, BorderLayout.WEST); add(jlbPicture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); }

//Listens to the check boxes events class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getSource(); if (source == jcbChin) { index = 0; c = 'c'; } else if (source == jcbGlasses) { index = 1; c = 'g'; } else if (source == jcbHair) { index = 2; c = 'h'; } else if (source == jcbTeeth) { index = 3; c = 't'; }

if (e.getStateChange() == ItemEvent.DESELECTED) c = '-';

choices.setCharAt(index, c); jlbPicture.setIcon(new ImageIcon("geek-" + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString()); } }

public static void main(String s[]) { JFrame frame = new JFrame("JCheckBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });

frame.setContentPane(new JCheckBoxDemo()); frame.pack(); frame.setVisible(true); }

}

Output

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 119: 108784097 Java Tutorial

Download jCheckBox Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 120: 108784097 Java Tutorial

Java JComboBox class example

JComboBoxJava Swing Tutorial Explaining the JComboBox Component. JComboBox is like a drop down box — you can click adrop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component hasfocus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbaris used for longer lists.

JComboBox Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JComboBoxDemo extends JPanel {

JLabel jlbPicture; public JComboBoxDemo() { String[] comboTypes = { "Numbers", "Alphabets", "Symbols" }; // Create the combo box, and set 2nd item as Default JComboBox comboTypesList = new JComboBox(comboTypes); comboTypesList.setSelectedIndex(2); comboTypesList.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { JComboBox jcmbType = (JComboBox) e.getSource(); String cmbType = (String) jcmbType.getSelectedItem(); jlbPicture.setIcon(new ImageIcon("" + cmbType.trim().toLowerCase() + ".jpg")); } }); // Set up the picture jlbPicture = new JLabel(new ImageIcon("" + comboTypes[comboTypesList.getSelectedIndex()] + ".jpg")); jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); jlbPicture.setPreferredSize(new Dimension(177, 122 + 10)); // Layout the demo setLayout(new BorderLayout()); add(comboTypesList, BorderLayout.NORTH); add(jlbPicture, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); } public static void main(String s[]) { JFrame frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new JComboBoxDemo()); frame.pack(); frame.setVisible(true); }}

Output

Download JComboBox Source Code

Another Example: JComboBox Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import java.util.*;import java.text.*;

public class DateComboBoxDemo extends JPanel {

static JFrame frame; JLabel jlbResult; String datePattern_Current; public DateComboBoxDemo() { String[] datePatterns = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy", "yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy", "h:mm a", "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" }; datePattern_Current = datePatterns[0]; // Set up the UI for selecting a pattern.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 121: 108784097 Java Tutorial

JLabel jlbHeading = new JLabel( "Enter Date pattern /Select from list:"); JComboBox patternList = new JComboBox(datePatterns); patternList.setEditable(true); patternList.setAlignmentX(Component.LEFT_ALIGNMENT); patternList.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { JComboBox jcmbDates = (JComboBox) e.getSource(); String seletedDate = (String) jcmbDates.getSelectedItem(); datePattern_Current = seletedDate; showDateinLabel(); } }); // Create the UI for displaying result JLabel jlbResultHeading = new JLabel("Current Date/Time", JLabel.LEFT); jlbResult = new JLabel(" "); jlbResult.setForeground(Color.black); jlbResult.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.black), BorderFactory .createEmptyBorder(5, 5, 5, 5))); // Lay out everything JPanel jpnDate = new JPanel(); jpnDate.setLayout(new BoxLayout(jpnDate, BoxLayout.Y_AXIS)); jpnDate.add(jlbHeading); jpnDate.add(patternList); JPanel jpnResults = new JPanel(); jpnResults.setLayout(new GridLayout(0, 1)); jpnResults.add(jlbResultHeading); jpnResults.add(jlbResult); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); jpnDate.setAlignmentX(Component.LEFT_ALIGNMENT); jpnResults.setAlignmentX(Component.LEFT_ALIGNMENT); add(jpnDate); add(Box.createRigidArea(new Dimension(0, 10))); add(jpnResults); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); showDateinLabel(); } // constructor /** Formats and displays today's date. */ public void showDateinLabel() { Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat( datePattern_Current); try { String dateString = formatter.format(today); jlbResult.setForeground(Color.black); jlbResult.setText(dateString); } catch (IllegalArgumentException e) { jlbResult.setForeground(Color.red); jlbResult.setText("Error: " + e.getMessage()); } } public static void main(String s[]) { frame = new JFrame("JComboBox Usage Demo"); frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setContentPane(new DateComboBoxDemo()); frame.pack(); frame.setVisible(true); }}

Output

Download JComboBox Source Code

Java JComboBox Hierarchy

javax.swingClass JComboBox java.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JComboBoxAll Implemented Interfaces: Accessible, ActionListener, EventListener, ImageObserver, ItemSelectable, ListDataListener, MenuContainer, Serializable

JComboBox Constructor

JComboBox()Creates a JComboBox with a default data model.

JComboBox(ComboBoxModel aModel)Creates a JComboBox that takes it’s items from an existing ComboBoxModel.

JComboBox(Object[] items)Creates a JComboBox that contains the elements in the specified array.

JComboBox(Vector items)Creates a JComboBox that contains the elements in the specified Vector.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 122: 108784097 Java Tutorial

Editable JComboBox

Java Swing Tutorial Explaining the Editable JComboBox Component. JComboBox is like a drop down box —you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, whenthe component has focus, pressing a key that corresponds to the first character in some entry’s name selects thatentry. A vertical scrollbar is used for longer lists.

Editable JComboBox Source Code

Oct 30, 2006 by Hemanth

JComboBox’s getSelectedItem() is used to get what is entered into the control. However when a user types somethinginto the JCombBox rather than selecting an item from the list and does not hit “enter” after entering the text, thegetSelectedItem() does not return what is currently entered in the field (it instead gets the last selected item). Theusers often do not know to hit enter when they change the value in the JComboBox so they just click an “OK” buttonon the panel (signifying a save) and the value in the JComboBox is not properly saved. But the below programovercomes this probelm by simulating an enter key in the JComboBox or get the value that has been manually enteredwhen the user does not hot “enter” in the JComboBox.

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JComboBoxEditable extends JFrame{ JComboBox jcmbNames;

public JComboBoxEditable() { String[] names = { "hemanth", "Shawn", "Hunter", "Undertaker", "Big Show" };

jcmbNames = new JComboBox( names ); jcmbNames.setEditable( true ); getContentPane().add(jcmbNames, BorderLayout.NORTH);

JButton jbnOk = new JButton("Ok"); getContentPane().add(jbnOk, BorderLayout.SOUTH);

// Print Name of the Selected Combo Box Item to Console when OK button is pressed jbnOk.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println( jcmbNames.getSelectedItem() ); } });

// Print Name of the Selected Combo Box Item to Console when Enter is pressed

jcmbNames.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println( jcmbNames.getSelectedItem() ); } }); }

public static void main(String[] args) { JComboBoxEditable frame = new JComboBoxEditable(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible( true ); }}

Output

Download Editable JComboBox Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 123: 108784097 Java Tutorial

Java JList class example

JListJava Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which one or moremay be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, thelist must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border.JList actions are handled using ListSelectionListener.

JList Source Codeimport javax.swing.*;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import java.awt.*;import java.awt.event.*;

public class JListDemo extends JFrame {

JList list; String[] listColorNames = { "black", "blue", "green", "yellow", "white" }; Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.WHITE }; Container contentpane; public JListDemo() { super("List Source Demo"); contentpane = getContentPane(); contentpane.setLayout(new FlowLayout()); list = new JList(listColorNames); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentpane.add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() {

public void valueChanged(ListSelectionEvent e) { contentpane.setBackground(listColorValues[list .getSelectedIndex()]); } }); setSize(200, 200); setVisible(true); } public static void main(String[] args) { JListDemo test = new JListDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}

Output

Download JList Source Code

Java JList Class

javax.swing Class Class JListjava.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JListAll Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Scrollable, Serializable

JList Constructor

JList()Constructs a JList with an empty model.

JList(ListModel dataModel)Constructs a JList that displays the elements in the specified, non-null model.

JList(Object[] listData)Constructs a JList that displays the elements in the specified array.

JList(Vector listData)

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 124: 108784097 Java Tutorial

Constructs a JList that displays the elements in the specified Vector.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 125: 108784097 Java Tutorial

Java JTabbedPane class example

JTabbedPaneJava Swing Tutorial Explaining the JTabbedPane Component. A JTabbedPane contains a tab that can have a tool tipand a mnemonic, and it can display both text and an image.

The shape of a tab and the way in which the selected tab is displayed varies by Look and Feel.

JTabbedPane Source Codeimport javax.swing.JTabbedPane;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JFrame;import java.awt.*;import java.awt.event.*;

public class JTabbedPaneDemo extends JPanel {

public JTabbedPaneDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG"); JTabbedPane jtbExample = new JTabbedPane(); JPanel jplInnerPanel1 = createInnerPanel("Tab 1 Contains Tooltip and Icon"); jtbExample.addTab("One", icon, jplInnerPanel1, "Tab 1"); jtbExample.setSelectedIndex(0); JPanel jplInnerPanel2 = createInnerPanel("Tab 2 Contains Icon only"); jtbExample.addTab("Two", icon, jplInnerPanel2); JPanel jplInnerPanel3 = createInnerPanel("Tab 3 Contains Tooltip and Icon"); jtbExample.addTab("Three", icon, jplInnerPanel3, "Tab 3"); JPanel jplInnerPanel4 = createInnerPanel("Tab 4 Contains Text only"); jtbExample.addTab("Four", jplInnerPanel4); // Add the tabbed pane to this panel. setLayout(new GridLayout(1, 1)); add(jtbExample); } protected JPanel createInnerPanel(String text) { JPanel jplPanel = new JPanel(); JLabel jlbDisplay = new JLabel(text); jlbDisplay.setHorizontalAlignment(JLabel.CENTER); jplPanel.setLayout(new GridLayout(1, 1)); jplPanel.add(jlbDisplay); return jplPanel; } public static void main(String[] args) { JFrame frame = new JFrame("TabbedPane Source Demo"); frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add(new JTabbedPaneDemo(), BorderLayout.CENTER); frame.setSize(400, 125); frame.setVisible(true); }}

Output

Download JTabbedPane Source Code

JTabbedPane question

When I use a JTabbedPane and want to listen to which tab is being clicked, which listerner should I use?

Answer: ChangeListener

Java JTabbedPane Hierarchy

javax.swingClass JTabbedPane java.lang.Objectjava.awt.Componentjava.awt.Containerjavax.swing.JComponentjavax.swing.JTabbedPane

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 126: 108784097 Java Tutorial

All Implemented Interfaces: Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants

JTabbedPane Constructor

JTabbedPane()Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP.

JTabbedPane(int tabPlacement)Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM,JTabbedPane.LEFT, or JTabbedPane.RIGHT.

JTabbedPane(int tabPlacement, int tabLayoutPolicy)Creates an empty TabbedPane with the specified tab placement and tab layout policy.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 127: 108784097 Java Tutorial

Java JToolBar class example

JToolbarJava Swing Tutorial Explaining the JToolBar Component. A JToolbar contains a number of components whose type isusually some kind of button which can also include separators to group related components within the toolbar. Thetoolbar can be docked against any of the four edges of a container (panel or a frame). A toolbar can also be made tofloat.

Toolbars uses BoxLayout, which arranges components in one horizontal row/ vertical column. This layout managerdoes not force each component to have the same height or width; instead, it uses their preferred height or width, andattempts to align them.You can adjust the resulting alignment by calling class Component’s methods setAlignmentX() and/or setAlignmentY()on each component.

JToolbar Source Codeimport javax.swing.JToolBar;import javax.swing.JButton;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JTextArea;import javax.swing.JScrollPane;import javax.swing.JPanel;import javax.swing.JTextField;import java.awt.*;import java.awt.event.*;

public class JToolBarDemo extends JFrame {

protected JTextArea textArea; protected String newline = "\n"; public JToolBarDemo() { super("ToolBarDemo"); // Create the toolbar. JToolBar jtbMainToolbar = new JToolBar(); // setFloatable(false) to make the toolbar non movable addButtons(jtbMainToolbar); // Create the text area textArea = new JTextArea(5, 30); JScrollPane jsPane = new JScrollPane(textArea); // Lay out the content pane. JPanel jplContentPane = new JPanel(); jplContentPane.setLayout(new BorderLayout()); jplContentPane.setPreferredSize(new Dimension(400, 100)); jplContentPane.add(jtbMainToolbar, BorderLayout.NORTH); jplContentPane.add(jsPane, BorderLayout.CENTER); setContentPane(jplContentPane); } public void addButtons(JToolBar jtbToolBar) { JButton jbnToolbarButtons = null; // first button jbnToolbarButtons = new JButton(new ImageIcon("left.gif")); jbnToolbarButtons.setToolTipText("left"); jbnToolbarButtons.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("This is Left Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // 2nd button jbnToolbarButtons = new JButton(new ImageIcon("right.gif")); jbnToolbarButtons.setToolTipText("right"); jbnToolbarButtons.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("This is right Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); jtbToolBar.addSeparator(); // 3rd button jbnToolbarButtons = new JButton(new ImageIcon("open.gif")); jbnToolbarButtons.setToolTipText("open"); jbnToolbarButtons.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("This is open Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // 4th button jbnToolbarButtons = new JButton(new ImageIcon("save.gif")); jbnToolbarButtons.setToolTipText("save"); jbnToolbarButtons.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("This is save Toolbar Button Reporting"); } }); jtbToolBar.add(jbnToolbarButtons); // We can add separators to group similar components jtbToolBar.addSeparator(); // fourth button jbnToolbarButtons = new JButton("Text button"); jbnToolbarButtons.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("Text button"); } }); jtbToolBar.add(jbnToolbarButtons); // fifth component is NOT a button! JTextField jtfButton = new JTextField("Text field");

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 128: 108784097 Java Tutorial

jtfButton.setEditable(false); jtfButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { displayInTextArea("TextField component can also be placed"); } }); jtbToolBar.add(jtfButton); } protected void displayInTextArea(String actionDescription) { textArea.append(actionDescription + newline); } public static void main(String[] args) { JToolBarDemo jtfToolbar = new JToolBarDemo(); // Extends Frame. jtfToolbar.pack(); jtfToolbar.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfToolbar.setVisible(true); }}

Output

Download JToolbar Source Code

Java JToolBar Hierarchy

javax.swingClass JToolBar java.lang.Objectjava.awt.BorderLayoutAll Implemented Interfaces: LayoutManager, LayoutManager2, Serializable

JToolBar Constructor

JToolBar()Creates a new tool bar; orientation defaults to HORIZONTAL.

JToolBar(int orientation)Creates a new tool bar with the specified orientation.

JToolBar(String name)Creates a new tool bar with the specified name.

JToolBar(String name, int orientation)Creates a new tool bar with a specified name and orientation.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 129: 108784097 Java Tutorial

Java FlowLayout class example

FlowLayoutJava Swing Tutorial Explaining the FlowLayout. FlowLayout when used arranges swing components from left to rightuntil there’s no more space available. Then it begins a new row below it and moves from left to right again. Eachcomponent in a FlowLayout gets as much space as it needs and no more.

FlowLayout Source Codeimport java.awt.ComponentOrientation;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;

import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;

public class FlowLayoutDemo { public static boolean RIGHT_TO_LEFT = false;

public static void addComponents(Container contentPane) { if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); } contentPane.setLayout(new FlowLayout());

contentPane.add(new JLabel("JLabel 1")); contentPane.add(new JButton("JButton 2")); contentPane.add(new JCheckBox("JCheckBox 3")); contentPane.add(new JTextField("Long-Named JTextField 4")); contentPane.add(new JButton("JButton 5")); }

private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("FlowLayout Source Demo") { public Dimension getMinimumSize() { Dimension prefSize = getPreferredSize(); return new Dimension(100, prefSize.height); } }; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane and components in FlowLayout addComponents(frame.getContentPane());

frame.pack(); frame.setVisible(true); }

public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}

Output

Download FlowLayout Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 130: 108784097 Java Tutorial

Java BorderLayout class example

BorderLayoutJava Swing Tutorial Explaining the BorderLayout . BorderLayout places swing components in the North, South, East,West and center of a container. All extra space is placed in the center area. You can add horizontal and vertical gapsbetween the areas.

Every content pane is initialized to use a BorderLayout. Components are added to a BorderLayout by using the addmethod. JFrame’s content pane default layout manager: BorderLayout. In BorderLayout, a component’s position isspecified by a second argument to add.

BorderLayout Source Code/* * BorderLayoutDemo.java is a 1.4 application that requires no other files. */

import java.awt.BorderLayout;import java.awt.Container;import java.awt.Dimension;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;

public class BorderLayoutDemo { public static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container contentPane) {// Use BorderLayout. Default empty constructor with no horizontal and vertical// gaps contentPane.setLayout(new BorderLayout(5,5)); if (!(contentPane.getLayout() instanceof BorderLayout)) { contentPane.add(new JLabel("Container doesn't use BorderLayout!")); return; }

if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT); }

JButton jbnSampleButtons = new JButton("Button 1 (PAGE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START);

jbnSampleButtons = new JButton("Button 2 (CENTER)"); jbnSampleButtons.setPreferredSize(new Dimension(200, 100)); contentPane.add(jbnSampleButtons, BorderLayout.CENTER);

jbnSampleButtons = new JButton("Button 3 (LINE_START)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_START);

jbnSampleButtons = new JButton("Long-Named Button 4 (PAGE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END);

jbnSampleButtons = new JButton("5 (LINE_END)"); contentPane.add(jbnSampleButtons, BorderLayout.LINE_END); }

private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("BorderLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane and add swing components to it addComponentsToPane(frame.getContentPane());

frame.pack(); frame.setVisible(true); }

public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}

output

Download BorderLayout Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 131: 108784097 Java Tutorial

Java GridLayout class example

GridLayoutJava Swing Tutorial Explaining the GridLayout. GridLayout is a layout manager that lays out a container’s componentsin a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in eachrectangle.

GridLayout Source Codeimport java.awt.*;import javax.swing.*;

public class GridLayoutDemo { public final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container contentPane) { if (RIGHT_TO_LEFT) { contentPane.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); }// Any number of rows and 2 columns contentPane.setLayout(new GridLayout(0,2));

contentPane.add(new JLabel("JLabel 1")); contentPane.add(new JButton("JButton 2")); contentPane.add(new JCheckBox("JCheckBox 3")); contentPane.add(new JTextField("Long-Named JTextField 4")); contentPane.add(new JButton("JButton 5")); }

private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("GridLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane and components in GridLayout addComponentsToPane(frame.getContentPane());

frame.pack(); frame.setVisible(true); }

public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}

Output

Download GridLayout Source Code

Java GridLayout Hierarchy

javax.swingClass GridLayoutjava.lang.Objectjava.awt.GridLayoutAll Implemented Interfaces: LayoutManager, Serializable

GridLayout Constructor

GridLayout()Creates a grid layout with a default of one column per component, in a single row.

GridLayout(int rows, int cols)Creates a grid layout with the specified number of rows and columns.

GridLayout(int rows, int cols, int hgap, int vgap)Creates a grid layout with the specified number of rows and columns.

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 132: 108784097 Java Tutorial

Java GridBagLayout class example

GridBagLayoutJava Swing Tutorial Explaining the GridBagLayout. GridBagLayout is a layout manager that lays out a container’scomponents in a gridof cells with each component occupying one or more cells, called its display area. The display area aligns componentsvertically andhorizontally, without requiring that the components be of the same size.

GridBagLayout Source Codeimport java.awt.*;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JTextField;

public class GridBagLayoutDemo {

public static void addComponentsToPane(Container pane) {

JButton jbnButton; pane.setLayout(new GridBagLayout()); GridBagConstraints gBC = new GridBagConstraints(); gBC.fill = GridBagConstraints.HORIZONTAL;

jbnButton = new JButton("Button 1"); gBC.weightx = 0.5; gBC.gridx = 0; gBC.gridy = 0; pane.add(jbnButton, gBC);

JTextField jtf = new JTextField("TextField 1"); gBC.gridx = 2; gBC.gridy = 0; jtf.setEditable(false); pane.add(jtf, gBC);

jbnButton = new JButton("Button 3"); gBC.gridx = 2; gBC.gridy = 0; pane.add(jbnButton, gBC);

jbnButton = new JButton("Button 4"); gBC.ipady = 40; //This component has more breadth compared to other buttons gBC.weightx = 0.0; gBC.gridwidth = 3; gBC.gridx = 0; gBC.gridy = 1; pane.add(jbnButton, gBC);

JComboBox jcmbSample = new JComboBox(new String[]{"ComboBox 1", "hi", "hello"}); gBC.ipady = 0; gBC.weighty = 1.0; gBC.anchor = GridBagConstraints.PAGE_END; gBC.insets = new Insets(10,0,0,0); //Padding gBC.gridx = 1; gBC.gridwidth = 2; gBC.gridy = 2; pane.add(jcmbSample, gBC); }

private static void createAndShowGUI() {

JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridBagLayout Source Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane. addComponentsToPane(frame.getContentPane());

frame.pack(); frame.setVisible(true); }

public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}

Output

After Expanding the Frame

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 133: 108784097 Java Tutorial

Download GridBagLayout Source Code

GridBagLayout Class

javax.swingClass GridBagLayoutjava.lang.Objectjava.awt.GridBagLayoutAll Implemented Interfaces: LayoutManager, LayoutManager2, Serializable

GridBagLayout Constructor

GridBagLayout()Creates a grid bag layout manager..

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 134: 108784097 Java Tutorial

Java JMenu class example

JMenuJava Swing Tutorial Explaining the JMenuBar Component. Swing provides support for pull-down and popup menus. AJMenubar can contain several JMenu ‘s. Each of the JMenu ‘s can contain a series of JMenuItem ‘s that you can select.

How Menu’s Are Created?

1. First, A JMenubar is created2. Then, we attach all of the menus to this JMenubar.3. Then we add JMenuItem ‘s to the JMenu ‘s.4. The JMenubar is then added to the frame. By default, each JMenuItem added to a JMenu is enabled—that is, it canbeselected. In certain situations, we may need to disable a JMenuItem. This is done by calling setEnabled(). ThesetEnabled()method also allows components to be enabled.

JMenu Source Codeimport java.awt.*;import java.awt.event.*;import javax.swing.JMenu;import javax.swing.JMenuItem;import javax.swing.JCheckBoxMenuItem;import javax.swing.JRadioButtonMenuItem;import javax.swing.ButtonGroup;import javax.swing.JMenuBar;import javax.swing.KeyStroke;import javax.swing.ImageIcon;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JScrollPane;import javax.swing.JFrame;

//Used Action Listner for JMenuItem & JRadioButtonMenuItem//Used Item Listner for JCheckBoxMenuItempublic class JMenuDemo implements ActionListener, ItemListener {

JTextArea jtAreaOutput; JScrollPane jspPane; public JMenuBar createJMenuBar() { JMenuBar mainMenuBar; JMenu menu1, menu2, submenu; JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem; JRadioButtonMenuItem rbMenuItem; JCheckBoxMenuItem cbMenuItem; ImageIcon icon = createImageIcon("jmenu.jpg"); mainMenuBar = new JMenuBar(); menu1 = new JMenu("Menu 1"); menu1.setMnemonic(KeyEvent.VK_M); mainMenuBar.add(menu1); // Creating the MenuItems plainTextMenuItem = new JMenuItem("Menu item with Plain Text", KeyEvent.VK_T); // can be done either way for assigning shortcuts // menuItem.setMnemonic(KeyEvent.VK_T); // Accelerators, offer keyboard shortcuts to bypass navigating the menu // hierarchy. plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1, ActionEvent.ALT_MASK)); plainTextMenuItem.addActionListener(this); menu1.add(plainTextMenuItem); textIconMenuItem = new JMenuItem("Menu Item with Text & Image", icon); textIconMenuItem.setMnemonic(KeyEvent.VK_B); textIconMenuItem.addActionListener(this); menu1.add(textIconMenuItem); // Menu Item with just an Image iconMenuItem = new JMenuItem(icon); iconMenuItem.setMnemonic(KeyEvent.VK_D); iconMenuItem.addActionListener(this); menu1.add(iconMenuItem); menu1.addSeparator(); // Radio Button Menu items follow a seperator ButtonGroup itemGroup = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem( "Menu Item with Radio Button"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem( "Menu Item 2 with Radio Button"); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); menu1.addSeparator(); // Radio Button Menu items follow a seperator cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box"); cbMenuItem.setMnemonic(KeyEvent.VK_C); cbMenuItem.addItemListener(this); menu1.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box"); cbMenuItem.addItemListener(this); menu1.add(cbMenuItem); menu1.addSeparator(); // Sub Menu follows a seperator submenu = new JMenu("Sub Menu"); submenu.setMnemonic(KeyEvent.VK_S); subMenuItem = new JMenuItem("Sub MenuItem 1"); subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 135: 108784097 Java Tutorial

ActionEvent.CTRL_MASK)); subMenuItem.addActionListener(this); submenu.add(subMenuItem); subMenuItem = new JMenuItem("Sub MenuItem 2"); submenu.add(subMenuItem); subMenuItem.addActionListener(this); menu1.add(submenu); // Build second menu in the menu bar. menu2 = new JMenu("Menu 2"); menu2.setMnemonic(KeyEvent.VK_N); mainMenuBar.add(menu2); return mainMenuBar; } public Container createContentPane() { // Create the content-pane-to-be. JPanel jplContentPane = new JPanel(new BorderLayout()); jplContentPane.setLayout(new BorderLayout());// Can do it either way // to set layout jplContentPane.setOpaque(true); // Create a scrolled text area. jtAreaOutput = new JTextArea(5, 30); jtAreaOutput.setEditable(false); jspPane = new JScrollPane(jtAreaOutput); // Add the text area to the content pane. jplContentPane.add(jspPane, BorderLayout.CENTER); return jplContentPane; } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = JMenuDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find image file: " + path); return null; } } private static void createGUI() { JFrame.setDefaultLookAndFeelDecorated(true); // Create and set up the window. JFrame frame = new JFrame("JMenu Usage Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuDemo app = new JMenuDemo(); frame.setJMenuBar(app.createJMenuBar()); frame.setContentPane(app.createContentPane()); frame.setSize(500, 300); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) (e.getSource()); String s = "Menu Item source: " + source.getText() + " (an instance of " + getClassName(source) + ")"; jtAreaOutput.append(s + "\n"); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument() .getLength()); } public void itemStateChanged(ItemEvent e) { JMenuItem source = (JMenuItem) (e.getSource()); String s = "Menu Item source: " + source.getText() + " (an instance of " + getClassName(source) + ")" + "\n" + " State of check Box: " + ((e.getStateChange() == ItemEvent.SELECTED) ? "selected" : "unselected"); jtAreaOutput.append(s + "\n"); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument() .getLength()); } // Returns the class name, no package info protected String getClassName(Object o) { String classString = o.getClass().getName(); int dotIndex = classString.lastIndexOf("."); return classString.substring(dotIndex + 1); // Returns only Class name } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() { createGUI(); } }); }}

Output

Download JMenuBar Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 136: 108784097 Java Tutorial

Java Scrollable Popup Menu

Scrollable JPopupMenuJava Swing Tutorial Explaining the Scrollable Popup Menu Component. Scrollable JPopupMenu can be used inany of the Java Applications.I developed this as the popup menu can have so many menuitems that, they exceed the screen visible areaand would not be visible.I needed a way to scroll through the menu items of the pop up menu to avoid this visibility problem.

Scrollable PopupMenu Source CodeCustom JButtons are placed on a JPanel. This JPanel is placed on JScrollPane which has a scrollbar.These custom JButtons are nothing but menuitems. These menuitems can be checked and unchecked similar toJCheckBoxMenuItems.

My scrollable jpopupmenu source code contains 5 files.

1. JFramePopupMenu.java (Mainframe containing the button to invoke Scrollable popup menu)

2. XCheckedButton.java (Custom JButton which acts like a JCheckBoxMenuItem for the pop up menu.This class provides a JCheckBoxMenuItrem Functionality, optionally working like a JMenuItem, primarilyused with XJPopupMenu. Rationale for development of this component was the inability of a JMenuItem to workin a Scrollable Popup menu as in XJPopupMenu)

3. XJPopupMenu.java (This is the heart of Scrollable JPopupMenu code)

4. XConstant.java (Interface containing commonly used constants)

5. check.gif

6. menu_spacer.gif

Here is a source code showing, how to create a java swing JPopupMenu with a vertical scrollbar:

1. JFramePopupMenu.java

import java.awt.Component;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.SwingUtilities;

public class JFramePopupMenu extends JFrame {

private JPanel jContentPane = null;

private JButton jbnPopup = null;

private JTextField jtfNumOfMenus = null;

private JLabel lblNumElem = null;

private XJPopupMenu scrollablePopupMenu = new XJPopupMenu(this);

private JButton getBtnPopup() {

if (jbnPopup == null) {

jbnPopup = new JButton();

jbnPopup.setText("View Scrollable popup menu ");

int n = Integer.parseInt(getTxtNumElem().getText());

for (int i=0;i<n;i++){

XCheckedButton xx = new XCheckedButton(" JMenuItem " + (i+1));

xx.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

System.out.println( e );

scrollablePopupMenu.hidemenu();

}

});

// Add Custom JSeperator after 2nd and 7th MenuItem.

if(i == 2 || i == 7){

scrollablePopupMenu.addSeparator();

}

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 137: 108784097 Java Tutorial

scrollablePopupMenu.add(xx);

}

jbnPopup.addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

Component source = (Component) e.getSource();

scrollablePopupMenu.show(source, e.getX(), e.getY());

}

});

}

return jbnPopup;

}

private JTextField getTxtNumElem() {

if (jtfNumOfMenus == null) {

jtfNumOfMenus = new JTextField();

jtfNumOfMenus.setColumns(3);

jtfNumOfMenus.setText("60");

}

return jtfNumOfMenus;

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

JFramePopupMenu thisClass = new JFramePopupMenu();

thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

thisClass.setVisible(true);

}

});

}

public JFramePopupMenu() {

super();

initialize();

}

private void initialize() {

this.setSize(274, 109);

this.setContentPane(getJContentPane());

this.setTitle(" Scrollable JPopupMenu ");

}

private JPanel getJContentPane() {

if (jContentPane == null) {

lblNumElem = new JLabel();

FlowLayout flowLayout = new FlowLayout();

flowLayout.setHgap(8);

flowLayout.setVgap(8);

jContentPane = new JPanel();

jContentPane.setLayout(flowLayout);

jContentPane.add(getBtnPopup(), null);

jContentPane.add(lblNumElem, null);

jContentPane.add(getTxtNumElem(), null);

}

return jContentPane;

}

}

2. XCheckedButton.java

import java.awt.Color;

import java.awt.event.ItemEvent;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import javax.swing.Action;

import javax.swing.BorderFactory;

import javax.swing.ButtonGroup;

import javax.swing.Icon;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JToggleButton;

import javax.swing.SwingConstants;

import javax.swing.UIManager;

import javax.swing.plaf.ComponentUI;

import javax.swing.plaf.basic.BasicButtonUI;

/**

* @author balajihe

*

*/

public class XCheckedButton extends JButton {

// Icon to be used to for the Checked Icon of the Button

private static ImageIcon checkedIcon;

/**

* These colors are required in order to simulate the JMenuItem's L&F

*/

public static final Color MENU_HIGHLIGHT_BG_COLOR = UIManager.getColor

("MenuItem.selectionBackground");

public static final Color MENU_HIGHLIGHT_FG_COLOR = UIManager.getColor

("MenuItem.selectionForeground");

public static final Color MENUITEM_BG_COLOR = UIManager.getColor

("MenuItem.background");

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 138: 108784097 Java Tutorial

public static final Color MENUITEM_FG_COLOR = UIManager.getColor

("MenuItem.foreground");

// This property if set to false, will result in the checked Icon not being

displayed

// when the button is selected

private boolean displayCheck = true;

public XCheckedButton() {

super();

init();

}

public XCheckedButton(Action a) {

super(a);

init();

}

public XCheckedButton(Icon icon) {

super(icon);

init();

}

public XCheckedButton(String text, Icon icon) {

super(text, icon);

init();

}

public XCheckedButton(String text) {

super(text);

init();

}

/**

* Initialize component LAF and add Listeners

*/

private void init() {

MouseAdapter mouseAdapter = getMouseAdapter();

// Basically JGoodies LAF UI for JButton does not allowBackground color to be set.

// So we need to set the default UI,

ComponentUI ui = BasicButtonUI.createUI(this);

this.setUI(ui);

setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 2));

setMenuItemDefaultColors();

// setContentAreaFilled(false);

setHorizontalTextPosition(SwingConstants.RIGHT);

setHorizontalAlignment(SwingConstants.LEFT);

// setModel(new JToggleButton.ToggleButtonModel());

setModel(new XCheckedButtonModel());

setSelected(false);

this.addMouseListener(mouseAdapter);

}

private void setMenuItemDefaultColors() {

XCheckedButton.this.setBackground(MENUITEM_BG_COLOR);

XCheckedButton.this.setForeground(MENUITEM_FG_COLOR);

}

/**

* @return

*/

private MouseAdapter getMouseAdapter() {

return new MouseAdapter() {

// For static menuitems, the background color remains the highlighted color, if this is notoverridden

public void mousePressed(MouseEvent e) {

setMenuItemDefaultColors();

}

public void mouseEntered(MouseEvent e) {

XCheckedButton.this.setBackground(MENU_HIGHLIGHT_BG_COLOR);

XCheckedButton.this.setForeground(MENU_HIGHLIGHT_FG_COLOR);

}

public void mouseExited(MouseEvent e) {

setMenuItemDefaultColors();

}

};

}

/**

* @param checkedFlag

*/

public void displayIcon(boolean checkedFlag) {

if (checkedFlag && isDisplayCheck()) {

if (checkedIcon == null) {

checkedIcon = new ImageIcon("check.gif");

}

this.setIcon(checkedIcon);

} else {

this.setIcon(XConstant.EMPTY_IMAGE_ICON);

}

this.repaint();

}

private class XCheckedButtonModel extends JToggleButton.ToggleButtonModel {

/*

* Need to Override keeping the super code, else the check mark won't come

*/

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 139: 108784097 Java Tutorial

public void setSelected(boolean b) {

ButtonGroup group = getGroup();

if (group != null) {

// use the group model instead

group.setSelected(this, b);

b = group.isSelected(this);

}

if (isSelected() == b) {

return;

}

if (b) {

stateMask |= SELECTED;

} else {

stateMask &= ~SELECTED;

}

// Send ChangeEvent

fireStateChanged();

// Send ItemEvent

fireItemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_

CHANGED, this,

this.isSelected() ? ItemEvent.SELECTED :

ItemEvent.DESELECTED));

XCheckedButton.this.displayIcon(b);

}

}

// Returns true if Button will display Checked Icon on Click. Default Behaviour is to display a

Checked Icon

public boolean isDisplayCheck() {

return displayCheck;

}

/**

* Sets the property which determines whether a checked Icon should be displayed or not

* Setting to false, makes this button display like a normal button

* @param displayCheck

*/

public void setDisplayCheck(boolean displayCheck) {

this.displayCheck = displayCheck;

}

}

3. XJPopupMenu.java

this.getToolkit().getScreenSize().height

- this.getToolkit().getScreenInsets(jframe.getGraphicsConfiguration()).top

- this.getToolkit().getScreenInsets(jframe.getGraphicsConfiguration()).bottom - 4));

super.add(scroll, BorderLayout.CENTER);

// super.add(scroll);

}

public void show(Component invoker, int x, int y) {

init(jframe);

// this.pack();

panelMenus.validate();

int maxsize = scroll.getMaximumSize().height;

int realsize = panelMenus.getPreferredSize().height;

int sizescroll = 0;

if (maxsize < realsize) {

sizescroll = scroll.getVerticalScrollBar().getPreferredSize().width;

}

Scroll.setPreferredSize(new Dimension(scroll.getPreferredSize().width + sizescroll + 20,

scroll.getPreferredSize().height));

this.pack();

this.setInvoker(invoker);

if (sizescroll != 0) {

//Set popup size only if scrollbar is visible

this.setPopupSize(new Dimension(scroll.getPreferredSize().width + 20,

scroll.getMaximumSize().height - 20));

}

// this.setMaximumSize(scroll.getMaximumSize());

Point invokerOrigin = invoker.getLocationOnScreen();

this.setLocation((int) invokerOrigin.getX() + x, (int) invokerOrigin.getY() + y);

this.setVisible(true);

}

public void hidemenu() {

if (this.isVisible()) {

this.setVisible(false);

}

}

public void add(AbstractButton menuItem) {

// menuItem.setMargin(new Insets(0, 20, 0 , 0));

if (menuItem == null) {

return;

}

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 140: 108784097 Java Tutorial

panelMenus.add(menuItem);

menuItem.removeActionListener(this);

menuItem.addActionListener(this);

if (menuItem.getIcon() == null) {

menuItem.setIcon(EMPTY_IMAGE_ICON);

}

if (!(menuItem instanceof XCheckedButton)) {

System.out.println(menuItem.getName());

}

}

public void addSeparator() {

panelMenus.add(new XSeperator());

}

public void actionPerformed(ActionEvent e) {

this.hidemenu();

}

public Component[] getComponents() {

return panelMenus.getComponents();

}

private static class XSeperator extends JSeparator {

XSeperator() {

ComponentUI ui = XBasicSeparatorUI.createUI(this);

XSeperator.this.setUI(ui);

}

private static class XBasicSeparatorUI extends BasicSeparatorUI {

public static ComponentUI createUI(JComponent c) {

return new XBasicSeparatorUI();

}

public void paint(Graphics g, JComponent c) {

Dimension s = c.getSize();

if (((JSeparator) c).getOrientation() == JSeparator.VERTICAL) {

g.setColor(c.getForeground());

g.drawLine(0, 0, 0, s.height);

g.setColor(c.getBackground());

g.drawLine(1, 0, 1, s.height);

} else // HORIZONTAL

{

g.setColor(c.getForeground());

g.drawLine(0, 7, s.width, 7);

g.setColor(c.getBackground());

g.drawLine(0, 8, s.width, 8);

}

}

}

}

}

4. XConstant.java

import javax.swing.Icon;

import javax.swing.ImageIcon;

public interface XConstant {

public static final Icon EMPTY_IMAGE_ICON = new ImageIcon("menu_spacer.gif");

}

Note: Please use the 2 jgoodies jars present in the zip file for the jgoodies look and feel

Download Scrollable JPopupMenu Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 141: 108784097 Java Tutorial

Java Swing Calculator

This is a free Java calculator tutorial developed using Java Swing. Below you will find the java code for calculator alongwith the screenshot. It is a basic four-function calculator java program source code. The calculator that we build willlook like:

Java simple calculator

1. A four-function calculator with the following functions:* Addition – adds two numbers: n1 + n2.* Subtraction – subtracts number two from number one: n1 – n2.* Multiplication – Multiplies two numbers: n1 * n2.* Division – divides number two into number one: n1 / n2.

2. Used JButton for the numbers and functions.

3. Used Jmenu for File and help.4. Created a class to respond to the events caused by numbers, functions, exit, help and about functionality.

5. Used BorderLayout to layout various components in the Calculator Frame. A BorderLayout lays out a container,arrangingand resizing its components to fit in five regions: north, south, east, west, and center.

Java Calculator Source CodeOct 15, 2006 by Hemanth

/* Name: Hemanth. B Website: wwww.java-swing-tutorial.html Topic: A basic Java Swing Calculator Conventions Used in Source code

---------------------------------

1. All JLabel components start with jlb*

2. All JPanel components start with jpl*

3. All JMenu components start with jmenu*

4. All JMenuItem components start with jmenuItem*

5. All JDialog components start with jdlg*

6. All JButton components start with jbn*

*/import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Font;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.KeyStroke;

public class Calculator extends JFrame implements ActionListener {

// Variables final int MAX_INPUT_LENGTH = 20; final int INPUT_MODE = 0; final int RESULT_MODE = 1; final int ERROR_MODE = 2; int displayMode; boolean clearOnNextDigit, percent; double lastNumber; String lastOperator;

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 142: 108784097 Java Tutorial

private JMenu jmenuFile, jmenuHelp; private JMenuItem jmenuitemExit, jmenuitemAbout; private JLabel jlbOutput; private JButton jbnButtons[]; private JPanel jplMaster, jplBackSpace, jplControl; /*

* Font(String name, int style, int size)

Creates a new Font from the specified name, style and point size.

*/ Font f12 = new Font("Times New Roman", 0, 12); Font f121 = new Font("Times New Roman", 1, 12); // Constructor public Calculator() { /* Set Up the JMenuBar.

* Have Provided All JMenu's with Mnemonics

* Have Provided some JMenuItem components with Keyboard Accelerators

*/ jmenuFile = new JMenu("File"); jmenuFile.setFont(f121); jmenuFile.setMnemonic(KeyEvent.VK_F); jmenuitemExit = new JMenuItem("Exit"); jmenuitemExit.setFont(f12); jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); jmenuFile.add(jmenuitemExit); jmenuHelp = new JMenu("Help"); jmenuHelp.setFont(f121); jmenuHelp.setMnemonic(KeyEvent.VK_H); jmenuitemAbout = new JMenuItem("About Calculator"); jmenuitemAbout.setFont(f12); jmenuHelp.add(jmenuitemAbout); JMenuBar mb = new JMenuBar(); mb.add(jmenuFile); mb.add(jmenuHelp); setJMenuBar(mb); //Set frame layout manager setBackground(Color.gray); jplMaster = new JPanel(); jlbOutput = new JLabel("0"); jlbOutput.setHorizontalTextPosition(JLabel.RIGHT); jlbOutput.setBackground(Color.WHITE); jlbOutput.setOpaque(true); // Add components to frame getContentPane().add(jlbOutput, BorderLayout.NORTH); jbnButtons = new JButton[23]; // GridLayout(int rows, int cols, int hgap, int vgap) JPanel jplButtons = new JPanel(); // container for Jbuttons // Create numeric Jbuttons for (int i = 0; i <= 9; i++) { // set each Jbutton label to the value of index jbnButtons[i] = new JButton(String.valueOf(i)); } // Create operator Jbuttons jbnButtons[10] = new JButton("+/-"); jbnButtons[11] = new JButton("."); jbnButtons[12] = new JButton("="); jbnButtons[13] = new JButton("/"); jbnButtons[14] = new JButton("*"); jbnButtons[15] = new JButton("-"); jbnButtons[16] = new JButton("+"); jbnButtons[17] = new JButton("sqrt"); jbnButtons[18] = new JButton("1/x"); jbnButtons[19] = new JButton("%"); jplBackSpace = new JPanel(); jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2)); jbnButtons[20] = new JButton("Backspace"); jplBackSpace.add(jbnButtons[20]); jplControl = new JPanel(); jplControl.setLayout(new GridLayout(1, 2, 2, 2)); jbnButtons[21] = new JButton(" CE "); jbnButtons[22] = new JButton("C"); jplControl.add(jbnButtons[21]); jplControl.add(jbnButtons[22]); // Setting all Numbered JButton's to Blue. The rest to Red for (int i = 0; i < jbnButtons.length; i++) { jbnButtons[i].setFont(f12); if (i < 10) jbnButtons[i].setForeground(Color.blue); else jbnButtons[i].setForeground(Color.red); } // Set panel layout manager for a 4 by 5 grid jplButtons.setLayout(new GridLayout(4, 5, 2, 2)); //Add buttons to keypad panel starting at top left // First row for (int i = 7; i <= 9; i++) { jplButtons.add(jbnButtons[i]); } // add button / and sqrt jplButtons.add(jbnButtons[13]); jplButtons.add(jbnButtons[17]); // Second row for (int i = 4; i <= 6; i++) { jplButtons.add(jbnButtons[i]); } // add button * and x^2 jplButtons.add(jbnButtons[14]); jplButtons.add(jbnButtons[18]); // Third row for (int i = 1; i <= 3; i++) { jplButtons.add(jbnButtons[i]); } //adds button - and % jplButtons.add(jbnButtons[15]); jplButtons.add(jbnButtons[19]); //Fourth Row // add 0, +/-, ., +, and = jplButtons.add(jbnButtons[0]); jplButtons.add(jbnButtons[10]); jplButtons.add(jbnButtons[11]); jplButtons.add(jbnButtons[16]); jplButtons.add(jbnButtons[12]); jplMaster.setLayout(new BorderLayout()); jplMaster.add(jplBackSpace, BorderLayout.WEST); jplMaster.add(jplControl, BorderLayout.EAST); jplMaster.add(jplButtons, BorderLayout.SOUTH); // Add components to frame getContentPane().add(jplMaster, BorderLayout.SOUTH); requestFocus(); //activate ActionListener for (int i = 0; i < jbnButtons.length; i++) { jbnButtons[i].addActionListener(this); }

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 143: 108784097 Java Tutorial

jmenuitemAbout.addActionListener(this); jmenuitemExit.addActionListener(this); clearAll(); //add WindowListener for closing frame and ending program addWindowListener(new WindowAdapter() {

public void windowClosed(WindowEvent e) { System.exit(0); } }); } //End of Contructor Calculator // Perform actionpublic void actionPerformed(ActionEvent e){

double result = 0;

if(e.getSource() == jmenuitemAbout){

JDialog dlgAbout = new CustomABOUTDialog(this,

"About Java Swing Calculator", true);

dlgAbout.setVisible(true);

}else if(e.getSource() == jmenuitemExit){

System.exit(0);

}

// Search for the button pressed until end of array or key found

for (int i=0; i< 1)

setDisplayString("0");

}

break;

case 21: // CE

clearExisting();

break;

case 22: // C

clearAll();

break;

}

}

}

} void setDisplayString(String s) { jlbOutput.setText(s); } String getDisplayString() { return jlbOutput.getText(); } void addDigitToDisplay(int digit) { if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); if (inputString.indexOf("0") == 0) { inputString = inputString.substring(1); } if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH) { setDisplayString(inputString + digit); } displayMode = INPUT_MODE; clearOnNextDigit = false; } void addDecimalPoint() { displayMode = INPUT_MODE; if (clearOnNextDigit) setDisplayString(""); String inputString = getDisplayString(); // If the input string already contains a decimal point, don't // do anything to it. if (inputString.indexOf(".") < 0) setDisplayString(new String(inputString + ".")); } void processSignChange() { if (displayMode == INPUT_MODE) { String input = getDisplayString(); if (input.length() > 0 && !input.equals("0")) { if (input.indexOf("-") == 0) setDisplayString(input.substring(1)); else setDisplayString("-" + input); } } else if (displayMode == RESULT_MODE) { double numberInDisplay = getNumberInDisplay(); if (numberInDisplay != 0) displayResult(-numberInDisplay); } } void clearAll() { setDisplayString("0"); lastOperator = "0"; lastNumber = 0; displayMode = INPUT_MODE; clearOnNextDigit = true; } void clearExisting() { setDisplayString("0"); clearOnNextDigit = true; displayMode = INPUT_MODE; } double getNumberInDisplay() { String input = jlbOutput.getText(); return Double.parseDouble(input); } void processOperator(String op) { if (displayMode != ERROR_MODE) { double numberInDisplay = getNumberInDisplay(); if (!lastOperator.equals("0")) { try { double result = processLastOperator(); displayResult(result); lastNumber = result; } catch (DivideByZeroException e) { }

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 144: 108784097 Java Tutorial

} else { lastNumber = numberInDisplay; } clearOnNextDigit = true; lastOperator = op; } } void processEquals() { double result = 0; if (displayMode != ERROR_MODE) { try { result = processLastOperator(); displayResult(result); } catch (DivideByZeroException e) { displayError("Cannot divide by zero!"); } lastOperator = "0"; } } double processLastOperator() throws DivideByZeroException { double result = 0; double numberInDisplay = getNumberInDisplay(); if (lastOperator.equals("/")) { if (numberInDisplay == 0) throw (new DivideByZeroException()); result = lastNumber / numberInDisplay; } if (lastOperator.equals("*")) result = lastNumber * numberInDisplay; if (lastOperator.equals("-")) result = lastNumber - numberInDisplay; if (lastOperator.equals("+")) result = lastNumber + numberInDisplay; return result; } void displayResult(double result) { setDisplayString(Double.toString(result)); lastNumber = result; displayMode = RESULT_MODE; clearOnNextDigit = true; } void displayError(String errorMessage) { setDisplayString(errorMessage); lastNumber = 0; displayMode = ERROR_MODE; clearOnNextDigit = true; } public static void main(String args[]) { Calculator calci = new Calculator(); Container contentPane = calci.getContentPane(); // contentPane.setLayout(new BorderLayout()); calci.setTitle("Java Swing Calculator"); calci.setSize(241, 217); calci.pack(); calci.setLocation(400, 250); calci.setVisible(true); calci.setResizable(false); }} //End of Swing Calculator Class.

class DivideByZeroException extends Exception {

public DivideByZeroException() { super(); } public DivideByZeroException(String s) { super(s); }}

class CustomABOUTDialog extends JDialog implements ActionListener {

JButton jbnOk; CustomABOUTDialog(JFrame parent, String title, boolean modal) { super(parent, title, modal); setBackground(Color.black); JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); StringBuffer text = new StringBuffer(); text.append("Calculator Information\n\n"); text.append("Developer: Hemanth\n"); text.append("Version: 1.0"); JTextArea jtAreaAbout = new JTextArea(5, 21); jtAreaAbout.setText(text.toString()); jtAreaAbout.setFont(new Font("Times New Roman", 1, 13)); jtAreaAbout.setEditable(false); p1.add(jtAreaAbout); p1.setBackground(Color.red); getContentPane().add(p1, BorderLayout.CENTER); JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); jbnOk = new JButton(" OK "); jbnOk.addActionListener(this); p2.add(jbnOk); getContentPane().add(p2, BorderLayout.SOUTH); setLocation(408, 270); setResizable(false); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { Window aboutDialog = e.getWindow(); aboutDialog.dispose(); } }); pack(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == jbnOk) { this.dispose(); } }}

Download Java Calculator Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 145: 108784097 Java Tutorial

Java Swing Address Book

This java swing project code demonstrate’s how to create a simple free address book program using java swing andjdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and LayoutManager (GridBagLayout).

In short, this is a Simple Address Book that keeps Names, email, Address and Phone Numbers of friends or people.It makes use of the JDBC driver and SQL statements for connecting and manipulating with the database.

Java Address Book Source CodeOct 22, 2006 by Hemanth

This Project Source code consists of 3 files:

1. AddressBookDemo.java2. PersonDao.java3. PersonInfo.java4. An sql Table (Person Table)

AddressBookDemo.java

/* Name: Hemanth. B Website: java-swing-tutorial.html Topic: A basic Java Address Book Conventions Used in Source code --------------------------------- 1. All JLabel components start with jlb*

2. All JPanel components start with jpl*

3. All JMenu components start with jmenu*

4. All JMenuItem components start with jmenuItem*

5. All JDialog components start with jdlg*

6. All JButton components start with jbn*

*/import java.awt.Container;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;

public class AddressBookDemo implements ActionListener {

ArrayList personsList; PersonDAO pDAO; JFrame appFrame; JLabel jlbName, jlbAddress, jlbPhone, jlbEmail; JTextField jtfName, jtfAddress, jtfPhone, jtfEmail; JButton jbbSave, jbnDelete, jbnClear, jbnUpdate, jbnSearch, jbnForward, jbnBack, jbnExit; String name, address, email; int phone; int recordNumber; // used to naviagate using >> and buttons Container cPane; public static void main(String args[]) { new AddressBookDemo(); } public AddressBookDemo() { name = ""; address = ""; email = ""; phone = -1; //Stores 0 to indicate no Phone Number recordNumber = -1; createGUI();

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 146: 108784097 Java Tutorial

personsList = new ArrayList(); // creating PersonDAO object pDAO = new PersonDAO(); } public void createGUI(){

/*Create a frame, get its contentpane and set layout*/ appFrame = new JFrame("Address Book"); cPane = appFrame.getContentPane(); cPane.setLayout(new GridBagLayout()); //Arrange components on contentPane and set Action Listeners to each JButton

arrangeComponents(); appFrame.setSize(240,300); appFrame.setResizable(false); appFrame.setVisible(true);

}

public void arrangeComponents() { jlbName = new JLabel("Name"); jlbAddress = new JLabel("Address"); jlbPhone = new JLabel("Phone"); jlbEmail = new JLabel("Email"); jtfName = new JTextField(20); jtfAddress = new JTextField(20); jtfPhone = new JTextField(20); jtfEmail = new JTextField(20); jbbSave = new JButton("Save"); jbnDelete = new JButton("Delete"); jbnClear = new JButton("Clear"); jbnUpdate = new JButton("Update"); jbnSearch = new JButton("Search"); jbnForward = new JButton(">>"); jbnBack = new JButton(""); jbnExit = new JButton("Exit"); /*add all initialized components to the container*/ GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints(); gridBagConstraintsx01.gridx = 0; gridBagConstraintsx01.gridy = 0; gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5); cPane.add(jlbName, gridBagConstraintsx01); GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints(); gridBagConstraintsx02.gridx = 1; gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx02.gridy = 0; gridBagConstraintsx02.gridwidth = 2; gridBagConstraintsx02.fill = GridBagConstraints.BOTH; cPane.add(jtfName, gridBagConstraintsx02); GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints(); gridBagConstraintsx03.gridx = 0; gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx03.gridy = 1; cPane.add(jlbAddress, gridBagConstraintsx03); GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints(); gridBagConstraintsx04.gridx = 1; gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx04.gridy = 1; gridBagConstraintsx04.gridwidth = 2; gridBagConstraintsx04.fill = GridBagConstraints.BOTH; cPane.add(jtfAddress, gridBagConstraintsx04); GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints(); gridBagConstraintsx05.gridx = 0; gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx05.gridy = 2; cPane.add(jlbPhone, gridBagConstraintsx05); GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints(); gridBagConstraintsx06.gridx = 1; gridBagConstraintsx06.gridy = 2; gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx06.gridwidth = 2; gridBagConstraintsx06.fill = GridBagConstraints.BOTH; cPane.add(jtfPhone, gridBagConstraintsx06); GridBagConstraints gridBagConstraintsx07 = new GridBagConstraints(); gridBagConstraintsx07.gridx = 0; gridBagConstraintsx07.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx07.gridy = 3; cPane.add(jlbEmail, gridBagConstraintsx07); GridBagConstraints gridBagConstraintsx08 = new GridBagConstraints(); gridBagConstraintsx08.gridx = 1; gridBagConstraintsx08.gridy = 3; gridBagConstraintsx08.gridwidth = 2; gridBagConstraintsx08.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx08.fill = GridBagConstraints.BOTH; cPane.add(jtfEmail, gridBagConstraintsx08); GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints(); gridBagConstraintsx09.gridx = 0; gridBagConstraintsx09.gridy = 4; gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5); cPane.add(jbbSave, gridBagConstraintsx09); GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints(); gridBagConstraintsx10.gridx = 1; gridBagConstraintsx10.gridy = 4; gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5); cPane.add(jbnDelete, gridBagConstraintsx10); GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints(); gridBagConstraintsx11.gridx = 2; gridBagConstraintsx11.gridy = 4; gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5); cPane.add(jbnUpdate, gridBagConstraintsx11); GridBagConstraints gridBagConstraintsx12 = new GridBagConstraints(); gridBagConstraintsx12.gridx = 0; gridBagConstraintsx12.gridy = 5; gridBagConstraintsx12.insets = new Insets(5, 5, 5, 5); cPane.add(jbnBack, gridBagConstraintsx12); GridBagConstraints gridBagConstraintsx13 = new GridBagConstraints(); gridBagConstraintsx13.gridx = 1; gridBagConstraintsx13.gridy = 5; gridBagConstraintsx13.insets = new Insets(5, 5, 5, 5); cPane.add(jbnSearch, gridBagConstraintsx13); GridBagConstraints gridBagConstraintsx14 = new GridBagConstraints(); gridBagConstraintsx14.gridx = 2; gridBagConstraintsx14.gridy = 5; gridBagConstraintsx14.insets = new Insets(5, 5, 5, 5); cPane.add(jbnForward, gridBagConstraintsx14); GridBagConstraints gridBagConstraintsx15 = new GridBagConstraints(); gridBagConstraintsx15.gridx = 1; gridBagConstraintsx15.insets = new Insets(5, 5, 5, 5); gridBagConstraintsx15.gridy = 6; cPane.add(jbnClear, gridBagConstraintsx15); GridBagConstraints gridBagConstraintsx16 = new GridBagConstraints(); gridBagConstraintsx16.gridx = 2; gridBagConstraintsx16.gridy = 6; gridBagConstraintsx16.insets = new Insets(5, 5, 5, 5); cPane.add(jbnExit, gridBagConstraintsx16); jbbSave.addActionListener(this); jbnDelete.addActionListener(this); jbnClear.addActionListener(this);

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 147: 108784097 Java Tutorial

jbnUpdate.addActionListener(this); jbnSearch.addActionListener(this); jbnForward.addActionListener(this); jbnBack.addActionListener(this); jbnExit.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == jbbSave) { savePerson(); clear(); } else if (e.getSource() == jbnDelete) { deletePerson(); clear(); } else if (e.getSource() == jbnUpdate) { updatePerson(); clear(); } else if (e.getSource() == jbnSearch) { searchPerson(); } else if (e.getSource() == jbnForward) { displayNextRecord(); } else if (e.getSource() == jbnBack) { displayPreviousRecord(); } else if (e.getSource() == jbnClear) { clear(); } else if (e.getSource() == jbnExit) { System.exit(0); } } // Save the Person into the Address Book public void savePerson() { name = jtfName.getText(); name = name.toUpperCase(); //Save all names in Uppercase address = jtfAddress.getText(); try { phone = Integer.parseInt("" + jtfPhone.getText()); } catch (Exception e) { /*System.out.print("Input is a string");

JOptionPane.showMessageDialog(null, "Please enter Phone Number");*/ } email = jtfEmail.getText(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name."); } else { //create a PersonInfo object and pass it to PersonDAO to save it PersonInfo person = new PersonInfo(name, address, phone, email); pDAO.savePerson(person); JOptionPane.showMessageDialog(null, "Person Saved"); } } public void deletePerson() { name = jtfName.getText(); name = name.toUpperCase(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name to delete."); } else { //remove Person of the given name from the Address Book database int numberOfDeleted = pDAO.removePerson(name); JOptionPane.showMessageDialog(null, numberOfDeleted + " Record(s) deleted."); } } public void updatePerson() { if (recordNumber >= 0 && recordNumber < personsList.size()) { PersonInfo person = (PersonInfo) personsList.get(recordNumber); int id = person.getId(); /*get values from text fields*/ name = jtfName.getText(); address = jtfAddress.getText(); phone = Integer.parseInt(jtfPhone.getText()); email = jtfEmail.getText(); /*update data of the given person name*/ person = new PersonInfo(id, name, address, phone, email); pDAO.updatePerson(person); JOptionPane.showMessageDialog(null, "Person info record updated successfully."); } else { JOptionPane.showMessageDialog(null, "No record to Update"); } } //Perform a Case-Insensitive Search to find the Person public void searchPerson() { name = jtfName.getText(); name = name.toUpperCase(); /*clear contents of arraylist if there are any from previous search*/ personsList.clear(); recordNumber = 0; if (name.equals("")) { JOptionPane.showMessageDialog(null, "Please enter person name to search."); } else { /*get an array list of searched persons using PersonDAO*/ personsList = pDAO.searchPerson(name); if (personsList.size() == 0) { JOptionPane.showMessageDialog(null, "No records found."); //Perform a clear if no records are found. clear(); } else { /*downcast the object from array list to PersonInfo*/ PersonInfo person = (PersonInfo) personsList .get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person.getAddress()); jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } } public void displayNextRecord() { // inc in recordNumber to display next person info, already stored in // personsList during search recordNumber++; if (recordNumber >= personsList.size()) { JOptionPane.showMessageDialog(null, "You have reached end of " + "search results"); /*if user has reached the end of results, disable forward button*/ jbnForward.setEnabled(false); jbnBack.setEnabled(true); // dec by one to counter last inc recordNumber--; } else { jbnBack.setEnabled(true); PersonInfo person = (PersonInfo) personsList.get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person.getAddress());

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 148: 108784097 Java Tutorial

jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } public void displayPreviousRecord() { // dec in recordNumber to display previous person info, already //stored in personsList during search recordNumber--; if (recordNumber < 0) { JOptionPane.showMessageDialog(null, "You have reached begining " + "of search results"); /*if user has reached the begining of results, disable back button*/ jbnForward.setEnabled(true); jbnBack.setEnabled(false); // inc by one to counter last dec recordNumber++; } else { jbnForward.setEnabled(true); PersonInfo person = (PersonInfo) personsList.get(recordNumber); // displaying search record in text fields jtfName.setText(person.getName()); jtfAddress.setText(person.getAddress()); jtfPhone.setText("" + person.getPhone()); jtfEmail.setText(person.getEmail()); } } public void clear() { jtfName.setText(""); jtfAddress.setText(""); jtfPhone.setText(""); jtfEmail.setText(""); /*clear contents of arraylist*/ recordNumber = -1; personsList.clear(); jbnForward.setEnabled(true); jbnBack.setEnabled(true); }}

PersonInfo.java

/*

Name: Hemanth. B Website: java-swing-tutorial.html Topic: A basic Java Address Book Conventions Used in Source code

---------------------------------

1. All JLabel components start with jlb*

2. All JPanel components start with jpl*

3. All JMenu components start with jmenu*

4. All JMenuItem components start with jmenuItem*

5. All JDialog components start with jdlg*

6. All JButton components start with jbn*

*/import java.util.*;import java.sql.*;

public class PersonDAO {

/* Person Table needs to be created in the Oracle Database. * create table Person ( id Integer, name Varchar(30), address Varchar(30), phone Integer, email Varchar(50) );*/

private ArrayList personsList; private String userid = "scott"; private String password = "tiger"; static String url = "jdbc:odbc:bob"; private Connection con; // constructor public PersonDAO() { personsList = new ArrayList(); getConnection(); //Create Connection to the Oracle Database } public Connection getConnection() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } return con; } public ArrayList searchPerson(String name) { try { String sql = "SELECT * FROM Person WHERE name like '%" + name + "%'"; // Create a prepared statement Statement s = con.createStatement(); ResultSet rs = s.executeQuery(sql); String pname = ""; String address = ""; String email = ""; int id, phone; while (rs.next()) { id = rs.getInt("id"); pname = rs.getString("name"); address = rs.getString("address"); phone = rs.getInt("phone"); email = rs.getString("email"); //Create a PersonInfo object PersonInfo person = new PersonInfo(id, pname, address, phone, email); //Add the person object to array list personsList.add(person); } } catch (Exception e) { System.out.println(e);

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com

Page 149: 108784097 Java Tutorial

} return personsList; } public void savePerson(PersonInfo person) { try { String sql = "INSERT INTO Person(name, address, " + "phone, email) VALUES (?,?,?,?) "; // Create a Preparedstatement PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, person.getName()); ps.setString(2, person.getAddress()); ps.setInt(3, person.getPhone()); ps.setString(4, person.getEmail()); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } } public void updatePerson(PersonInfo person) { try { String sql = "UPDATE Person SET name = ?, address=? , " + "phone=? , email=? where id=?"; // Create a Prepared statement PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, person.getName()); ps.setString(2, person.getAddress()); ps.setInt(3, person.getPhone()); ps.setString(4, person.getEmail()); ps.setInt(5, person.getId()); ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } } public int removePerson(String name) { int no = 0; try { String sql = "DELETE FROM Person WHERE name = ?"; // Create a Prepared statement PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, name); no = ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return no; }}// end class PersonDAO

SQL Table

create table Person (id Integer,name Varchar(30),address Varchar(30),phone Integer,email Varchar(50)

Download Java Address Book Source Code

Created By www.ebooktutorials.blogspot.in

Content Downloaded From www.javabeginner.com


Recommended