100% found this document useful (1 vote)
448 views

Java - by Manish

The document provides an introduction to the Java programming language. It discusses that Java was originally developed by Sun Microsystems and released in 1995. It notes that Java is an object-oriented language that is platform independent, meaning programs can run on any operating system. The document then lists and describes 12 key features of Java, including that it is object-oriented, platform independent, simple, secure, architecturally neutral, portable, robust, multi-threaded, interpreted, distributed, dynamic, and high-performance. It also discusses the different types of Java applications and editions of the Java technology.

Uploaded by

Rahul singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
448 views

Java - by Manish

The document provides an introduction to the Java programming language. It discusses that Java was originally developed by Sun Microsystems and released in 1995. It notes that Java is an object-oriented language that is platform independent, meaning programs can run on any operating system. The document then lists and describes 12 key features of Java, including that it is object-oriented, platform independent, simple, secure, architecturally neutral, portable, robust, multi-threaded, interpreted, distributed, dynamic, and high-performance. It also discusses the different types of Java applications and editions of the Java technology.

Uploaded by

Rahul singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

Introduction of java Java Tutorial

By:Manish Swarnkar
Contact No:9887474850
[email protected]

Java Training Module

(A Software Development Company and Training Center)

c Address Contact Information:


Aims Tutorial Contact No: +91-8947920041,
Oriental Bank of Commerce 9829761399
H.No.:69/339 VT Road Ward 27, Email: [email protected]
Mansarovar Jaipur (Rajasthan) [email protected]
302020 Website: www.aimstutorial.com
www.integrationedutech.com

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.

Types of java Application


1. Web Application
Java is used to create server side applications. Currently , servelet, jsp, struts, jsf etc
technology are used.
2. Stand- Alone Application
It is also known as desktop application or window based application. An application
that we need to install on every machine such as antivirus, media player etc. AWT and
Swing is used in java for creating standalone application.
3. Enterprise Application
An application that is distributed in nature, such as banking application etc. In java
EJB is used to create enterprise application.
4. Mobile application
Java is used to create application software for mobile devices. Currently
java ME is used for creating application for small devices and java is programming for
Google Android application development.

Different Editions of java Technology


1. Java SE
Java SE or Java Standard Edition provides tools and API’s that can use to create
server application, desktop application and even applets. These programs developed
using java SE can be run on almost every popular operating system include Linux,
Macintosh, Solaris, and Windows.
2. JEE
Based on the foundation framework of the standard edition, java Enterprise Edition
helps in web application service, component model and enterprise class service
oriented architecture.
3. JME
Java Micro Edition or JME is use for the development of software for devices like
mobile phones, PDA’s, TV set-top box, game programming.

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]

C++ v/s Java

Comparison C++ Java


Platform-
C++ is platform-dependent. Java is platform-independent.
independent
Java is mainly used for application
C++ is mainly used for system programming. It is widely used in
Mainly used for
programming. window, web-based, enterprise and
mobile applications.
Goto C++ supports goto statement. Java doesn't support goto statement.
Java doesn't support multiple inheritance
Multiple C++ supports multiple
through class. It can be achieved by
inheritance inheritance.
interfaces in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
C++ supports pointers. You you can't write the pointer program in
Pointers can write pointer program in java. It means java has restricted pointer
C++. support in java.
Compiler and
C++ uses compiler only. Java uses compiler and interpreter both.
Interpreter
Call by Value and C++ supports both call by Java supports call by value only. There is
Call by reference value and call by reference. no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
C++ doesn't have built-in
support for threads. It relies
Thread Support Java has built-in thread support.
on third-party libraries for
thread support.
Java supports documentation comment
Documentation C++ doesn't support
(/** ... */) to create documentation for
comment documentation comment.
java source code.
Java has no virtual keyword. We can
C++ supports virtual keyword
override all non-static methods by
Virtual Keyword so that we can decide whether
default. In other words, non-static
or not override a function.
methods are virtual by default.
Java supports unsigned right shift >>>
unsigned right C++ doesn't support >>> operator that fills zero at the top for the
shift >>> operator. negative numbers. For positive numbers,
it works same like >> operator.
Java uses single inheritance tree always
C++ creates a new inheritance because all classes are the child of Object
Inheritance Tree
tree always. class in java. Object class is the root of
inheritance tree in java.

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]

Java oop’s Concepts or java oop’s paradigm


 Object Oriented Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.
 The programming paradigm where everything is represented as an object is known as
