JAVA - A Quick Reference
A quick guide to learn more about JAVA Programming. This covers the core concepts of JAVA with OOP concepts. This also covers swing programming.
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Java quick reference
1. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
JAVA PROGRAMMING – A QUICK REFERENCE
PART I
INTRODUCTION TO OBJECT ORIENTED CONCEPTS AND JAVA
PROGRAMMING
Definition:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
I. Characteristics of OOPs
1. Object
Definition:
Instance of class.
Contains address and has space in memory.
Object can communicate without knowing the details of each or data or codes.
It is a runtime entity.
Object has state (variable) and behaviour (method)
Example:
smallTable, rollingChair, bluePen, eBike, rolaxWatch
Pen blue, ink (State) – writing (behaviour)
2. Class
Definition:
Collection of object
Blueprint for object
Logical entity
Variable and methods
Example:
Table, Chair, Pen, Bike, Watch
Keyword:
class
3. Inheritance
Definition:
Ability to inherit the properties of one class to another class
Example:
University College UG Program B.Tech Program IT
Grand Parent Parent Child
2. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Keywords:
extends
implements
4. Polymorphism
Definition:
One task preformed in different ways
Method overloading and method overriding
Example:
Speaking
5. Abstraction
Definition:
Hiding the internal details and showing the functionality
Hiding the implementation details
Example:
Phone call
Keyword:
abstract
6. Encapsulation
Definition:
Binding code and data together into a single unit
Wrapping up of data
Hiding the data
Example:
Capsule
Keyword:
private
II. History of JAVA
James Goshling
1995
Sun Microsystems
Oracle Corporation
Greentalk Oak JAVA
JAVA island First coffee estate
3. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
III. Features of JAVA
1. Object Oriented Programming Language
a. Impure primitive data type
2. Platform Independent
a. Bytecode .class
b. Original code .java
c. Compiler = converts .java .class
d. Interpreter = converts .class .exe
3. Secured
a. No pointer
b. Class loader
c. Byte verifier
d. Security manager
e. Java virtual machine
4. Architectural Neutral
a. WORA – Write Once Read Any
5. Robust
6. Portable
7. Compiled and Interpreted
8. Multithreaded
9. Dynamic Programming
10. Distributed
11. High performance
12. Simple
IV. JAVA Source File Format
Section 1 – Documentation
// - Single line comment
/* ….. */ - Multi line comment
/**
* ..
*…
*/ - JavaDoc Generate HTML document
Section 2 – Package (optional)
Folder creation
Collection of class
Syntax:
4. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
package packagename;
Section 3 – Import (if needed)
Similar to #include in C language
Syntax:
import packagename.subpackagename.*;
Example:
import java.util.*
import java.io.*;
Section 4 – Interface (optional)
Multiple inheritance
Syntax:
interface interfacename{}
Section 5 – User defined class
Section 6 – Main Class
class classname
{
// Static variables and methods
public static void main(String args[])
{
// statements
}
}
V. Fundamentals of JAVA Programming
a. Hierarchy
separated using dot
Package
Class
Object
Variables and
Methods
Static
Members
Non - Static
Members
5. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Non static members Package.class.object.variable/method
Static members Package.class.variable/method
Example – Naming Conversion
Method printMethod()
Class PrintMethod
Object printmethod
Package printmethod
Constants PRINTMETHOD
b. Print Statements – Output Statement
println() Method
System Class
out object
System.out.println(“statements”)
System.out.println(“statements”+variable)
c. Input Statement
Package – io, util
import java.util.Scanner;
Scanner s1 = new Scanner(System.in);
next() – to get the string
nextInt() – to get integer
nextLine() – to get string with space
nextFloat() – to get floating point
nextChar() – to get character
6. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
VI. Primitive Data Types:
Data Type Size Default Value Range
byte 8 0 -128..127
short 16 0 -32,768..32,767
int 32 0 -2,147,483,648.. 2,147,483,647
long 64 0
-9,223,372,036,854,775,808..
9,223,372,036,854,775,807
float 32 0.0f 3.4e-0.38.. 3.4e+0.38
double 64 0.0d 1.7e-308.. 1.7e+308
char 16 „ „ (space) Complete Unicode Character Set
Boolean 1 FALSE True, False
VII. Variables:
Variables in Java refer to the name of the reserved memory area. You need variables
to store any value for the computational or reference purpose.
There are 3 types of variable in Java:
1. Local variable – within a block – with a method
2. Instance variable – within a class
3. Static variable – Class variable
Syntax:
datatype variableName;
Initialization of Variable:
datatype variableName = value;
Data Conversion:
The process of changing a value from one data type to another type is known as data type
conversion. Data Type conversion is of two types:
1. Widening: The lower size datatype is converted into a higher size data type without
loss of information.
2. Narrowing: The higher size datatype is converted into a lower size data type with a
loss of information.
7. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
VIII. Java Operators:
Operator Type Operators
Arithmetic +, – , *, ? , %
Assignment =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=
Bitwise ^, &, |
Logical &&, ||
Relational <, >, <=, >=,==, !=
Shift <<, >>, >>>
Ternary ?:
Unary ++x, –x, x++, x–, +x, –x, !, ~
IX. Decision Making Statements:
Selection statements used when you need to choose between alternative actions
during execution of the program
1. if statement
Syntax:
if (condition)
{
Expression
}
2. if-else statement
Syntax:
if (condition)
{
Expression
}
else
{
Expression
}
3. switch statement
Syntax:
switch (var)
{
case 1:
expression;
break;
default:
expression;
8. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
break;
}
X. Iterative Statements:
Iterative statements are used when you need to repeat a set of statements until the
condition for termination is not met.
1. for loop
Syntax:
for (condition)
{
Expression
}
2. for each loop
Syntax:
for (int i: someArray) {}
3. while loop
Syntax:
while (condition)
{
Expression
}
4. do while loop
Syntax:
do
{
Expression
} while(condition);
XI. Classes
A class in Java is a blueprint which includes all your data. A class contains fields
(variables) and methods to describe the behaviour of an object.
Syntax:
<access specifier> class <ClassName> {
member variables // class body
methods
}
Objects
An object is a major element in a class which has a state and behaviour. It is an
instance of a class which can access your data. The „new‟ keyword is used to create the
object.
a. Predefined Class
i. Scanner
9. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
ii. System
iii. String
iv. Date
v. Arrays
vi. Random
b. Main Class
c. User defined Class
Modularity
Inheritance
Polymorphism
Syntax:
class ClassName
{
// Variable declaration
// Method definition
}
Syntax: Declaring and Initializing an object
ClassName objectName = new ClassName();
XII. Access Modifiers
Scope of the class members
Types of access modifiers
o private – within a block – {}
o public – anywhere
o protected – inheritance
o default – no keyword
Access Modifier within class within package
outside package
by subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
10. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
XIII. Methods
Method Definition:
Syntax:
<access modifier> returnType methodName(Parameters)
{
…. // statements
}
Accessor method / Getter: It accesses only the instance field without modification.
public returntype getFieldName()
{
return fieldName;
}
Mutator / Setter: It changes the instance fields
public void setFieldName(return-type variable)
{
fieldName=variable;
Types of Method Definition:
a. Method with no argument and no return type
b. Method with argument and no return type
c. Method with no argument and with return type
d. Method with argument and with return type
XV. Constructors
A constructor is a block of code that initializes a newly created object. It is similar to
a method in Java but doesn‟t have any return type and its name is same as the class name.
There are 2 types of constructors:
1. Default Constructor (No-Argument Constructor)
2. Parameterized Constructor
Constraints:
a. Class name and Constructor name should be same
b. No return type for a constructor
c. Constructor can have n number of parameters
11. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
d. Constructors are similar to methods but it is invoked automatically during the object
creation
Default Constructor
Syntax:
<access specifier> class ClassName{
public ClassName(){
}
}
Parameterized Constructor
Syntax:
<access specifier> class ClassName{
public ClassName(arguments){
}
}
XVI. Arrays
Definition: Group of similar data items
Advantages:
1. Code Optimization
2. Random Access
Disadvantage:
1. Limit
Types of Array:
1. Single Dimensional Array
2. Multi-Dimensional Array
Single Dimensional Array:
Array Index – 0 to n-1
Name of the array = a
0 1 2 3 4 5 6 7
100 179 234 543 678 123 108 54
12. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Array Initialization:
Syntax:
datatype variable_name[] = {values separated with commas};
Example:
int a[] = {100, 179, 234, 543, 678, 123, 108, 54};
Array Declaration and Creation:
Syntax:
datatype variable_name[] = new datatype[size];
Example: double first[] = new double[100];
Declaration: datatype variable_name[];
Creation: variable_name = new datatype[size];
Two Dimensional Array:
Syntax:
datatype variable_name[][] = new datatype[row][col];
Predefined class – Arrays
Package – util
Predefined Methods: - Static methods
1. sort
2. binarySearch
3. copyOf
4. toString
XVII. Strings:
Creating a string object:
There are two ways to create String object:
1. By string literal
String s = “Hello”
2. By new keyword
String s = new String(“Hello”);
Methods:
char charAt(int index) - Returns the character at the specified index.
13. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
int compareTo(String anotherString) - Compares two strings lexicographically.
int compareToIgnoreCase(String str) - Compares two strings lexicographically,
ignoring case differences.
String concat(String str) - Concatenates the specified string to the end of this string.
boolean equals(Object anObject) - Compares this string to the specified object.
int indexOf(int ch) - Returns the index within this string of the first occurrence of the
specified character.
int length() - Returns the length of this string.
String replace(char oldChar, char newChar) - Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.
String[] split(String regex) - Splits this string around matches of the given regular
expression.
boolean startsWith(String prefix) - Tests if this string starts with the specified prefix.
String substring(int beginIndex) - Returns a new string that is a substring of this
string.
String toLowerCase() - Converts all of the characters in this String to lower case using
the rules of the default locale.
String toString() - This object (which is already a string!) is itself returned.
String toUpperCase() - Converts all of the characters in this String to upper case using
the rules of the default locale.
String trim() - Returns a copy of the string, with leading and trailing whitespace
omitted.
14. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
PART II
I. Inheritance
Inheritance is the property of a child/derived/subclass which allows it to inherit the
properties(data members) and functionalities(methods) from its parent/base/superclass.
All objects have the Object class as their top parent.
Methods can be overridden but attributes cannot.
To call a parent class constructor, super() is used.
Java supports 3 types of inheritance:
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Advantage:
• Reusability of an existing class
• Derived class that has own properties along with base class properties.
Syntax:
class SubClassName extends BaseClassName
{
Expressions;
}
Single Inheritance
In this, a class inherits the properties of a single parent class.
Syntax
Class A{
//your parent class code
}
Class B extends A {
//your child class code
}
15. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Multi Level Inheritance
In multi-level inheritance, one class has more than one parent class but at different levels of
inheritance.
Syntax:
Class A{
//your parent class code
}
Class B extends A {
//your code
}
Class C extends B {
//your code
}
Hierarchical Inheritance
In hierarchical inheritance, one parent can have one or more child/sub/derived classes.
Syntax:
Class A{
//your parent class code
}
Class B extends A {
//your child class code
}
Class C extends A {
//your child class code
}
16. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Note:
It is enough to create the object for the child class
Child class can access all the members in the parent class directly
Parent class members can be accessed using child class object
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
Note:
Super() should be written inside the derived class constructor as the first statement
II. POLYMORPHISM
Definition: Object taking more than one form
Types:
1. Static polymorphism – Method Overloading – Static binding – Compile time
polymorphism
2. Dynamic polymorphism – Method Overriding – Dynamic binding – Runtime
polymorphism
Static Polymorphism:
Method overloading: Same method name with different number of arguments and return type
Syntax:
void eating(int a)
{
}
void eating(int a, int b)
{
17. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
}
void eating(String str)
{
}
Dynamic Polymorphism
Same method signature (method name, arguments, return type)
Inheritance
Dynamic binding
SuperClassName object = new SubClassName();
// Dynamic Polymorphism
// Super Class
class DynamicPoly
{
void display()
{
System.out.println("Hello");
}
}
// Sub Class
class SubDynamicPoly extends DynamicPoly
{
void display()
{
System.out.println("Welcome");
}
}
// Sub Class
class SubDynamic extends SubDynamicPoly
{
void display()
{
System.out.println("Hai.....");
}
}
public class Main{
public static void main(String args[])
{
DynamicPoly dy;
dy = new DynamicPoly();
dy.display();
18. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
dy = new SubDynamicPoly();
dy.display();
dy = new SubDynamic();
dy.display();
}
}
III. Interface:
An interface is a collection of abstract methods. A class implements an interface,
thereby inheriting the abstract methods of the interface.
Declaring Interfaces
The interface keyword is used to declare an interface.
Syntax:
interface interfacename
{
//Any number of final, static fields
//Any number of abstract method declarations
}
Variable Declaration (Constants):
Syntax:
public static final datatype variablename = value;
Method Declaration (Abstract Method):
Syntax:
public abstract returntype methodname(Argument(s));
Properties:
• An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
19. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
• Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
• Methods in an interface are implicitly public.
IV. Access Modifier
Final
1. Final Class – Class Cannot be subclassed.
2. Final Method – Method Cannot be overridden.
3. Final Variable – Variable Value cannot be changed (Constant)
Static
1. Static Method – It is also called as Class method. It cannot refer to nonstatic variables
and methods of the class. Static methods are implicitly final and invoked through the
class name.
2. Static Variable – It is also called as Class variable. It has only one copy regardless of
how many instances are created. Accessed only through the class name.
Abstract
Key Points:
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the
method.
Syntax:
abstract class ClassName{
abstract returnType methodName(arguments){
}
}
V. Inner Class (Nested Class)
=> Class within Class
=> Purpose - Hide the data and implementation
Syntax:
class OuterClassName
20. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
{
class InnerClassName
{
}
}
Types of inner class
a. Member inner class
b. Anonymous inner class
c. Local inner class
b. Static inner class
a. Member inner class
Syntax:
class OuterClassName
{
class InnerClassName
{
}
}
Note:
1. Outer class members can be accessed directly by the inner class
2. Inner class members cannot be accessed directly in the outer class
3. To access the inner class members in outer class, object has to be created for inner class
4. To access the inner class members outside the outer class
i. Create an object for outer class
ii. OuterClassName.InnerClassName ic = outerClassObject.new InnerClassName();
b. Anonymous Inner Class
=> no name
c. Local Inner Class
=> Define the inner class within the method definition
d. Static Inner Class
=> Inner class will be static
21. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
PART III
I. Exception
=> Runtime error
=> Unexpected termination
=> Exception handlers
Predefined class
Throwable - Super Interface
Exception - Super Class
Sub-class - IOEXception, ArrayIndexOutOfBoundsException, NullPointerException,
InputMismatchException
Types of Exception:
1. Checked exception
2. Unchecked exception
Exception Handlers:
a. Try
b. Catch
c. Finally
d. Throw
e. Throws
a. The try Statement:
Syntax:
try {
// Suspected statements
}
22. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
b. The catch Statement:
Syntax:
try {
. . .
}
catch (ExceptionClassName e) {
// Statements
}
c. The finally Clause:
Syntax:
try {
// statements that throw exceptions
}
catch(<exception>) {
// do stuff
}
finally {
– // code here runs whether or not catch runs
}
d. The throws clause:
Syntax:
public static void main(String[] args) throws IOException {
….
}
e. The throw statement:
Syntax:
throw exceptionObject ;
User Defined Exception
Syntax:
class MyException extends Exception{
}
23. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Exception Description
ArithmeticException Caused by exceptional conditions like divide by zero
ArrayIndexOfBoundsException
Thrown when an array is Exception accessed beyond its
bounds
ArrayStoreException Thrown when an incompatible type is stored in an array
ClassCastException Thrown when there is an invalid cast
IllegalArgumentException
Thrown when an inappropriate argument is passed to a
method
IllegalMonitorStateException
Illegal monitor operations such as waiting on an unlocked
thread
IllegalThreadStateException
Thrown when a requested operation is incompatible with
the current thread state.
IndexOutOfBoundsException Thrown to indicate that an index is out of range.
NegativeArraySizeException Thrown when an array is created with negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a number.
SecurityException Thrown when security is violated.
ClassNotFoundException Thrown when a class is not found.
CloneNotSupportedException
Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Thrown when a method does not have access to a class.
InstantiationException
Thrown when an attempt is made to instantiate an
abstract class or an interface.
InterruptedException
Thrown when a second thread interrupts a waiting,
sleeping, or paused thread.
II. Generic Programming
Definition:
=> operates on object with different type except the primitive type
Wrapper Classes
1. Integer
2. Float
3. Double
4. Character
Type parameter
1. E - Element
2. T, S, U, V - Type
3. K - Keys
4. N - Number
24. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Generic class
Syntax: Generic class creation
class ClassName <Type Parameter>
{
// instance variable
// method definition
}
Syntax: Creating object for generic ClassName
ClassName<WrapperClass> objectName = new ClassName<WrapperClass>();
Generic Method:
Syntax:
<Type Parameter> return_type methodName(list of args)
{
}
Wild Card Types:
? - unknown type
Restrictions in Wildcard:
a. It cannot be used as type argument
b. It cannot be used for generic class instance creation
c. It cannot be used as a super type
Inheritance in generic
Upper bound and lower bound
Upper Bound
<Type_parameter extends SuperClass>
Lower Bound
<Type_parameter super Type_parameter>
25. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
III. Collection Framework
Java Collections : Interface
a. Iterator interface :
Iterator is an interface that iterates the elements.
It is used to traverse the list and modify the elements.
Methods:
public boolean hasNext() – This method returns true if the iterator has more elements.
public object next() – It returns the element and moves the cursor pointer to the next element.
public void remove() – This method removes the last elements returned by the iterator.
b. Java collections: List
A List is an ordered Collection of elements which may contain duplicates.
It is an interface that extends the Collection interface.
Types:
ArrayList
LinkedList
Vectors
i. ArrayList
Syntax:
ArrayList object = new ArrayList ();
26. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Methods:
boolean add(Collection c) - Appends the specified element to the end of a list.
void add(int index, Object element) - Inserts the specified element at the specified
position.
void clear() - Removes all the elements from this list.
int lastIndexOf(Object o) - Return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.
Object clone() - Return a shallow copy of an ArrayList.
Object[] toArray() - Returns an array containing all the elements in the list.
void trimToSize() - Trims the capacity of this ArrayList instance to be the list‟s
current size.
ii. Linked List
Linked List is a sequence of links which contains items.
Each link contains a connection to another link.
Syntax:
Linkedlist object = new Linkedlist();
Methods:
boolean add(Object o) - It is used to append the specified element to the end of the
vector.
boolean contains(Object o) - Returns true if this list contains the specified element.
void add (int index, Object element) - Inserts the element at the specified element in
the vector.
void addFirst(Object o) - It is used to insert the given element at the beginning.
void addLast(Object o) - It is used to append the given element to the end.
int size() - It is used to return the number of elements in a list
boolean remove(Object o) - Removes the first occurrence of the specified element
from this list.
int indexOf(Object element) - Returns the index of the first occurrence of the
specified element in this list, or -1.
int lastIndexOf(Object element) - Returns the index of the last occurrence of the
specified element in this list, or -1.
27. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
c. Java Collections: Sets
A Set refers to a collection that cannot contain duplicate elements.
It is mainly used to model the mathematical set abstraction.
Set has its implementation in various classes such as HashSet, TreeSetand
LinkedHashSet.
i. HashSet
Java HashSet class creates a collection that uses a hash table for storage.
Hashset only contain unique elements and it inherits the AbstractSet class and
implements Set interface.
Methods
boolean add(Object o) - Adds the specified element to this set if it is not already
present.
boolean contains(Object o) - Returns true if the set contains the specified element.
void clear() - Removes all the elements from the set.
boolean isEmpty() - Returns true if the set contains no elements.
boolean remove(Object o) - Remove the specified element from the set.
Object clone() - Returns a shallow copy of the HashSet instance: the elements
themselves are not cloned.
Iterator iterator() - Returns an iterator over the elements in this set.
int size() - Return the number of elements in the set.
d. Java Map Interface
A Map in Java is an object that maps keys to values and is designed for the faster
lookups.
Data is stored in key-value pairs and every key is unique.
Each key maps to a value hence the name map.
These key-value pairs are called map entries.
Characteristics of Map Interface
The Map interface is not a true subtype of Collection interface, therefore, its
characteristics and behaviors are different from the rest of the collection types.
It provides three collection views – set of keys, set of key-value mappings and
collection of values.
28. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
A Map cannot contain duplicate keys and each key can map to at most one value.
Some implementations allow null key and null value (HashMap and LinkedHashMap)
but some does not (TreeMap).
The Map interface doesn‟t guarantee the order of mappings, however, it depends on
the implementation. For instance, HashMap doesn‟t guarantee the order of mappings
but TreeMap does.
AbstractMap class provides a skeletal implementation of the Java Map interface and
most of the Map concrete classes extend AbstractMap class and implement required
methods.
Methods
public put(Object key, Object value) - This method inserts an entry in the map
public void putAll(Map map) - This method inserts the specified map in this map
public Object remove(Object key) - It is used to delete an entry for the specified key
public Set keySet() - It returns the Set view containing all the keys
public Set entrySet() - It returns the Set view containing all the keys and values
void clear() - It is used to reset the map
public void putIfAbsent(K key, V value) - It inserts the specified value with the
specified key in the map only if it is not already specified
public Object get(Object key) - It returns the value for the specified key
public boolean containsKey(Object key) - It is used to search the specified key from
this map
29. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
PART IV
I. IO Streams
Package:
java.io.*
OutputStream Class Methods:
Method Description
public void write(int)throws
IOException:
is used to write a byte to the current output
stream.
public void write(byte[])throws
IOException:
is used to write an array of byte to the current
output stream.
public void flush()throws
IOException:
flushes the current output stream.
public void close()throws IOException: is used to close the current output stream.
InputStream Class Methods:
Method Description
public abstract int read()throws
IOException:
reads the next byte of data from the input stream.It
returns -1 at the end of file.
public int available()throws
IOException:
returns an estimate of the number of bytes that can
be read from the current input stream.
public void close()throws IOException: is used to close the current input stream.
30. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
File Methods:
Methods Description
getName() To retrieve file name of a given file pointer
Return value: String
getPath() To retrieve current path of a file
Return value: String
getAbsolutePath() To retrieve entire file path location of a file
Return value: String
exists() To check if the file is exists
Return value: boolean
It returns true if file exist otherwise false
canRead() To check if the file has read permission
Return value: boolean
It returns true if file has permission otherwise false
canWrite() To check if the file has write permission
Return value: boolean
It returns true if file has permission otherwise false
length() To find number of bytes that are stored in a file
Return value: int
31. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
II. Swing Components
MVC Architecture
JFrame Class:
Package:
javax.swing.*
Constructor:
JFrame() - Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) - Creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank title.
JFrame(String title) - Creates a new, initially invisible Frame with the specified
title.
JFrame(String title, GraphicsConfiguration gc) - Creates a JFrame with the
specified title and the specified GraphicsConfiguration of a screen device.
Methods:
void setDefaultCloseOperation(int operation) - Sets the operation that will happen by
default when the user initiates a "close" on this frame.
void setLayout(LayoutManager manager) - Sets the LayoutManager.
setVisible(boolean aFlag): It makes the component visible or invisible.
JButton Class:
Package:
javax.swing.*
Constructors:
JButton() - It creates a button with no text and icon.
JButton(String s) - It creates a button with the specified text.
JButton(Icon i) - It creates a button with the specified icon object.
32. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Methods:
void setText(String s) - It is used to set specified text on button
String getText() - It is used to return the text of the button.
void setEnabled(boolean b) - It is used to enable or disable the button.
void setIcon(Icon b) - It is used to set the specified Icon on the button.
Icon getIcon() - It is used to get the Icon of the button.
void setMnemonic(int a) - It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) - It is used to add the action listener to this
object.
JTextField Class:
Package:
javax.swing.*
Constructors:
JTextField() - Creates a new TextField
JTextField(String text) - Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) - Creates a new TextField initialized with the
specified text and columns.
JTextField(int columns) - Creates a new empty TextField with the specified number
of columns.
Methods:
void setText(String s) - It is used to set specified text on button
String getText() - It is used to return the text of the button.
void setEnabled(boolean b) - It is used to enable or disable the button.
void addActionListener(ActionListener a) - It is used to add the action listener to this
object.
JLabel Class
Constructors
Constructor Description
JLabel() Creates a JLabel instance with no image and with an
empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int
horizontalAlignment)
Creates a JLabel instance with the specified text, image,
and horizontal alignment.
33. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
Methods
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will
display.
void
setHorizontalAlignment(int
alignment)
It sets the alignment of the label's contents along the X
axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.
JPasswordField Class
Constructors
Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the
specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the
specified text.
JPasswordField(String text, int
columns)
Construct a new JPasswordField initialized with the
specified text and columns.
Methods
Method Description
isEditable() Returns a boolean value indicating whether or not a text
field is editable
setEditable() Passing True enables text to be edited, while False
disables editing. The default is True.
addActionListener() Registers an ActionListener object to receive action
events from a text field
getEchoChar() Returns the character used for echoing
getColumns() Returns the number of columns in a text field
setEchoChar() Sets the echo character for a text field
getText() Returns the text contained in the text field
setText() Sets the text for a text field
JTextArea Class
Constructors
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
34. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
JTextArea(int row, int
column)
Creates a text area with the specified number of rows and
columns that displays no text initially.
JTextArea(String s, int row,
int column)
Creates a text area with the specified number of rows and
columns that displays specified text.
Methods
Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int
position)
It is used to insert the specified text on the specified
position.
void append(String s) It is used to append the given text to the end of the
document.
JCheckbox Class
Constructors
Constructor Description
JCheckBox() Creates an initially unselected check box button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text,
boolean selected)
Creates a check box with text and specifies whether or not it is
initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
JRadioButton Class
Constructors
Constructor Description
JRadioButton() Creates an unselected radio button with no
text.
JRadioButton(String s) Creates an unselected radio button with
specified text.
JRadioButton(String s, boolean
selected)
Creates a radio button with the specified text
and selected status.
Methods
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
35. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
button.
void addActionListener(ActionListener
a)
It is used to add the action listener to this
object.
JComboBox Class
Constructors
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?>
items)
Creates a JComboBox that contains the elements in the
specified Vector.
Methods
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
void
addActionListener(ActionListener a)
It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
JList
Constructors
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary>
dataModel)
Creates a JList that displays elements from the specified,
non-null, model.
Methods
Methods Description
Void
addListSelectionListener(ListSelectio
nListener listener)
It is used to add a listener to the list, to be notified
each time a change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an
array of objects.
36. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
JOptionPane Class
Methods
Methods Description
JDialog createDialog(String title) It is used to create and return a new parentless
JDialog with the specified title.
static void showMessageDialog
(Component parentComponent, Object
message)
It is used to create an information-message
dialog titled "Message".
static void showMessageDialog
(Component parentComponent, Object
message, String title, int messageType)
It is used to create a message dialog with
given title and messageType.
static int showConfirmDialog
(Component parentComponent, Object
message)
It is used to create a dialog with the options
Yes, No and Cancel; with the title, Select an
Option.
static String showInputDialog
(Component parentComponent, Object
message)
It is used to show a question-message dialog
requesting input from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.
Menus:
A JMenuBar instance is first created as:
JMenuBar mb = new JMenuBar();
The JMenuBar instance is added to a frame using the setMenuBar() method of the
Frame class as follows:
setJMenuBar(mb);
Individual menus are created (instances of the JMenu class) and added to the
menu bar with the add() method
Add the Menu items using JMenuItem class
Layout Managers:
Border Layout:
Constructors:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
Constants:
public static final int NORTH
37. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
GridLayout Class:
Constructors:
GridLayout() - Creates a grid layout with a default of one column per component,
in a single row.
GridLayout(int rows, int cols) - Creates a grid layout with the specified number of
rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap) - Creates a grid layout with the
specified number of rows and columns.
FlowLayout Class
Constructors:
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Constants:
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Listeners
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
38. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Mouse Listener
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
39. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
Window Listener
Sr.
no.
Method signature Description
1. public abstract void
windowActivated (WindowEvent
e);
It is called when the Window is set to be an
active Window.
2. public abstract void windowClosed
(WindowEvent e);
It is called when a window has been closed as
the result of calling dispose on the window.
3. public abstract void windowClosing
(WindowEvent e);
It is called when the user attempts to close the
window from the system menu of the window.
4. public abstract void
windowDeactivated (WindowEvent
e);
It is called when a Window is not an active
Window anymore.
5. public abstract void
windowDeiconified (WindowEvent
e);
It is called when a window is changed from a
minimized to a normal state.
6. public abstract void
windowIconified (WindowEvent e);
It is called when a window is changed from a
normal to a minimized state.
7. public abstract void windowOpened
(WindowEvent e);
It is called when window is made visible for
the first time.
Key Listener
Sr.
no.
Method name Description
1. public abstract void keyPressed
(KeyEvent e);
It is invoked when a key has been
pressed.
2. public abstract void keyReleased
(KeyEvent e);
It is invoked when a key has been
released.
3. public abstract void keyTyped
(KeyEvent e);
It is invoked when a key has been
typed.
Adapter Classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
40. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
PART V
I. Multithreading
=> Multitasking
=> It is a process of executing multiple threads simultaneously
=> threads - small program/task - lightweight component / sub-process
=> Example - Simple calculator - four operations - add, sub, mul, div - all these 4 operations
as threads
- there are 4 threads - independent operations
Advantage
1. saves time
2. Independent
Support
1. Thread class
2. Runnable interface
Life cycle of Thread
Stages
1. New born
2. Active
2. Blocked / Waiting
4. Timed Waiting
5. Terminated
Implementation of Thread
Two ways:
1. By extending the Thread class
2. By implementing the runnable interface
java.lang.*
Methods - Thread Class
1. start()
41. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
2. run()
3. lock()
4. unlock()
5. wait()
6. notify()
7. sleep(millisec)
8. stop()
9. notifyAll()
10. getName()
11. setName(String str)
12. getPriority()
13. setPriority(int priority)
14. suspend()
15. resume()
16. isAlive()
17. currentThread()
Method - Runnable interface
1. run()
a. Extending the Thread Class
The steps for creating a thread by using the first mechanism are:
1. Create a class by extending the Thread class and override the run() method:
class MyThread extends Thread {
public void run() {
// thread body of execution
}
}
2. Create a thread object:
MyThread thr1 = new MyThread();
3. Start Execution of created thread:
thr1.start();
b. Implementing the Runnable Interface
The steps for creating a thread by using the second mechanism are:
42. JAVA Programming – A Quick Reference
Prepared by Dr. R. Arthy, AP/IT, Kamaraj College of Engineering and Technology
1. Create a class that implements the interface Runnable and override run() method:
class MyThread implements Runnable {
…
public void run() {
// thread body of execution
}
}
2. Creating Object:
MyThread myObject = new MyThread();
3. Creating Thread Object:
Thread thr1 = new Thread(myObject);
4. Start Execution:
thr1.start();
Reference:
www.javatpoint.com
https://www.edureka.co/