Java - by Manish
Java - by Manish
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P age |1
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Java
Java is an object oriented programming language originally developed by Sun Micro
System and released in 1995.
Java was originally by James Gosling at Sun Microsystems (which has since merge in
Oracle Corporation).
Java programs are platform independent which means they can be run on any operating
system.
Java codes that run on one platform does not need to recompile to run on another
platform, it’s called “write once run anywhere”.
Java Features
1. Object Oriented
Java is an object oriented programming language which follows the concepts of oop’s.
2. Platform Independent
Java application programs written on one operating system can be able to run on any
platform. So the java is platform independent.
On compilation java program is compiled into byte code (.class file). This byte code is
platform independent and can be run on any machine, in addition to this bytecode format
also provide security. Any machine with Java Runtime Environment can run java
programs.
3. Simple
Java syntax is similar to c and c++ and it follow the oop’s concepts so it is easy to learn.
Aims Tutorial
Oriental Bank of Commerce P age |2
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
4. Secure
Java’s securing feature it enable to develop virus free, tamper free (software which is not
modify by attacker). Authentication techniques are based on public key encryption
Note: A cryptographic system that uses two keys -- a public key known to everyone
and a private or secret key known only to the recipient of the message. When John
wants to send a secure message to Jane, he uses Jane's public key to encrypt the
message. Jane then uses her private key to decrypt it.
Class loader- It adds security by separation by separating the package for the
classes of the local file system from those that are imported from network sources.
Byte code verifiers-It checks the code fragments for illegal code that can violate
access right to objects.
Security Manager- It determines what resources a class can access such as
reading and writing to the local disk.
High Performance- Compilation of program to an architecture independent
machine like language, result in a small efficient interpreter of java programs. The
java environment also complies the java byte code into native machine code at
runtime.
5. Architectural Neutral
Java compiler generates an architectural neutral object file format which makes the
compiler code to be executed on many processors, with the presence of java runtime
system.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for
both 32 and 64 bit architectures.
6. Portable
We may carry the java byte code to any platform.
7. Robust
Robust simply means strong. Java uses strong memory management. There is lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points make
java robust.
8. Multi Threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications etc.
9. Interpreted
Java is a compiled programming language, but rather than compile straight to executable
machine code, it compiles to an intermediate binary form called JVM byte code. The byte
code is then compiled and/or interpreted to run the program.
10. High Performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Aims Tutorial
Oriental Bank of Commerce P age |3
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
11. Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine on
the internet.
12. Dynamic
Java is considered more dynamic than c and c++. In java the application can be create
more dynamic.
Aims Tutorial
Oriental Bank of Commerce P age |4
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P age |5
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Object
Class
Inheritance
Abstraction
Encapsulation
Polymorphism
Class
It is similar to structures in C language. Class can also be defined as user defined data
type but it also contains functions in it. So, class is basically a blueprint for object.
A class enclosed both the data and function that operate on the data, into a single unit.
The variable and function enclosed in a class are called member and member functions
respectively. Member functions define the permission operation on the data member of a
class.
data
Data 1
Data2
Data3
function fun()1
fun()2
fun(3)
Aims Tutorial
Oriental Bank of Commerce P age |6
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Object
Objects are the basic unit of OOP. They are instances of class, which have data
members and use various member functions to perform tasks.
Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be more
than one instance of a class. Each instance of a class can hold its own relevant data.
Data Data1
Data2
Function
Fun1
Fun2
Inheritance
Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class. The new class that is
formed is called derived class. Derived class is also known as a child class or sub class.
Inheritance helps in reducing the overall code size of the program, which is an
important concept in object-oriented programming.
Inheritance is a way to reuse once written code again and again. The derived class can
use all the functions which are defined in base class, hence making code reusable.
Animal
Mammal Reptile
Aims Tutorial
Oriental Bank of Commerce P age |7
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Data Abstraction
Abstraction refers to showing only the essential features of the application and hiding
the details. In C++, classes provide methods to the outside world to access & use the
data variables, but the variables are hidden from direct access.
Data abstraction allows a program to ignore the details of how a data type is
represented. Abstraction (derived from a Latin word , meaning away from and ,
meaning to draw) refers to the act of representing essential features without including
the background details or explanations.
While classifying a class, both data members and member functions are expressed in
the code. But, while using an object (that is an instance of a class) the built in data
types and the members in the class get ignored which is known as data abstraction.
Data Encapsulation
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
It can also be said data binding. Encapsulation is all about binding the data variables
and functions together in class.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.
Polymorphism
The term Polymorphism get derived from the Greek word where ‘poly’+ ‘morphos’
where ‘poly’ means many and ‘morphos’ means forms.
Polymorphism makes the code more readable. It is a feature, which lets is create
functions with same name but different.
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
Shap
Draw()
Aims Tutorial
Oriental Bank of Commerce P age |8
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P age |9
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Step:4 Now alter the path variable so that it also contains the path to jdk installed
directory.
Aims Tutorial
Oriental Bank of Commerce P a g e | 10
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
class: class is a keyword is used to declare classes in java
public: It is an access specifiers . Public means this function is visible to all.
static: static is used to make a function static. To execute a static function you
do not have to create an Object of the class. The main () method here is called
by jvm, without creating any object for class.
void: void is return type, meaning this function will not return anything.
main(): main() method is the most important method in a java program . this
is the method which is executed hence all logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
System.out.println(): This is used to print anything on the consol like
printf()in c.
Aims Tutorial
Oriental Bank of Commerce P a g e | 11
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Step: 5 Now Type java FirstJava on command prompt the enter to run program.
Step: 6 Now you will be able to see Welcome in Aims oriented on your command
prompt.
Aims Tutorial
Oriental Bank of Commerce P a g e | 12
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 13
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 14
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Byte Code:
When the java program compile the source code is converted in intermediate code with
extension .class called, Byte Code which is read by the JVM machine.
Byte code and JVM both makes java platform independent.
Aims Tutorial
Oriental Bank of Commerce P a g e | 15
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Introduction of java Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Garbage Collection
It provides a system-level thread that tracks each memory allocation. During idle cycles in
the JVM, the garbage collection threads checks for and free any memory that can freed.
Garbage collection happens automatically during the life time of a java technology program,
eliminating the need to deal locate memory and avoiding memory leak.
Aims Tutorial
Oriental Bank of Commerce P a g e | 16
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Tokens
Each and every smallest individual unit in a program is known as tokens.
Tokens are the basic buildings blocks in language which are constructed together to
write a program.
The keywords, identifiers, constants, string literals, and operators are examples
of tokens. Punctuation characters such as brackets [ ], braces { }, parentheses ( ), and
commas (,) are also tokens.
1. Keywords
Keywords are those words whose meaning is already defined by language
There are 50 Keywords in java.
Keywords are also called as reserved words.
const and goto are two keywords which are reserved in java but not defined by
java language.
Aims Tutorial
Oriental Bank of Commerce P a g e | 17
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
2. Identifiers
Identifiers are the name given to various programming element like variable name, class
name, object name array name, function name interface name, package name.
Rules for constructing identifier name
All the identifiers must start with either a letter (a to z or A to z) or currency
character ($) or an underscore.
They can have alphabets, digits, and the underscore (_) and dollar sign ($)
characters.
They must not begin with a digit.
After first character, an identifier can have any combination of character.
A java keyword cannot use as an identifiers.
Identifiers in java are case sensitive abc and ABC are two different identifiers.
Uppercase and lowercase are distinct.
Java developers have followed some naming conventions.
1. When more than one word are used in a public methods and instance
name, the second and subsequent words are marked with a leading
letters.
Examples:
dayTemperature
firstDayOfMonth
totalMarks
2. All private and local variable use only lowercase letters combine with
underscores.
Examples:
length
batch_strength
3. All classes and interface start with uppercase letter(and each subsequent
word with a leading uppercase)
Example:
Student
HelloJava
Vehical
MotorCycle
4. Variables that represent constant values use all uppercase letter and
underscore between words.
Example:
TOTAL
F_MAX
PRINCIPAL_AMOUNT
Aims Tutorial
Oriental Bank of Commerce P a g e | 18
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
3. Constants or Literals
Constants or Literals are the fixes values which are not change during the execution of
the programs.
Literals are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in a variable.
Constants or Literals are declare using final keywords
There are five major types of literals.
1. Integer literals
Integers are any numeric values either positive or negative without having
fractional part.
Integer datatype consists of the following primitive data types:
byte, int, short, long can be expressed in decimal(base 10),
hexadecimal(base 16) or octal(base 8) number system.
Example:
final int decimal=100;
final int octal=0144;
final int hexa=0x64;
2. Floating literals
Floats are the numeric values either negative or positive having
fractional parts.
Java has two types of floating point numbers: float and double.
By default floating point literals is double
We can define the floating point literals by appending F or f suffix
after the values.
Example:
final float pi=3.14f;
3. Character literals
A Character literals is a single character in a pair of single quote such as ‘a’,
‘#’
Char datatypes is a single 16-bit Unicode character.
Example:
final char ch=’A’;
final char ch=’\u0041’;
final char ch=’\t’;
final char ch=’\u0009’;
Aims Tutorial
Oriental Bank of Commerce P a g e | 19
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
4. String literals
The set of characters represented as String literals. It is use “double
quotes”.
final String ch="Aims";
5. Boolean literals
The values true and false are treated as literals in java. When we assign a
value to a boolean variable is true or false.
final boolean bool=true;
4. Operator
Operator is the special symbols the perform the mathematical and logical manipulation.
Types of operator
1. Arithmetic operator
Operators which are used for arithmetical operation (+, -, *, /, and %) called
arithmetic operator.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
2. Relational operator
Operators are used to test the relation between two values called relational operator.
All relational operators are binary operators and therefore require two operands. A
relational expression returns false when the relation is false and a true when it is
true.
Aims Tutorial
Oriental Bank of Commerce P a g e | 20
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
3. Logical operator
Operators which are used to combine one or more relational expression called logical
operator.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One ‘Complement
>> Bitwise right shift
<< Bitwise left Shift
Aims Tutorial
Oriental Bank of Commerce P a g e | 21
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
5. Ternary operator
Operator that performs operation on three operands called ternary operator.
Conditional Operator
The conditional operator ? : is called ternary operator as it requires three
operands.
Syntax:
Conditional Exp? Exp1: Exp2
If the value of conditional expression is true then the exp1 is evaluated, otherwise exp2 is
evaluated.
public class TernaryOperatorsDemo
{
public static void main(String args[]) {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
}
6. Assignment operator
Operator ('=') which is used for assigning a value to a variable is called assignment
operator. This operator takes the expression on its right-hand-side and places it into
the variable on its left-hand-side.
For example: m = 5;
Aims Tutorial
Oriental Bank of Commerce P a g e | 22
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Tokens Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Post-decrement
-- is written after variable name. Value is assigned in expression then the
decrement the value.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a--;
System.out.println(i);
}
}OUTPUT:5
5. Separator
The separators define the structure of a program. The separators are used parentheses (
), braces { }, the period (.) and (;) semicolon.
Comments
Comments are special part of the program, to describe or explain the code which make
easy to understand.
Comments are those lines which are not read by the compilers.
Types of Comments
1. Single line comments
Single line comments starts with two forward slash (//)
It useful when only single lines are commented.
final int a=5// a is constants variable
2. Multiline comments
Multiline comments are starts with forward slash/ and after that star (*) and
the text or comment line put then again star(*) put the again forward slash(/)
put to comment .
It is useful when we comment multiple line in program.
3. Document comment
/** document comment*/
This is document comment it described the author and other information
about a program. The JDK javadoc tool uses doc comment for
automatically generated documentation.
Aims Tutorial
Oriental Bank of Commerce P a g e | 24
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Data Types Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Data Types:
Data type are the keyword which assign a type to a variable.
byte
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
Aims Tutorial
Oriental Bank of Commerce P a g e | 25
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Data Types Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
float
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values, generally
the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
Reference Datatypes
Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Aims Tutorial
Oriental Bank of Commerce P a g e | 26
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java Tutorial
Class By:Manish Swarnkar
Contact No:9887474850
[email protected]
Class
“Class is a user defined data types, which holds variables and , which can be accessed and
used by creating instance of that class.”
Class is just a blue print, which declare and defined variables and methods. All objects
of this class will share these data member and function.
About Class:
1. Class name start with an uppercase letter. If class name is made then one word, the
first letter of each word must be in uppercase.
Ex:- Class Study, class AimsTutorial
2. Objects of the class holds separate copies of data member. We can create as many
objects of a class as we need.
How to declare class:
Syntax:
public class Class_Name
{
variables;
methods( );
public static void main(String[] args)
{
Class_Name obj=new Class_Name()
}
};
Example:
public class Aims
{
int i=10;
public static void main(String[] args)
{
Aims a1=new Aims();
System.out.println(a1.i);
}
}
Output: 10;
Objects
Objects are the variable which declare using class name, it holds the data variable, declared in
the class and the member function works on these class objects.
How to declare objects:
public class Abc
{
int x=10;
void display( )
{
System.out.println(x);
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 27
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java Tutorial
Class By:Manish Swarnkar
Contact No:9887474850
[email protected]
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
class Test
{
int a=10;
int b=20;
void add()
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 28
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Array Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Static variable or Class variables − Class variables are variables declared within a
class, outside any method, with the static keyword.
class Test
{
System.out.println(b);//20
}
}
Arrays:-
1) Array is a final class inheritance is not possible.
2) Arrays are used to store the multiple numbers of elements of single type.
3) The length of the array is established at the time of array creation. After creation the length
is fixed.
Root structure:-
java.lang.Object
+--java.lang.reflect.Array
public final class Array extends Object
single dimensional array declaration:-
int[] a;
int []a;
int a[];
declaration & instantiation & initialization :-
approach 1:- int a[]={10,20,30,40};
approach 2:- int[] a=new int[100];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;
10 20 30 40 50 60 70 80 90
Ex:-printing the array elements
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 29
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Array Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Methods (behaviors):-
1) Methods are used to provide the business logic of the project.
2) The methods like a functions in C-language called functions, in java language is called
methods.
3) Inside the class it is possible to declare any number of methods based on the developer
requirement.
4) As a software developer while writing method we have to fallow the coding standards like
the method name starts with lower case letters if the method contains two words every inner
word also starts uppercase letter.
5) It will improve the reusability of the code. By using methods we can optimize the code.
Syntax:-
[modifiers-list] return-Type Method-name (parameter-list)throws Exception
Ex:-
public void m1()
public void m2(int a, int b)
Method Signature:-
The name of the method and parameter list is called Method Signature. Return type and
modifiers list not part of a method signature.
Ex:- m1(int a,int b)------Method Signature
m2();------------------Method signature
Aims Tutorial
Oriental Bank of Commerce P a g e | 30
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Array Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
}
Static method
Method which are declare and defined inside a class and with static keyword and
called using classname.
class Test
{
Static void display()
{
System.out.println("Aims Tutorial");
}
Test.display();
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 31
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Constructor Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
3) Having more memory compared with the 3) Stack memory is very less memory when
stack memory. compared with the heap memory
4) Heap memory is also known as public 4) Stack memory also known as private
memory. This is applicable all the objects. memory. This is applicable only for owners.
This memory is shared by all threads.
5) Destroy when the method is completed.
5)the objects are created in the heap memory Jvm is creating stack memory
with the help of new operator
Constructor
Constructor is a special type of method which has same as class that is used to initialize the
object. Constructor is called at the time of object creation. It constructs the value or provides
data for the object that is why it is known as constructor.
Types of constructor
1. Default constructor.
A Constructor that have no parameter is known as default constructor.
Purpose of default constructor
Default constructor provide the default value to the object 0,null etc depending on the
type.
class Bike
{
public static void main(String args[])
{
Bike b=new Bike();
}
Bike()
{
System.out.println(“Default constructor is created”);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 32
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Constructor Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
2. Parameterized constructor.
A Constructor that has parameter is known as parameterized constructor.
Why use parameterized Constructor
parameterized constructor provide the different values to the distinct object
class Square
{
public static void main(String args[])
{
Square b=new Square (5);
}
Square(int n)
{
System.out.println(n*n);
}
}
this heyword:-
This keyword is used to represent
1. Current class variables.
2. Current class methods.
3. Current class constructors.
class Test
{
int a=10;
int b=20;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 33
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
INHERITANCE
Types of Inheritance
1. Single Inheritance
In this inheritance one derived class inherits from only one base class. It is the simplest
form of inheritance.
A
Base class
B
Derived class
Aims Tutorial
Oriental Bank of Commerce P a g e | 34
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
2. Multiple Inheritance
In this type of inheritance a single derived class inherits from two or more than two base
classes.
A B
Base class Base class
C
Derived class
3. Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which is turn inherits
from some other class. The super class for one is sub class for another class.
A
Base class
B
Derived class
C
Derived class
Aims Tutorial
Oriental Bank of Commerce P a g e | 35
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
4. Hierarchical Inheritance
In this type of inheritance multiple derived classes are inherits from a single base class.
C
Base class
A B
Derived class Derived class
5. Hybrid Inheritance
Hybrid inheritance is combination of multiple and multilevel inheritance. Two or more
type of inheritance are used to design called Hybrid inheritance.
A
Base class
B C
Derived class Derived class
D
Derived class
Aims Tutorial
Oriental Bank of Commerce P a g e | 36
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
1. Single Inheritance
public class Shap
{
int width;
int height;
void setdata(int w, int h)
{
width=w;
height=h;
}
}
class Rectangle extends Shap
{
int getArea()
{
return(width*height);
}
public static void main(String[] args)
{
Rectangle Rect;
Rect.setdata(5,7);
System.out.prinln(“Total Area="+Rect.getArea());
2. Multilevel
publc class Student
{
int rollno;
void read(int rollno)
{
this.rollno=rollno;
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 37
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
}
Output: Enter RollNo=234
Enter Marks in Sub1=20
Enter Marks in Sub2=30
Enter Marks in Sub3=40
Total result=90
Aims Tutorial
Oriental Bank of Commerce P a g e | 38
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Inheritance Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
3. Hierarchal
public class Shap
{
int width;
int height;
void setdata(int w, int h)
{
width=w;
height=h;
}
}
public class Rectangle extends Shap
{
int getArea()
{
return width*height;
}
}
public class Triangle extends Shap
{
int getArea()
{
return (width*height)/2;
}
public static void main(String[] args)
{
Rectangle rect;
Triangle tri;
rect.setdata(5,7);
tri.setdata(5,8);
System.out.println(“Area of Rectangle="+rect.getArea());
System.out.prinln(“Area of Triangle="+tri.getArea());
Aims Tutorial
Oriental Bank of Commerce P a g e | 39
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Polymorphism Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
POLYMORPHISM
1) One thing can exhibits more than one form called polymorphism.
2) The ability to appear in more forms.
3) Polymorphism is a Greek word poly means many and morphism means forms.
Types of Polymorphism
1. Compile Time Polymorphism (Early binding, Static binding)
2. Run Time Polymorphism (Late binding, Dynamic binding)
Ex:-Method Overloading Ex:-Method Overriding
Aims Tutorial
Oriental Bank of Commerce P a g e | 40
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Polymorphism Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
{
System.out.prinln(a+b);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2.5f,3.4f);
}
}
B. Constructor overloading
Just like Method constructor can be overloaded.
We can define multiple constructors with different parameters to overload.
Class Cal
{
void Cal(int a, int b)
{
System.out.prinln(a+b);
}
void Cal(int a, int b, int c)
{
System.out.prinln(a+b+c);
}
public static void main(String args[])
{
Cal C1=new Cal(2,3);
Cal C2=new Cal(3,4,5);
}
}
B. Method Overriding
If we inherit a class into the derived class and provide a definition for one of the
base class’s method again. The method is said to be overriding.
Requirement for method overriding
Inheritance should be there. method overriding cannot be done within a class, for
this we require a derived class and a base class.
method signature should be same in base class and derived class.
class Base
{
void show()
{
System.out.prinln(“Base Class”+”\t");
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 41
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Polymorphism Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
void show()
{
System.out.prinln("Derived Class");
}
public static void main(String[]args)
{
Base B=new Base();
Derived D=new Derived();
B.show();
D.show();
}
}
Output:
Base Class
Derived Class
In the above example, we are calling the overridden function using Base Class and Derived
Class object. Base class object call base class version of function and derived class’s object
call Derived class version of function.
Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.
Aims Tutorial
Oriental Bank of Commerce P a g e | 42
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Abstraction Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
ABSTRACTION
Hiding the internal implementation details and highlighting the essential functionality to the
user this mechanism is called abstraction.
Ex:
a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of services
like withdraw, money transfer, mobile registration).
b. Mobile phones (The mobile persons are hiding the internal circuit implementation and
highlighting touch screen).
Abstraction concepts are implemented in java by abstract class and interface
1. Abstract Class
Abstract class is a java class which contains at least one abstract method.
To specify the particular class is abstract and particular method is abstract method by
using abstract modifier.
For the abstract classes it is not possible to create an object. Because it contains the
unimplemented methods.
For any class if we don’t want instantiation then we have to declare that class as abstract
i.e., for abstract classes instantiation (creation of object) is not possible.
abstract class Test
{
Aims Tutorial
Oriental Bank of Commerce P a g e | 43
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Abstraction Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Abstract methods:-
The method which is having declaration but not implementations such type of methods are
called abstract Method. Hence every abstract method should end with “;”.
The child classes are responsible to provide implementation for parent class abstract
methods.
public abstract Add
{
abstract void add(int a, int b);//it is abstract method which has no definition
}
class Cal
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}
2. Interface
1. Interface is also one of the type of class it contains only abstract methods.
2. For the interfaces also .class files will be generated.
3. Each and every interface by default abstract hence it is not possible to create an
object.
4. Interfaces not alternative for abstract class it is extension for abstract classes.
5. 100 % pure abstract class is called interface.
6. The Interface contains only abstract methods means unimplemented methods.
7. Interfaces giving the information about the functionalities it are not giving the
information about internal implementation.
8. To provide implementation for abstract methods we have to take separate class that
class we can called it as implementation class for that interface.
9. Interface can be implemented by using implements keyword.
10. For the interfaces also the inheritance concept is applicable.
Syntax:-
Interface interface-name
Ex:- interface it1
Note: -
if we are declaring or not By default interface methods are public abstract
interface it1 abstract interface it1
{ {
Void m1(); Both are same public abstract void m1();
Void m2(); public abstract void m2();
} }
Aims Tutorial
Oriental Bank of Commerce P a g e | 44
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Abstraction Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
interface Cal
{
void add(int a, int b);
void sub(int a, int b);
}
class Solution implements Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void sub(int a, int b)
{
System.out.prinln(a-b);
}
public static void main(String[] args)
{
Solution S1=new Solution()’
S1.add();
S1.sub();
}
}
Adaptor class:-
It is a intermefdiate class between the interface and user defined class. And it contains empty
implementation of interface methods.
Limitation of interface advantage of adaptor classes
interface it
{
void m1();
void m2();
;
;
void m100()
}
Class Test implements it
{
Must provide implementation of 100 methods otherwise compiler raise compilation
error
}
interface it
{
void m1();
void m2();
;
;
void m100() ;
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 45
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Abstraction Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 46
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Encapsulation Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Encapsulation
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapsulations by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
get the data.
Ex:-
class Encapsulation
{
private int sid;
private int sname;
public void setSid(int x)
{
this.sid=sid;
}
public int getSid()
{
return sid;
}
public void setSname(String sname)
{
this.sname=sname;
}
public String getSname()
{
return sname;
}
}
To access encapsulated use fallowing code:-
class Test
{
public static void main(String[] args)
{
Encapsulation e=new Encapsulation();
e.setSid(100);
e.setSname("ratan");
int num=e.getSid();
String name=e.getSname();
System.out.println(num);
System.out.println(name);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 47
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Super key-word Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Super Key-word
Aims Tutorial
Oriental Bank of Commerce P a g e | 48
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Super key-word Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Modifiers
Modifiers are the keyword which define the accessibility or scope of a variable , class method
in the program.
1. Public
This is the modifier applicable for classes, methods and variables (only for
instance and static variables but not for local variables).
If a class is declared with public modifier then we can access that class from
anywhere (within the package and outside of the package).
If we declare a member(variable) as a public then we can access that member
from anywhere but Corresponding class should be visible i.e., before checking
member visibility we have to check class visibility.
Ex:-
public class Test // public class can access anywhere
{
public int a=10; //public variable can access any where
public void m1() //public method can access any where
{
System.out.println("public method access in any package");
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 49
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Modifiers Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 50
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Modifiers Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
import calculator.Cal;
public class Solution extends Cal
{
public static void main(String[] args)
{
Solution S1=new Solution();
S1.add(3,4);
S1.sub(3,2);
S1.multi(3,5);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 51
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
String
1) String is a final class it is present in java.lang package.
2) String is nothing but a group of characters or character array.
3) Once we are creating String object it is not possible to do the modifications on existing
object called immutability nature.
Aims Tutorial
Oriental Bank of Commerce P a g e | 52
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Method Description
1 char charAt(int index) returns char value for the particular index
8 static String valueOf(int value) converts given type into string. It is overloaded.
String charAt()
The java string charAt() method returns a char value at the given index number. The
index number starts from 0
public class CharAtExample
{
public static void main(String args[])
{
String name="AimsTutorial";
char ch=name.charAt(4); //returns the char value at the 4th index
System.out.println(ch);
Aims Tutorial
Oriental Bank of Commerce P a g e | 53
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
String length()
The java string length() method length of the string. It returns count of total number of characters.
The length of java string is same as the unicode units of the string.
String concat()
The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.
public class ConcatExample
{
public static void main(String args[])
{
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}
}
String indexOf()
The java string indexOf() method returns index of given character value or substring. If it is
not found, it returns -1. The index counter starts from zero.
public class IndexOfExample
{
public static void main(String args[])
{
int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4);//3
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 54
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
String toLowerCase()
The java string toLowerCase() method returns the string in lowercase letter. In other
words, it converts all characters of the string into lower case letter.
String toUpperCase
The java string toUpperCase() method returns the string in uppercase letter. In other
words, it converts all characters of the string into upper case letter.
String trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before
and after the string, if it exists then removes the spaces and returns the omitted string.
Aims Tutorial
Oriental Bank of Commerce P a g e | 55
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
StringBuffer
Constructors:-
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 56
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class A
{
public static void main(String args[])
{
Aims Tutorial
Oriental Bank of Commerce P a g e | 57
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK
1.5.
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity
as length.
There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:
2) String is slow and consumes more memory when you StringBuffer is fast and consumes
concat too many strings because every time it creates new less memory when you cancat
Aims Tutorial
Oriental Bank of Commerce P a g e | 58
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
String Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
instance. strings.
There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:
StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
1) means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[])
{
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1.toString);
System.out.println(s2);//compiler writes here s2.toString()
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 59
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Wrapper Classes Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Wrapper classes
1) To represent primitive data types as a Object form we required some classes these classes
are called wrapper classes.
2) All wrapper classes present in the java.lang package.
3) Int,byte…. Acts as a primitives we can make the primitives into the objects is called
wrapper calless the the wrapper classes are Integer,Short-----.
4) We are having 8 primitive data types hence sun peoples are providing 8 wrapper classes.
Aims Tutorial
Oriental Bank of Commerce P a g e | 60
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Wrapper Classes Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
1) valueOf():-
By using valueof() we are creating wrapper object and it is a alternative to the constructor.
class Test
{
public static void main(String[] args)
{
//by using constructor converting String/primitive to wrapper object
Integer i=new Integer(10);
System.out.println(i);
//by using valueOf() converting String/primitive to the wrapper object
Boolean b=Boolean.valueOf("true");
System.out.println(b);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 61
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Wrapper Classes Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
XxxValue():-
by using XXXValue() method we are converting wrapper objects into the corresponding
primitive values
class Test
{
public static void main(String[] args)
{
Integer i=Integer.valueOf(150);
System.out.println("byte value :"+i.byteValue());//-106
System.out.println("short value :"+i.shortValue());//150
System.out.println("int value :"+i.intValue());//150
System.out.println("long value :"+i.longValue());//150
System.out.println("float value :"+i.floatValue());//150.0
System.out.println("double value :"+i.doubleValue());//150.0
Character c=new Character('s');
char ch=c.charValue();
System.out.println(ch);
Boolean b=new Boolean(false);
boolean bb=b.booleanValue();
System.out.println(bb);
}
}
parseXXX():-
by using above method we are converting String into the corresponding primitive.
class Test
{
public static void main(String[] args)
{
String str1="10";
String str2="20";
System.out.println(str1+str2);//1020
int a=Integer.parseInt(str1);
float f=Float.parseFloat(str2);
System.out.println(a+f);//30.0
}
}
Autoboxing and Autounboxing:-(introduced in the 1.5 version)
Until 1.4 version we are not allowed to place primitive in the wrapper and wrapper in the
place of primitive. The programmer is responsible person to do the explicit conversion
primitive to the wrapper and wrapper to the primitive.
Autoboxing:-
Integer i=10;
System.out.println(i);
The above statement does not work on the 1.4 and below versions. The auto conversion of the
primitive into the Wrapper object is called the autoboxing these conversions done by
compiler at the time of compilation.
Aims Tutorial
Oriental Bank of Commerce P a g e | 62
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Wrapper Classes Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Autounboxing:-
int a=new Integer(100);
System.out.println(a);
The auto conversion of the wrapper object to the primitive value is called autounboxing and
these conversions are done by compiler at the time of compilation.
Ex :-
class Test
{
static Integer i=10;//i is wrapper object
static int j;//j is primitive variable
static void print(int i)
{
j=i;
System.out.println(j);
}
public static void main(String[] args)
{
print(i);
System.out.println(j);
}
}
Automatic conversion of the primitive to wrapper and wrapper to the primitive:-
Aims Tutorial
Oriental Bank of Commerce P a g e | 63
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Java.io package
Java io(input/output) is used to process to the input and produced the output.
Java uses the concept of stream and makes fast I/O operation.
The java.io package is the collection of classes which are requires to input and output.
We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
Aims Tutorial
Oriental Bank of Commerce P a g e | 64
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Method Description
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
Aims Tutorial
Oriental Bank of Commerce P a g e | 65
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input
stream of bytes.
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It
IOException returns -1 at the end of file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException read from the current input stream.
InputStream Hierarchy
Aims Tutorial
Oriental Bank of Commerce P a g e | 66
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutStream.
Method Description
protected void finalize() It is sued to clean up the connection with the file output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset
int len) off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
It is used to return the file channel object associated with the file
FileChannel getChannel()
output stream.
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader
class.
Method Description
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
Aims Tutorial
Oriental Bank of Commerce P a g e | 68
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
It is used to skip over and discards x bytes of data from the input
long skip(long x)
stream.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In
this file, we are having following content:
Welcome to Aims Tutorial.
After executing the above program, you will get a single character from the file which is 87 (in
byte form). To see the text, you need to convert it into character.
Output:
Welcome to AimsTutorial
Aims Tutorial
Oriental Bank of Commerce P a g e | 69
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Output:
Welcome to Aims Tutorial
BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally uses
buffer to store data. It adds more efficiency than to write data directly into a stream. So, it
makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
Constructor Description
Aims Tutorial
Oriental Bank of Commerce P a g e | 70
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int It write the bytes from the specified byte-input stream into a
off, int len) specified byte array, starting with the given offset
In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Aims Tutorial.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
Success
testout.txt
Welcome to Aims Tutorial.
Aims Tutorial
Oriental Bank of Commerce P a g e | 71
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
Constructor Description
Method Description
int read() It read the next byte of data from the input stream.
int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified
off, int ln) byte array, starting with the given offset.
It closes the input stream and releases any of the system resources
void close()
associated with the stream.
void mark(int
It sees the general contract of the mark method for the input stream.
readlimit)
Aims Tutorial
Oriental Bank of Commerce P a g e | 72
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean
It tests for the input stream to support the mark and reset methods.
markSupported()
Output:
Aims Tutorial
BufferedWriter Class
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
Aims Tutorial
Oriental Bank of Commerce P a g e | 73
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Class constructors
Constructor Description
Class methods
Method Description
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
Aims Tutorial
Oriental Bank of Commerce P a g e | 74
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Output:
success
testout.txt:
Welcome to Aims Tutorial.
BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can
be used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.
Constructor Description
BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses
size) the specified size for an input buffer.
Method Description
It is used to test the input stream support for the mark and reset
boolean markSupported()
method.
boolean ready() It is used to test whether the input stream is ready to be read.
Aims Tutorial
Oriental Bank of Commerce P a g e | 75
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
Java.io package Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
void mark(int
It is used for marking the present position in a stream.
readAheadLimit)
System.out.print((char)i);
}
br.close();
fr.close();
Here, we are assuming that you have following data in "testout.txt" file:
Output:
Welcome to Aims Tutorial.
Aims Tutorial
Oriental Bank of Commerce P a g e | 76
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
GUI
component : -
Component is an object which is displayed pictorially on the screen.
Ex:-
Button,Label,TextField......etc
Container:-
Container is a GUI component, it is able to accommodate all other GUI components.
Ex:-
Frame,Applet.
Event:-
The event nothing but a action generated on the component or the change is made on the
state of the object.
Ex:-
Button clicked, Checkboxchecked, Itemselected in the list, Scrollbar scrolled
horizontal/vertically.
Aims Tutorial
Oriental Bank of Commerce P a g e | 77
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Frame
1) Frame is a class which is present in java.awt package.
2) Frame is a Basic component in AWT, because all the components displayed in a Frame.
3) We are displaying pictures on the Frame.
4) It is possible to display some text on the Frame.
Based on the above reasons the frame will become basic component in AWT.
Constructors:-
* create a Frame class object.
Frame f=new Frame();
* create a Frame class object and pass file
Frame f=new Frame("MyFrame");
* Take a subclass to the Frame and create object to the subclass.
class MyFrame extends Frame
MyFrame f=new MyFrame();
Aims Tutorial
Oriental Bank of Commerce P a g e | 78
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
3) To provide title to the Frame explicitly we have to use the following method
4) When we create a Frame, the default background color of the Frame is white. If you want to
provide particular color to the Frame we have to use the following method.
********CREATION OF FRMAE**********
import java.awt.*;
class Demo
{
public static void main(String[] args)
{
//frame creation
Frame f=new Frame();
//set visibility
f.setVisible(true);
//set the size of the frame
f.setSize(400,400);
//set the background
f.setBackground(Color.red);
//set the title of the frame
f.setTitle("Aims Tutorial");
}
};
Aims Tutorial
Oriental Bank of Commerce P a g e | 79
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Label
1) Label is a constant text which is displayed along with a TextField or TextArea.
2) Label is a class which is present in java.awt package.
3) To display the label we have to add that label into the frame for that purpose we have to
use add() method present in the Frame class.
Constructor
Label l=new Label();
Label l=new Label(“user name”);
Ex :-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("Aims");
f.setBackground(Color.red);
f.setSize(400,500);
Label l=new Label("user name:");
f.add(l);
}
}
TextField
1) TextField is an editable area.
2) In TextField we are able to provide single line of text.
3) Enter Button doesn’t work on TextField. To add TextField into the Frame we have to use
add() method.
1. To set Text to the textarea we have to use the following method.
t.setText(“Aims”);
2. To get the text form the TextArea we have to use fallowing method.
String s=t.getText();
t.appendText("Tutorial");
Aims Tutorial
Oriental Bank of Commerce P a g e | 80
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Constructor:-
TextFiled tx=new TextFiled();
TextField tx=new TextField(“Aims”);
Ex :-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("Aims");
f.setBackground(Color.red);
f.setSize(400,500);
//TextField tx=new TextField(); empty TextField
TextField tx=new TextField("Manish");
//TextField with data
f.add(tx);
}
}
TextArea
1) TextArea is a class present in java.awt.package.
2) TextArea is a Editable Area. Enter button will work on TextArea.
3) To add the TextArea into the frame we have to use the add()
Construction:-
TextArea t=new TextArea();
TextArea t=new TextArea(int rows,int columns);
t.setText(“Aims Tutorial”);
5. To get the text form the TextArea we have to use fallowing method.
String s=t.getText();
Aims Tutorial
Oriental Bank of Commerce P a g e | 81
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
t.appendText("Tutorial");
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("AimsTutorial");
f.setBackground(Color.red);
f.setSize(400,500);
f.setLayout(new FlowLayout());
Label l=new Label("user name:");
TextArea tx=new TextArea(4,10);//4 character height 10 character width
tx.appendText("Manish");
tx.setText("Soni");
System.out.println(tx.getText());
f.add(l);
f.add(tx);
}
}
Choice
1) Choice is a class present in java.awt package.
2) List is allows to select multiple items but choice is allow to select single Item.
Constructor:-
Choice ch=new Choice();
Methods :-
1. To add items to the choice we have to use following method.
ch.add(“HYD”);
ch.add(“Chennai”);
ch.add(“BANGALORE”);
ch.remove(“HYD”);
ch.remove(“BANGALORE”);
Aims Tutorial
Oriental Bank of Commerce P a g e | 82
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
ch.remove(2);
ch.removeAll();
5. To inset the data into the choice based on the particular position.
ch.insert(2,”ratan”);
6. To get selected item from the choice we have to use following method. String
s=ch.getSelectedItem();
7. To get the selected item index number we have to use fallowing method
int a=ch.getSelectedIndex();
ex:-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("AimsTutorial");
f.setBackground(Color.red);
f.setSize(400,500);
Choice ch=new Choice();
ch.add("c");
ch.add("cpp");
ch.add("java");
ch.add(".net");
ch.remove(".net");
ch.remove(0);
ch.insert("Manish",0);
f.add(ch);
System.out.println(ch.getItem(0));
System.out.println(ch.getSelectedItem());
System.out.println(ch.getSelectedIndex());
//ch.removeAll();
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 83
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
List
1) List is a class it is present in java.awt.package
2) List is providing list of options to select. Based on your requirement we can select any
number of elements. To add the List to the frame we have to use add() method.
CONSTRUCTOR:-
It will display the three items size and it is allow selecting the only single item.
It will display the five items and it is allow selecting the multiple items.
Methods:-
l.add(“c”);
l.add(“cpp”);
l.add(“java”);
l.add(“Manish”,0);
2. To remove element from the List we have to use following method.
l.remove(“c”);
l.remove(2);
3. To get selected item from the List we have to use following method.
String x=l.get SelectedItem();
4. To get selected items from the List we have to use following method.
String[] x=s.get SelectedItems()
Ex:-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("ratan");
f.setBackground(Color.red);
f.setSize(400,500);
f.setLayout(new FlowLayout());
List l=new List(4,true);
l.add("c");
Aims Tutorial
Oriental Bank of Commerce P a g e | 84
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
l.add("cpp");
l.add("java");
l.add(".net");
l.add("ratan");
l.add("arun",0);
l.remove(0);
f.add(l);
System.out.println(l.getSelectedItem());
}
}
Checkbox:-
2) The user can select more than one checkbox at a time. To add the checkbox to the frame we
have to use add() method.
Constructor:-
cb1.setLable(“BTECH”);
Methods:-
1. To set a label to the CheckBox explicitly and to get label from the CheckBox we have to use
the following method.
cb.setLabel(“BSC”);
String str=cb.getLabel();
3. To get state of the CheckBox and to set state to the CheckBox we have to use following
method.
Boolean b=ch.getState();
Ex:-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Aims Tutorial
Oriental Bank of Commerce P a g e | 85
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
2) It is possible to select Only item is selected from group of item. To add the RadioButton to
the frame we have to use add() method.
1) To set status and to get status we have to use setState() and getState() methods.
String str=Cb.getState();
Cb.setState();
String str=getLabel()
setLabel(“female”).
Ex:-
import java.awt.*;
class Test
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setVisible(true);
f.setTitle("Aims Tutorial");
f.setBackground(Color.red);
f.setSize(400,500);
Aims Tutorial
Oriental Bank of Commerce P a g e | 86
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
1. When we create a component the components visible on the screen but it is not possible to
perform any action for example button.
2. Whenever we create a Frame it can be minimized and maximized and resized but it is not
possible to close the Frame even if we click on Frame close Button.
3. The Frame is a static component so it is not possible to perform actions on the Frame.
4. To make static component into dynamic component we have to add some actions to the
Frame.
Aims Tutorial
Oriental Bank of Commerce P a g e | 87
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Whenever we click on button no action will be performed clicking like this is called
event.
Event: - Event is nothing but a particular action generated on the particular component.
1. When an event generates on the component the component is unable to respond because
component can't listen the event.
2. To make the component listen the event we have to add listeners to the component.
3. Wherever we are adding listeners to the component the component is able to respond
based on the generated event.
A component delegate event to the listener and listener is designates the event to appropriate
method by executing that method only the event is handled. This is called Event Delegation
Model.
Handling method
Added listener to the component
Delegates
Handling method
listeners
component
Delegates Delegates
Delegates
Click the button(event is raised)
Handling method
Note: -
To attach a particular listener to the Frame we have to use following method
Public void AddxxxListener(xxxListener e)
Where xxx may be ActionListener,windowListener
The Appropriate Listener for the Frame is “windowListener”
ScrollBar:-
1. VERTICAL ScrollBar
2. HORIZONTAL ScrollBar
Aims Tutorial
Oriental Bank of Commerce P a g e | 88
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 89
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 90
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 91
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Note ;- by using WindowAdaptor class we can close the frame. Internally WindowAdaptor
class implements WindowListener interface. Hence WindowAdaptor class contains empty
implementation of abstract methods.
****PROVIDING CLOSEING OPTION THE FRAME******
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.red);
this.setTitle("trialAims T");
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
class FrameEx
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
***WRITE SOME TEXT INTO THE FRAME********
import java.awt.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.red);
this.setTitle("rattaiah");
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
this.setForeground(Color.green);
g.drawString("HI BTECH ",100,100);
g.drawString("good boys &",200,200);
g.drawString("good girls",300,300);
Aims Tutorial
Oriental Bank of Commerce P a g e | 92
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
}
class FrameEx
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
------------------------------------------------
********LAYOUT MACHANISUMS FLOWLAYOUT**********
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Label l1,l2;
TextField tx1,tx2;
Button b;
MyFrame()
{
this.setVisible(true);
this.setSize(340,500);
this.setBackground(Color.green);
this.setTitle("Aims Tutorial");
l1=new Label("user name:");
l2=new Label("password:");
tx1=new TextField(25);
tx2=new TextField(25);
b=new Button("login");
tx2.setEchoChar('*');
this.setLayout(new FlowLayout());
this.add(l1);
this.add(tx1);
this.add(l2);
this.add(tx2);
this.add(b);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
Aims Tutorial
Oriental Bank of Commerce P a g e | 93
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
----------------------------------------------------
*****BORDERLAYOUT**********
import java.awt.*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4,b5;
MyFrame()
{
this.setBackground(Color.green);
this.setSize(400,400);
this.setVisible(true);
this.setLayout(new BorderLayout());
b1=new Button("Boys");
b2=new Button("Girls");
b3=new Button("management");
b4=new Button("Teaching Staff");
b5=new Button("non-teaching staff");
this.add("North",b1);
this.add("Center",b2);
this.add("South",b3);
this.add("East",b4);
this.add("West",b5);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
---------------------------------------------------
********CardLayout*************
import java.awt.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setSize(400,400);
this.setVisible(true);
this.setLayout(new CardLayout());
Button b1=new Button("button1");
Button b2=new Button("button2");
Button b3=new Button("button3");
Button b4=new Button("button4");
Button b5=new Button("button5");
this.add("First Card",b1);
this.add("Second Card",b2);
Aims Tutorial
Oriental Bank of Commerce P a g e | 94
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
this.add("Thrid Card",b3);
this.add("Fourth Card",b4);
this.add("Fifth Card",b5);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
********GRIDLAYOUT**********
import java.awt.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("rattaiah");
this.setBackground(Color.red);
this.setLayout(new GridLayout(4,4));
for (int i=0;i<10 ;i++ )
{ Button b=new Button(""+i);
this.add(b);
}
};
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
*********ACTIONLISTENER**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ActionListener
{
TextField tx1,tx2,tx3;
Label l1,l2,l3;
Button b1,b2;
int result;
myframe()
{
this.setSize(250,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
Aims Tutorial
Oriental Bank of Commerce P a g e | 95
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 96
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
------------------------------------------------------------------------------------------------------------------------
----------------
***** LOGIN STATUS*********
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
Label l1,l2;
TextField tx1,tx2;
Button b;
String status="";
MyFrame()
{
setVisible(true);
setSize(400,400);
setTitle("girls");
setBackground(Color.red);
l1=new Label("user name:");
l2=new Label("password:");
tx1=new TextField(25);
tx2=new TextField(25);
b=new Button("login");
b.addActionListener(this);
tx2.setEchoChar('*');
this.setLayout(new FlowLayout());
this.add(l1);
this.add(tx1);
this.add(l2);
this.add(tx2);
this.add(b);
}
public void actionPerformed(ActionEvent ae)
{
String uname=tx1.getText();
String upwd=tx2.getText();
if (uname.equals("durga")&&upwd.equals("dss"))
{
status="login success";
}
else
{
status="login failure";
}
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,30);
g.setFont(f);
Aims Tutorial
Oriental Bank of Commerce P a g e | 97
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
this.setForeground(Color.green);
g.drawString("Status:----"+status,50,300);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
------------------------------------------------------------------------------------------------------------------------
----------------
******MENUITEMS************
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
String label="";
MenuBar mb;
Menu m1,m2,m3;
MenuItem mi1,mi2,mi3;
MyFrame()
{
this.setSize(300,300);
this.setVisible(true);
this.setTitle("myFrame");
this.setBackground(Color.green);
mb=new MenuBar();
this.setMenuBar(mb);
m1=new Menu("new");
m2=new Menu("option");
m3=new Menu("edit");
mb.add(m1);
mb.add(m2);
mb.add(m3);
mi1=new MenuItem("open");
mi2=new MenuItem("save");
mi3=new MenuItem("saveas");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
}
public void actionPerformed(ActionEvent ae)
{
label=ae.getActionCommand();
Aims Tutorial
Oriental Bank of Commerce P a g e | 98
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,25);
g.setFont(f);
g.drawString("Selected item....."+label,50,200);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
------------------------------------------------------------------------------------------------------------------------
----------------
*****MOUSELISTENER INTERFACE**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements MouseListener
{
String[] msg=new String[5];
myframe()
{
this.setSize(500,500);
this.setVisible(true);
this.addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
msg[0]="mouse clicked......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mousePressed(MouseEvent e)
{
msg[1]="mouse pressed......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseReleased(MouseEvent e)
{
msg[2]="mouse released......("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseEntered(MouseEvent e)
{
msg[3]="mouse entered......("+e.getX()+","+e.getY()+")";
repaint();
Aims Tutorial
Oriental Bank of Commerce P a g e | 99
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
public void mouseExited(MouseEvent e)
{
msg[4]="mouse exited......("+e.getX()+","+e.getY()+")";
repaint();
}
public void paint(Graphics g)
{
int X=50;
int Y=100;
for(int i=0;i<msg.length;i++)
{
if (msg[i]!=null)
{
g.drawString(msg[i],X,Y);
Y=Y+50;
}
}
}
};
class Demo
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};
------------------------------------------------------------------------------------------------------------------------
----------------
*******ITEMLISTENER INTERFACE**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{
String qual="",gen="";
Label l1,l2;
CheckboxGroup cg;
Checkbox c1,c2,c3,c4,c5;
Font f;
myframe()
{
this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
l1=new Label("Qualification: ");
l2=new Label("Gender: ");
c1=new Checkbox("BSC");
c2=new Checkbox("BTECH");
c3=new Checkbox("MCA");
Aims Tutorial
Oriental Bank of Commerce P a g e | 100
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
cg=new CheckboxGroup();
c4=new Checkbox("Male",cg,false);
c5=new Checkbox("Female",cg,true);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
this.add(l1);
this.add(c1);
this.add(c2);
this.add(c3);
this.add(l2);
this.add(c4);
this.add(c5);
}
public void itemStateChanged(ItemEvent ie)
{
if(c1.getState()==true)
{
qual=qual+c1.getLabel()+",";
}
if(c2.getState()==true)
{
qual=qual+c2.getLabel()+",";
}
if(c3.getState()==true)
{
qual=qual+c3.getLabel()+",";
}
if(c4.getState()==true)
{
gen=c4.getLabel();
}
if(c5.getState()==true)
{
gen=c5.getLabel();
}
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
this.setForeground(Color.green);
g.drawString("qualification------>"+qual,50,100);
g.drawString("gender-------------->"+gen,50,150);
qual="";
gen="";
Aims Tutorial
Oriental Bank of Commerce P a g e | 101
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
}
class rc
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};
------------------------------------------------------------------------------------------------------------------------
----------------
*********KEYLISTENER INTERFACE***********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame
{
myframe()
{
this.setSize(400,400);
this.setVisible(true);
this.setBackground(Color.green);
this.addKeyListener(new keyboardimpl());
}
};
class keyboardimpl implements KeyListener
{
public void keyTyped(KeyEvent e)
{
System.out.println("key typed "+e.getKeyChar());
}
public void keyPressed(KeyEvent e)
{
System.out.println("key pressed "+e.getKeyChar());
}
public void keyReleased(KeyEvent e)
{
System.out.println("key released "+e.getKeyChar());
}
}
class Demo
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};
Aims Tutorial
Oriental Bank of Commerce P a g e | 102
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
---------------------------------------------------------------------------------------------------------------------------------------
***********CHECK LIST AND CHOICE************
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{
Label l1,l2;
List l;
Choice ch;
String[] tech;
String city="";
myframe()
{
this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
l1=new Label("Technologies: ");
l2=new Label("City: ");
l=new List(3,true);
l.add("c");
l.add("c++");
l.add("java");
l.addItemListener(this);
ch=new Choice();
ch.add("hyd");
ch.add("chenni");
ch.add("Banglore");
ch.addItemListener(this);
this.add(l1);
this.add(l);
this.add(l2);
this.add(ch);
}
public void itemStateChanged(ItemEvent ie)
{
tech=l.getSelectedItems();
city=ch.getSelectedItem();
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
String utech="";
for(int i=0;i<tech.length ;i++ )
{
utech=utech+tech[i]+" ";
}
g.drawString("tech:-------"+utech,50,200);
g.drawString("city---------"+city,50,300);
Aims Tutorial
Oriental Bank of Commerce P a g e | 103
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
utech="";
}
}
class Demo
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};
-----------------------------------------------
*********AdjustmentListener**********
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements AdjustmentListener
{
Scrollbar sb;
int position;
myframe()
{
this.setSize(400,400);
this.setVisible(true);
this.setLayout(new BorderLayout());
sb=new Scrollbar(Scrollbar.VERTICAL);
this.add("East",sb);
sb.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
position=sb.getValue();
}
public void paint(Graphics g)
{
g.drawString("position:"+position,100,200);
repaint();
}
}
class scrollbarex
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};
Aims Tutorial
Oriental Bank of Commerce P a g e | 104
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
SWINGS
3. An alternative to AWT Netscape Communication has provided set of GUI components in the form of
IFC(Internet Foundation Class).
4. IFC also provide less performance and it is not satisfy the client requirement.
5. In the above contest[sun+Netscape] combine and introduced common product to design GUI
applications.
1. AWT components are heavyweight component but swing components are light weight component.
2. AWT components consume more number of system resources Swings consume less number of system
resources.
3. AWT components are platform dependent but Swings are platform independent.
4. AWT is provided less number of components where as swings provides more number of components.
5. AWT doesn’t provide Tooltip Test support but swing components have provided Tooltip test support.
windowAdaptor
In case of swing use small piece of code.
i. f.setDefaultCloseOption(JFrame.EXIT-ON-CLOSE);
7. AWT will not follow MVC but swing follows MVC Model View Controller It is a design pattern to provide
clear separation b/w controller part,model part,view part.
Aims Tutorial
Oriental Bank of Commerce P a g e | 105
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
8. In case of AWT we will add the GUI components in the Frame directly but Swing we will add all GUI
components to panes to accommodate GUI components.
Classes of swing:-
******************SWING*********************
import java.awt.*;
import javax.swing.*;
class MyFrame extends JFrame
{
JLabel l1,l2,l3,l4,l5,l6,l7;
JTextField tf;
JPasswordField pf;
JCheckBox cb1,cb2,cb3;
JRadioButton rb1,rb2;
JList l;
JComboBox cb;
JTextArea ta;
JButton b;
Container c;
MyFrame()
{
this.setVisible(true);
this.setSize(150,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.green);
l1=new JLabel("User Name");
l2= new JLabel("password");
l3= new JLabel("Qualification");
l4= new JLabel("User Gender");
l5= new JLabel("Technologies");
l6= new JLabel("UserAddress");
l7= new JLabel("comments");
tf=new JTextField(15);
tf.setToolTipText("TextField");
pf=new JPasswordField(15);
pf.setToolTipText("PasswordField");
cb1=new JCheckBox("BSC",false);
cb2=new JCheckBox("MCA",false);
cb3=new JCheckBox("PHD",false);
rb1=new JRadioButton("Male",false);
rb2=new JRadioButton("Female",false);
Aims Tutorial
Oriental Bank of Commerce P a g e | 106
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
Aims Tutorial
Oriental Bank of Commerce P a g e | 107
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=getContentPane();
cc=new JColorChooser();
cc.getSelectionModel().addChangeListener(this);
c.add(cc);
}
public void stateChanged(ChangeEvent c)
{
Color color=cc.getColor();
JFrame f=new JFrame();
f.setSize(400,400);
f.setVisible(true);
f.getContentPane().setBackground(color);
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
********JFILECHOOSER*********************
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ActionListener
{
JFileChooser fc;
Container c;
JLabel l;
JTextField tf;
JButton b;
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=getContentPane();
l=new JLabel("Select File:");
tf=new JTextField(25);
b=new JButton("BROWSE");
this.setLayout(new FlowLayout());
b.addActionListener(this);
c.add(l);
c.add(tf);
c.add(b);
Aims Tutorial
Oriental Bank of Commerce P a g e | 108
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
}
public void actionPerformed(ActionEvent ae)
{
class FileChooserDemo extends JFrame implements ActionListener
{
FileChooserDemo()
{
Container c=getContentPane();
this.setVisible(true);
this.setSize(500,500);
fc=new JFileChooser();
fc.addActionListener(this);
fc.setLayout(new FlowLayout());
c.add(fc);
}
public void actionPerformed(ActionEvent ae)
{
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
tf.setText(path);
this.setVisible(false);
}
}
new FileChooserDemo();
}
}
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
-----------------------------------------
********JTABLE******************
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
class Demo1
{
public static void main(String[] args)
{
JFrame f=new JFrame();
f.setVisible(true);
f.setSize(300,300);
Container c=f.getContentPane();
String[] header={"ENO","ENAME","ESAL"};
Object[][] body={{"111","aaa",5000},{"222","bbb",6000},{"333","ccc",7000},{"444","ddd",8000}};
JTable t=new JTable(body,header);
JTableHeader th=t.getTableHeader();
c.setLayout(new BorderLayout());
Aims Tutorial
Oriental Bank of Commerce P a g e | 109
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041
GUI Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
[email protected]
c.add("North",th);
c.add("Center",t);
}
}
Aims Tutorial
Oriental Bank of Commerce P a g e | 110
H.No.:69/339 VT Road Ward 27, By: Manish Swarnkar
Mansarovar Jaipur (Rajasthan) 302020 9887474850
Contact No: +91-8947920041