truly object-oriented programming language.

OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming
is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

 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

Obj Obj Obj


1 2 3
Data Data Data

function function function

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

Elephant Tiger Crocodile

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()

Circle obj Box obj Triangle obj

Draw(Circle) Draw(Box) Draw(Triangle)

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]

Setting Path for Java


Java is freely available on the oracle website Download the latest version of JDK(java
Development Kit)on your machine. Install JDK on your machine. Once you have installed
java on your machine it need to set environment variable to point to correct installation
directory.
An environment variable is a dynamic “object ” on a computer that stores a value (like a key
value ), which can be reference by one or more software programs in Windows. Like in java ,
we will set environment variable with name ”java” and its values will be the path of /bin
directory present variable which will give it the path to the execution.

Step: 1 Right click on My Computer icon and select properties.

Step: 2 Go to Advance Setting Tab

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: 3 Click on Environment Variable Button

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]

First java Program


public class FirstJava
{
public static void main(String[] args)
{
System.out.println("Welcome in Aims");
}

}
 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.

Steps to compile and Run FirstJava Program


Step: 1 Open a text editor like Notepad and write the code as above.
Step: 2 save the file as FirstJava.java
Step: 3Open command prompt and go to the directory where you saved your first java
program

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: 4 Type javac FirstJava.java then enter to compile the program

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]

Java Development Kit (JDK)


JDK is an acronym for Java Development Kit.
It physically exists. It contains JRE + the complete set of class file for all the java technology
package, which include basic language classes.GUI components classes, an advanced
collection API, and so no.

Java Virtual Machine (JVM)


It is an abstract machine or imaginary machine that is implemented by emulating it in
software on a real machine. Code for JVM is stored in .class file. It is a specification that
provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM specification provides concrete definition for the implementation of the following:
an instruction set (equivalent to that of a center processing machine [CPU]), a register set,
the class file format, a runtime stack, a garbage-collector heap a memory area etc.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM Internal Architecture


It contains
1. Class loader: class loader loads all classes needed for the execution of a program. The class
loader adds security.
2. Memory area
1. Class (Method) Area: Class (Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
2. Heap: It is the runtime data area in which objects are allocated.
3. Stack: It holds local variables and partial results, and plays a part in method invocation and
return.
4. Program counter Registers: PC (program counter) register. It contains the address of the
Java virtual machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.
3. Execution engine
It contains
1. A virtual processor
2. Interpreter: Read byte code stream the execute the instruction

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]

Java Runtime Environment (JRE)


It is used to provide runtime environment. It is the implementation of JVM. It physically
exists. It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs is also actively released by other companies besides Sun Micro
Systems.

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]

Difference between JRE and JDK


Sr. JRE JDK
no
1 JRE is an implementation of the java JDk is bundle of software that is used to
Virtual Machine which actually develop java base application
executes java program
2 Java Runtime Environment is a plug- Java Development Kit is needed for
in needed for running java programs developing java application
3 JRE include the JVM, core libraries JDk include the JRE, set of API classes, java
And other additional component to run complier and additional files needed to write
application and applets written in java java applets and applications.

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.

Just-In-Time (JIT) Compiler


In some Java technology runtime environments a portion of verified byte code is
compiled to native machine code by the JIT(Just-In-Time compiler)and execute directly
on the hardware platform. This compiler is called Just-IN-Time Complier. It enables the java
software code to run close to the speed of C or C++ with small delay at load time to enable
the code to be compiled to the native machine code.

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]

Byte Code Verifier


Java software code passes several tasks before running on your machine. The JVM puts the
code through byte code verifiers that tests the format of code fragments and check code for
illegal code, called byte code verifiers. It provides securities for java programs.

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.

abstract continue goto package switch


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

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

5. Package name should be in lowercase


Example:
java, lang, sql, util, etc.
6. Method name should be in lowercase letters.
Example:
print (), println().

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’;

Escape Sequence Characters

Escape Character Meaning


\n New line
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ backslash
\’ single quote
\”” double quotation marks

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.

Relational Operators Meaning


< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to
public class RelationalOperatorsDemo
{ public static void main(String args[])
{
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}
}

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.

Operators Meaning operation


|| OR a||b is true
&& AND a&&b is false
! NOT (!a) is false

public class LogicalOperatorsDemo


{
public static void main(String args[]) {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
}
4. Bitwise operator
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in java are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One ‘Complement
>> Bitwise right shift
<< Bitwise left Shift

Truth Table of Bitwise operator


x y x|y x&y x^y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0

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]

public class BitwiseOperatorsDemo


{
public static void main(String args[])
{
int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1
int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int z; System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
}
}

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;

Operator Example Equivalent to


+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2

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]

7. Increment or decrement operator


Operator which perform operation only on one operand are called Unary operator.
1. Increment Operator
++ Operator increment the value of a variable by 1 is called increment operator.
 Pre-increment
++ is written before variable name. Value is incremented first then
incremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=++a;
System.out.println(i);
}
}OUTPUT: 6
Post-increment
 ++ is written after variable name. Value is assigned to expression after that the
value is increment.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a++;
System.out.println(i);
}
}OUTPUT:5
2. Decrement Operator
-- Operator decrement the value of a variable by 1 is called decrement operator.
 Pre-decrement
-- is written before variable name. Value is decremented first then
decremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=--a;
System.out.println(i);
}
}OUTPUT: 4
Aims Tutorial
Oriental Bank of Commerce P a g e | 23
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.

There are two data types available in Java


 Primitive Data Types
 Reference/Object Data Types

Primitive Data Types


Eight Primitive datatypes are predefined by the java.

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]

public static void main(String[] args)


{
Abc obj=new Abc();
Obj.display();
}
}
Output:10
 Each object has different data variables.
 Object are initialized using special methods are called constructor.

A class can contain any of the following variable types.


 Local variables − Variables which defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the method
and the variable will be destroyed when the method has completed.
class Test
{
public static void main(String[] args)
{
int a=10; Local variables
int b=20;
System.out.println(a+b);
}
}

 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
{

static int b=20;


public static void main(String[] args)
{

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]

Ex:-printing the array elements by using for loop


class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
declaration of two dimensional array:-
int[][] a;
int [][]a;
int a[][];
int []a[];
Ex:-
class Test
{
public static void main(String[] args)
{
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
}

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]

There are two types of methods:-


 Instance method
Method which are declare and defined inside a class and without static keyword and
called using object.
class Test
{
void display()
{
System.out.println("Aims Tutorial");
}

public static void main(String[] args)


{
Test t=new Test();
t.display();

}
}
 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");
}

public static void main(String[] args)


{

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]

Heap memory Stack memory


1) It is used to store the objects 1) It is used to store the function calls and
local variables.
2) We are getting outOfMemoryError 2) If the there is no memory in the stack to
store method calls or local variables the JVM
will throw the StackOverflowError.

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.

Rules for creating constructor


1. Constructor name must be same as its class name.
2. Constructor must have no return type.

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

Inheritance is the capability of acquire property(variables) and behaviors(methods)


of another class is called inheritance.
1. The main purpose of the inheritance is code extensibility whenever we are extending
automatically the code is reused.
2. In inheritance one class giving the properties and behavior and another class is taking the
properties and behavior.
3. Inheritance is also known as is-a relationship means two classes are belongs to the same
hierarchy.
4. By using extends keyword we are achieving inheritance concept.
5. In the inheritance the person who is giving the properties is called parent the person who
is taking the properties is called child.
6. To reduce length of the code and redundancy of the code sun peoples introducing
inheritance concept.

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]

class Marks extends Student


{
int m1, m2, m3;
void getMarks(int m1,int m2,int m3)
{
this.m1=m1;
this.m2=m2;
this.m3=m3;
}
}
class Result extends Marks
{
int total;
void process()
{
total=m1+m2+m3;
}
void print()
{
System.out.prinln(“Total result="+total);
}
public static void main(String[] args)
{
Result R;
R.read();
R.getMarks();
R.process();
R.print();

}
}
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

A. Method overloading ( Compile Time Polymorphism ,Early binding, Static binding)


 If any class has multiple method with same name but different parameters then they
are said to be overloaded.
 Function overloading allows to use the same name for different function to
performed either same or different action in the same class.
 Method overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of
arguments, then you can simply overload the method There are two types of
method overloading in java
1. By Changing number of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(int a, int b, int c)
{
System.out.prinln(a+b+c);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2,3,4);
}
}
2. By having different types of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(float a, float b)

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]

class Derived extends Base


{

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.

Difference between method overloading and method overriding in java


There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

Method overriding is used to provide


Method overloading is used to increase the readability of the specific implementation of the
1)
the program. method that is already provided by its
super class.

Method overriding occurs in two classes


2) Method overloading is performed within class. that have IS-A (inheritance)
relationship.

In case of method overloading, parameter must be In case of method overriding,


3)
different. parameter must be same.

Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.

In java, method overloading can't be performed by


changing return type of the method only. Return type Return type must be same or covariant
5)
can be same or different in method overloading. But you in method overriding.
must have to change the parameter.

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
{

abstract void m3();


}
Abstract class:-
class Test
{
abstract void m1();
abstract void m2();
abstract void m3();
}
abstract class Add
{
abstract void add(int a, int b);
}
class Cal extends Add
{
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);
}
}

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]

class Adaptor implements it


{
void m1()
{
}
void m2()
{
}
;
;
void m100()
{
}
};
class Test implements it
{
must provide the 100 methods implementation
};
class Test extends Adaptor
{
provide the implementation of required methods.
};

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

Super:- Super keyword is used to represent


1) Call the Super class variable.
2) Call the super class constructor.
3) Call the super class methods.

Super keyword is not required


class Parent
{
int a=10;
int b=20;
}
class Child extends Parent
{
int x=100;
int y=200;
void add(int i,int j)
{
System.out.println(i+j);
System.out.println(x+y);
System.out.println(a+b);
}
public static void main(String[] args)
{
Child c=new Child();
c.add(1000,2000);
}
}

Super keyword is required


class Test1
{
int a=10;
int b=20;
};
class Test extends Test1
{
int a=100;
int b=200;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b);
}

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]

public static void main(String[] args)


{
Test t=new Test();
t.add(1000,2000);
}
}

Command Line Arguments:-


The arguments which are passed from command prompt is called command line arguments.
We are passing command line arguments at the time program execution.
Ex1:-
class Test
{
public static void main(String[] args)
{
System.out.println(args.length);
System.out.println(args[0]);
System.out.println(args[1]);
}
}
Compilation : Javac Test.java
Execution : java Test a b c //a,b,c are the command line arguments
Output : 3
a
b

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]

public static void main(String[] args)


{
Test t=new Test();
t.m1();
System.out.println(t.a);
}
}
2. Default:-
 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 <default> modifier then we can access that class only
within that current package but not from outside of the package.
 Default access also known as a package level access.
 The default modifier in the java language is default.
class Test
{
void m1()
{
System.out.println("m1-method");
}
void m2()
{
System.out.println("m2-method");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
t.m2();
}
}
in the above program we are not providing any modifier for the methods and classes
at that situation the default modifier is available for methods and classes that is default
modifier. Hence we can access that methods and class with in the package.
3. Private:-
 Private is a modifier applicable for methods and variables. If a member
declared as private then we can access that member only from within the
current class.
 If a method declare as a private we can access that method only within the
class. it is not possible to call even in the child classes also.
class Test
{
private void m1()
{
System.out.println("we can access this method only with in this class");
}

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]

public static void main(String[] args)


{
Test t=new Test();
t.m1();
}
}
4. Protected :-
 If a member declared as protected then we can access that member with in the
current package anywhere but outside package only in child classes.
 But from outside package we can access protected members only by using
child reference. If we try to use parent reference we will get compile time error.
 Members can be accesses only from instance area directly i.e., from static area
we can’t access instance members directly otherwise we will get compile time
error.

Ex:-demonstrate the user defined packages and imports.


Aims project source file:-
package calculator;
public class Cal
{
protected void add(int a, int b)
{
System.out.println(a+b);
}
protected void sub(int a, int b)
{
System.out.println(a-b);
}
protected void multi(int a, int b)
{
System.out.println(a*b);
}
}

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.

Constructors of string class:-


1) String str=new String(java.lang.String);
This constructor takes the String as a argument.
Ex:-
String str=new String(“Aims”);
System.out.println(str);//Aims

2) Stirng str=new String(char[]);


This constructor take the array of characters as a argument.
Ex:-
char[] ch={'a','b','c','d'};
String str1=new String(ch);
System.out.println(str1); //abcd

3) String str=new String(char[] ,int ,int );


This contractor takes the array of characters with starting index and ending index. First int
represent the starting position Second int represent the ending position.
Ex:-
char[] ch={'a','b','c','d'};
String str1=new String(ch,1,3);
System.out.println(str1);//bcd
Ex:-
class Test
{
public static void main(String[] args)
{
String str="Manish";
System.out.println(str); //Manish
String str1=new String("Manish");
System.out.println(str1); //Manish
String str2=new String(str1);
System.out.println(str2);
char[] ch={'a','i','m','s'};
String str3=new String(ch);
System.out.println(str3); //aims
char[] ch1={'t','u','t','o','r','i','a',’l’};
String str4=new String(ch1,1,5);
System.out.println(str4); //utorial
}
}

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]

String is immutability nature:-


Once we are creating string object it is not possible to do the modifications on the existing
object is called immutability nature.
public class Test
{
public static void main(String[] args)
{
String str1=new String("Aims");
str1.concat("Tutorial”);
System.out.println(str1);
}
}
OUTPUT: Aims

String class Methods

Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 String concat(String str) concatenates specified string

4 int indexOf(int ch) returns specified char value index

5 String toLowerCase() returns string in lowercase.

6 String toUpperCase() returns string in uppercase.

7 String trim() removes beginning and ending spaces of this string.

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.

public class LengthExample


{
public static void main(String args[])
{
String s1="java";
String s2="python";
System.out.println("string length is: "+s1.length());
//10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());
//6 is the length of python 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.

public class StringLowerExample


{
public static void main(String args[])
{
String s1="AMIS TUTORIAL";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}

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.

public class StringUpperExample


{
public static void main(String args[])
{
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}

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.

public class StringTrimExample


{
public static void main(String args[])
{
String s1=" hello student ";
System.out.println(s1+"welcome");//without trim()
System.out.println(s1.trim()+"in aims");//with trim()
}

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

1. String Buffer is a class present in the java.lang package.


2. StringBuffer is a final class so it can’t be inherited.
3. StringBuffer is a mutable class so it is possible to change the content in the same location.
4. StringBuffer .equals() method is used for reference comparison.

What is mutable string


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

Constructors:-

1. StringBuffer sb=new StringBuffer();


2. StringBuffer sb1=new StringBuffer(int capacity);
3. StringBuffer sb2=new StringBuffer(String str);

1) StringBuffer append() method


The append() method concatenates the given argument with this string.

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]

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.

class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

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[])
{

StringBuffer sb=new StringBuffer("Hello");


sb.reverse();
System.out.println(sb);//prints olleH

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]

6) StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.

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");

System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2


}
}

Java StringBuilder class

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.

Important Constructors of StringBuilder class

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.

Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

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.

String class overrides the equals() method of Object class.


StringBuffer class doesn't override
3) So you can compare the contents of two strings by equals()
the equals() method of Object class.
method.

Difference between StringBuffer and StringBuilder

There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder

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.

Java toString() method


If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depends on your implementation.

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.

Data types and corresponding wrapper classes:-


byte ----- Byte
short ----- Short
int ----- Integer
long ----- Long
float ----- Float
double ----- Double
boolean ----- Boolean
char ------ Character

6) Byte,Short,Integer,Long,Float,Double these are child classes of Number class.

Constructors of wrapper classes:-


All most all wrapper classes contain two constructors:-
1. Integer i=new Integer(10);
2. Integer i=new Integer(“10”);

Primitives Wrapper classes Fallowing constructor


arguments
byte Byte Byte or String
short Short Short or String
int Integer Int or String
long Long Long or String
float Float Float or double or String
double Double double or String
char Character Char
Boolean Boolean Boolean or String

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]

Wrapper classes hierarchy

The main importance of wrapper classes:-


1. To convert a data types into the object means we are giving object from data types by
using constructor.
2. To convert String into the data types by using parsexxx() method
Utility methods:-
1. valueOf()
2. xxxValue()
3. parsexxx()

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.

Useful methods of OutputStream

Method Description

1) public void write(int)throws is used to write a byte to the current output


IOException stream.

2) public void write(byte[])throws is used to write an array of byte to the current


IOException output stream.

3) public void flush()throws IOException flushes the current output stream.

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.

Useful methods of InputStream

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.

3) public void close()throws


is used to close the current input stream.
IOException

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.

FileOutputStream class methods

Method Description

protected void finalize() It is sued to clean up the connection with the file output stream.

It is used to write ary.length bytes from the byte array to the


void write(byte[] ary)
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.

It is used to return the file descriptor associated with the


FileDescriptor getFD()
stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte


import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...(this is the output which show at consol after the execution of the program)
Aims Tutorial
Oriental Bank of Commerce P a g e | 67
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]

The content of a text file testout.txt is set with the data A.


testout.txt
A (this is data which is written by the program in the testout.txt file)

Java FileOutputStream example 2: write string


import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to Aims Tutorial.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to Aims Tutorial.
testout.txt
Welcome to Aims Tutorial.

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.

Java FileInputStream class methods

Method Description

It is used to return the estimated number of bytes that can be read


int available()
from the input stream.

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.

int read(byte[] b, int off,


It is used to read up to len bytes of data from the input stream.
int len)

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.

FileChannel It is used to return the unique FileChannel object associated with


getChannel() the file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

It is used to ensure that the close method is call when there is no


protected void finalize()
more reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

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]

Java FileInputStream example 2: read all characters


package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

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:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Packag


e\\testout.txt"));

Java BufferedOutputStream class constructors

Constructor Description

It creates the new buffered output stream which is


BufferedOutputStream(OutputStream os) used for writing the data to the specified output
stream.

It creates the new buffered output stream which is


BufferedOutputStream(OutputStream os,
used for writing the data to the specified output
int size)
stream with a specified buffer size.

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]

Java BufferedOutputStream class methods

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

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:

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.

The important points about BufferedInputStream are:


 When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
 When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class constructors

Constructor Description

It creates the BufferedInputStream and saves it


BufferedInputStream(InputStream IS)
argument, the input stream IS, for later use.

It creates the BufferedInputStream with a specified


BufferedInputStream(InputStream IS,
buffer size and saves it argument, the input stream IS,
int size)
for later use.

Java BufferedInputStream class methods

Method Description

It returns an estimate number of bytes that can be read from the


int available() input stream without blocking by the next invocation method for the
input stream.

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.

It repositions the stream at a position the mark method was last


void reset()
called on this input 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()

Example of Java BufferedInputStream


package com.javatpoint;
import java.io.*;
public class BufferedInputStreamExample
{
public static void main(String args[])
{
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1)
{
System.out.print((char)i);
}
bin.close();
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Aims Tutorial

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

It is used to create a buffered character output stream that


BufferedWriter(Writer wrt)
uses the default size for an output buffer.

BufferedWriter(Writer wrt, It is used to create a buffered character output stream that


int size) uses the specified size for an output buffer.

Class methods

Method Description

void newLine() It is used to add a new line by writing a line separator.

void write(int c) It is used to write a single character.

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.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Example of Java BufferedWriter


Let's see the simple example of writing the data to a text file testout.txt using Java
BufferedWriter.
package com.aims;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception
{
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to Aims Tutorial.");
buffer.close();
System.out.println("Success");

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.

Java BufferedReader class constructors

Constructor Description

It is used to create a buffered character input stream that uses


BufferedReader(Reader rd)
the default size for an input buffer.

BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses
size) the specified size for an input buffer.

Java BufferedReader class methods

Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int off,


It is used for reading characters into a portion of an array.
int len)

It is used to test the input stream support for the mark and reset
boolean markSupported()
method.

String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.

It repositions the stream at a position the mark method was last


void reset()
called on this input stream.

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)

It closes the input stream and releases any of the system


void close()
resources associated with the stream.

Java BufferedReader Example


In this example, we are reading the data from the text file testout.txt using Java
BufferedReader class.
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1)
{

System.out.print((char)i);

}
br.close();
fr.close();

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to Aims Tutorial.

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

 GUI stands for Graphical User Interface.


 It is a type of interface which allow user to interact with computer.
 It is used windows, menus , icons which can be manipulated by mouse.

What is GUI programming?


Programming application which used such as windows, menus, icon, labels, this type of
applications development are known as GII programming.

GUI programming in java


We can make GUI application using AWT(Abstract window toolkit), Swing , JavaFx , this is the
readymade API(application interface) which provide a rich set of classes and interface. So the
developer can developed GUI using these API’S.

AWT(Abstract Window tool kit)


 Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
 Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components are
using the resources of OS.
 The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
 It is a package in which the collection of classes and interfaces from which developer
can make GUI application

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]

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

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();

Characteristics of the Frame:-


1) When we create a Frame class object the Frame will be created automatically with the
invisible mode. To provide visible mode to following method.

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]

public void setVisible(boolean b)


where b==true means visible mode.
where b==false means invisible mode.
Ex: f.setVisible(true);

public void setSize(int width,int height)


Ex: f.setSize(400,500);

3) To provide title to the Frame explicitly we have to use the following method

public void setTitle(String Title)


Ex: f.setTitle("MyFrame");

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.

public void setBackground(color c)


Ex: f.setBackground(Color.red);

********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]

Preparation of the components

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();

3. To append the text into the TextArea.

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);

4. To set Text to the textarea we have to use the following method.

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]

6. To append the text into the TextArea.

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”);

2. To remove item from the choice based on the string.

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]

3. To remove the item based on the index position

ch.remove(2);

4. To remove the all elements

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:-

1) List l=new List();


It will creates the list by default size is four elements. And it is allow selecting the only one
item at a time.

2) List l=new List(3);

It will display the three items size and it is allow selecting the only single item.

3) List l=new List(5,true);

It will display the five items and it is allow selecting the multiple items.
Methods:-

1. To add the elements to the List we have to use following method.

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:-

1) Checkbox is a class present in java.awt package.

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:-

1) Checkbox cb1=new CheckBox();

cb1.setLable(“BTECH”);

2) Checkbox cb1=new CheckBox(“MCA”);

3) Checkbox cb3=new CheckBox(“BSC”,true);

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”);

2. To get the label of the checkbox we have to use fallowing method.

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]

Frame f=new Frame();


f.setVisible(true);
f.setTitle("Aims Tutorial");
f.setBackground(Color.red);
f.setSize(400,500);
Checkbox cb1=new Checkbox("BTECH",true);
f.add(cb1);
System.out.println(cb1.getLabel());
System.out.println(cb1.getState());
}
}
RADIO BUTTON:-

1) AWT does not provide any predefined support to create RadioButtons.

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.

By using two classes we create Radio Button those are


a)CheckBoxgroup
b)CheckBox
step 1:- Create CheckBox group object.
CheckBoxGroup cg=new CheckBoxGroup();
step 2:- pass Checkbox object to the CheckboxGroup class then the radio buttons are created.
CheckBox cb1=new CheckBox(“male”,cg,false);
CheckBox cb2=new CheckBox(“female”,cg,false);
Methods:-

1) To set status and to get status we have to use setState() and getState() methods.

String str=Cb.getState();
Cb.setState();

2) To get Label and to set Label we have to use following methods.

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]

CheckboxGroup cg=new CheckboxGroup();


Checkbox cb1=new Checkbox("male",cg,true);
f.add(cb1);
System.out.println(cb1.getLabel());
System.out.println(cb1.getState());
}
}
Layout Managers:-
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);
Label l1=new Label("user name:");
TextField tx1=new TextField();
Label l2=new Label("password:");
TextField tx2=new TextField();
Button b=new Button("login");
f.add(l1);
f.add(tx1);
f.add(l2);
f.add(tx1);
f.add(b);
}
}
Event delegation model:-

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.

5. To attach actions to the Frame component we need event delegation model.

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.

4. A listener is a interface which contain abstract methods and it is present in java.awt.event


package

5. The listeners are different from component to component.

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. ScrollBar is a class present in the java.qwt.package

2. By using ScrollBar we can move the Frame up and down.

ScrollBar s=new ScrollBar(int type)


Type of 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]

To create a HORIZONTAL ScrollBar:-


ScrollBar sb=new ScrollBar(ScrollBar.HORIZONTAL);
To get the current position of the scrollbar we have to use the following method.
public int getValue()
To create a VERTICAL ScrollBar:-
ScrollBar sb=new ScrollBar(ScrollBar.VERTICAL);
Appropriate Listeners for Components:-
GUI Component Event Name Listner Name Lisener Methods
____________ __________ ____________ _______________
1.Frame Window Event Window Listener
1.Public Void WindowOpened(WindowEvent e)
2.Public Void WindowActivated(WindowEvent e)
3.Public Void WindowDeactivated(WindowEvent e)
4.Public Void WindowClosing(WindowEvent e)
5.Public Void WindowClosed(WindowEvent e)
6.Public Void WindowIconfield(WindowEvent e)
7.Public Void WindowDeiconified(WindowEvent e)
2.Textfield ActionEvent ActionListener
1.Public Void Actionperformed(ActionEvent ae)
3.TextArea ActionEvent ActionListener
1.Public Void Actionperformed(ActionEvent ae)
4.Menu ActionEvent ActionListener
1.Public Void Actionperformed(ActionEvent ae)
5.Button ActionEvent ActionListener
1.Public Void Actionperformed(ActionEvent ae)
6.Checkbox ItemEvent ItemListener
1.Public Void ItemStatechanged(ItemEvent e)
7.Radio ItemEvent ItemListener
1.Public Void ItemStatechanged(ItemEvent e)
8.List ItemEvent ItemListener
1.Public Void ItemStatechanged(ItemEvent e)
9.Choice ItemEvent ItemListener
1.Public Void ItemStatechanged(ItemEvent e)
10.Scrollbar AdjustmentEvent AdjustmentListener
1.Public Void AdjustementValueChanged (AdjustementEvent e)
11.Mouse MouseEvent MouseListener
1.Public Void MouseEntered(MouseEvent e)
2.Public Void MouseExited(MouseEvent e)
3.Public Void MousePressed(MouseEvent e)
4.Public Void MouseReleased(MouseEvent e)
5.Public Void MouseClicked(MouseEvent e)
12.Keyboard KeyEvent KeyListener
1.Public Void KeyTyped(KeyEvent e)
2.Public Void KeyPressed(KeyEvent e)
3.Public Void KeyReleased(KeyEvent e)

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]

***PROVIDING CLOSING OPTION TO THE FRAME****


import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setSize(400,500);
this.setVisible(true);
this.setTitle("myframe");
this.addWindowListener(new myclassimpl());
}
}
class myclassimpl implements WindowListener
{
public void windowActivated(WindowEvent e)
{
System.out.println("window activated");
}
public void windowDeactivated(WindowEvent e)
{
System.out.println("window deactivated");
}
public void windowIconified(WindowEvent e)
{
System.out.println("window iconified");
}
public void windowDeiconified(WindowEvent e)
{
System.out.println("window deiconified");
}
public void windowClosed(WindowEvent e)
{
System.out.println("window closed");
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}

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]

public void windowOpened(WindowEvent e)


{
System.out.println("window Opened");
}
};
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
**PROVIDING CLOSEING OPTION TO 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("Aims Tutoiral");
this.addWindowListener(new Listenerimpl());
}
};
class Listenerimpl extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
};
class Demo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};

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]

l1=new Label("first value");


l2=new Label("second value");
l3=new Label("result");
tx1=new TextField(25);
tx2=new TextField(25);
tx3=new TextField(25);
b1=new Button("add");
b2=new Button("mul");
b1.addActionListener(this);
b2.addActionListener(this);
this.add(l1);
this.add(tx1);
this.add(l2);
this.add(tx2);
this.add(l3);
this.add(tx3);
this.add(b1);
this.add(b2);
}
public void actionPerformed(ActionEvent e)
{
try{
int fval=Integer.parseInt(tx1.getText());
int sval=Integer.parseInt(tx2.getText());
String label=e.getActionCommand();
if (label.equals("add"))
{
result=fval+sval;
}
if (label.equals("mul"))
{
result=fval*sval;
}
tx3.setText(""+result);
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
};
class Demo
{
public static void main(String[] args)
{
myframe f=new myframe();
}
};

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

1. Sun Micro Systems introduced AWT to prepare GUI applications.

2. awt components not satisfy the client requirement.

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.

Differences between awt and Swings:

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.

6. in awt for only window closing : windowListener

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.

a. Controller is a normal java class it will provide controlling.

b. View part provides presentation

c. Model part provides required logic.

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]

ButtonGroup bg=new ButtonGroup();


bg.add(rb1);
bg.add(rb2);
String[] listitems={"cpp","c","java"};
l=new JList(listitems);
String[] cbitems={"hyd","pune","bangalore"};
cb=new JComboBox(cbitems);
ta=new JTextArea(5,20);
b=new JButton("submit");
c.add(l1);
c.add(tf);
c.add(l2);
c.add(pf);
c.add(l3);
c.add(cb1);
c.add(cb2);
c.add(cb3);
c.add(l4);
c.add(rb1);
c.add(rb2);
c.add(l5);
c.add(l);
c.add(l6);
c.add(cb);
c.add(l7);
c.add(ta);
c.add(b);
}
}
class SwingDemo
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
}
};
----------------------------------------------------------------------------------------------------------------------------------------
********JCOLORCHOOSER***********
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ChangeListener
{
JColorChooser cc;
Container c;
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");

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

You might also like