Java Programming Basics and Concepts
Java Programming Basics and Concepts
JAVA -SE
1
Program File:Compile &Run Cycle
•Only 1 public outer class inside a single Java File, Name of the java file would be
same as of Public Class. Only Public class can be accessed directly from outside of
the package. No other class of a package . When members (Fields+ Method) are
private they can not be accessed from outside the class body.
•When members are protected , they can be accessed from any class of the same
package and child class from other package. When members are public , they can be
accessed from any class of any package. When members are package-private they are
accessible only from the class of same package.
Methods operate on an object's internal state and serve as
the primary mechanism for object-to-object communication.
Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data
encapsulation. For example, if the bicycle only has 6 gears, a
method to change gears could reject any value that is less
4 than 1 or greater than 6.
package : Grouping of Class as per their usage and domain e.g. Package
[Link] & Package [Link]. Just like various folders in Computer Drive C:\,
D: \[Link] also help us avoid class name collision when we use same class
name in different packages.
Compiling .java file
Running .java file
The Java compiler automatically
imports two entire packages for
each source file:
(1) The [Link] package and
(2) the current package (the
package for the current file).
F Q N: Fully Qualified Name::To use class of same name exist in different
packages we need to use fully qualified name of class for creating object
new package name . class name ().
To use a public package member from outside its package.1. Refer to the member by its fully
qualified name. [Link] the package [Link] the member's entire package with.*.
Importing nested class: first import enclosing class then import entire package of enclosing
class with .*; import [Link]; import [Link].*;
importing
5 static members from Math class:import static [Link].*;
Keywords in Java
Java Keywords
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while true false
null
objects define their interaction with the outside world through the
methods that they expose. Methods form the object's interface with the
outside world; the buttons on the front of television set, for example, are
the interface between human and the electrical wiring on the other side of
6 its plastic casing.
Data Types
By default, floating point numbers are double in
Java. In order to store them into float variable,
you need to cast them explicitly or suffix with 'f' .
float x=3.5 ; (error - default is double)
float x=3.5 f ; (no error).
Assigning a value of one type to a variable of
another type is known as Type Casting.
Example : int x = 65; char c = (char)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit),Narrowing Casting
package myjava;
public class Driver {
public static void main(String[] args) {
int i=9786; [Link]("%020d%n",i);
[Link]("%20d",i);}
Printing Date in Java
9
Math class in Java
Basic Math Methods
Random Numbers:: Method Description
The random() method returns a double abs(double d),
float abs(float f) Returns the absolute value of the
pseudo-randomly selected number int abs(int i) argument.
long abs(long lng)
between 0.0 and 1.0. The range double min(double arg1, double arg2)
includes 0.0 but not 1.0. In other float min(float arg1, float arg2)
int min(int arg1, int arg2)
Returns the smaller of the two arguments.
words: 0.0 <= [Link]() < 1.0. long min(long arg1, long arg2)
double max(double arg1, double arg2)
To get a number in a different range, float max(float arg1, float arg2)
Returns the larger of the two arguments.
you can perform arithmetic on the int max(int arg1, int arg2)
long max(long arg1, long arg2)
value returned by the random
Exponential and Logarithmic Methods
method. For example, to generate an Method Description
integer between 0 and 9, you would double log(double d) Returns the natural logarithm of the argument.
double pow(double base, Returns the value of the first argument raised to the
write: double exponent) power of the second argument.
int number = (int)([Link]() * double sqrt(double d) Returns the square root of the argument.
double toDegrees(double d)
10); double toRadians(double d) Converts the argument to degrees or radians.
package myjava;
public class Driver {
public static void main(String[] args) {
[Link](Math.log10(1000));
[Link]([Link]()*10);}}
3.0
10
0.9637996890441303
Reference Variable Vs Pointer
Pointers can point nowhere ( NULL ), whereas a reference always
refers to an object. difference between
pointers and references is that a pointer is an
independent variable and can be assigned new address values;
whereas a reference once assigned can never refer to any new object
.However Java references are bound to one object at a time but can
be assigned other objects while the program executes.
Pointers: A pointer is a variable that holds memory address of another
variable. A pointer needs to be de referenced with * operator to access
the memory location it points to.
References : A reference variable is an alias, that is, another name for
an already existing variable. A reference, like a pointer is also
implemented by storing the address of an object.
A reference can be thought of as a constant pointer with automatic
indirection, i.e. the compiler will apply the * operator for you.
11
Object Creation in Java
Popular ways to create an object in Java
• new Keyword:
• clone() method
• newInstance() method of the Class class
• newInstance() method of the Constructor class
• Deserialization
Nested Inner Class Object Creation
Inner in= Outer [Link] Inner(); Normal access modifier
There's a special null literal that can be used as a value for any reference
type. null may be assigned to any variable, except variables of primitive
type. A literal called a class literal, formed by taking a type name and
appending ".class"; for example, [Link]. This refers to the object (of
12 type Class) that represents the type itself.
Object creation thru Clone method of Object Class
13
Shallow Copy Vs Deep Copy
Feature Shallow Copy Deep Copy
References Shares references Creates independent
to objects copies of objects
Changes in Affect the copied Do not affect the copied
Original Object object object
Complexity Simpler to More complex to
implement implement
Performance Faster Slower
14
Shallow Copy
17
Pass by Value
reference variable as parameter
Create copy of references.
It only affects the local copy of the ref within that method. The
reassignment does not affect the original ref outside the method.
19
Object creation thru
newInstance () of Class class
Object creation thru
newInstance() of Constructor class
20
Serialization and Deserialization in Java
Serialization: it is a mechanism of converting the state of an object into a byte stream .
byte stream created is platform independent. To make a Java object serializable we implement
the [Link] interface.(Marker Interface).
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
The objects can be read (reconstituted) using an ObjectInputStream. The ObjectOutputStream class
contains writeObject() method for serializing an Object. Once object is serialized then it can be
used ,[Link] save/persist state of an object.2. To travel an object across a network.
Deserialization : it is the reverse process where the byte stream is used to recreate the actual Java
object in memory. The ObjectInputStream class contains readObject() method for
deserializing an object.
21
1. Only non-static data members are saved via Serialization process.
2. Static data members and transient data members are not saved via
Serialization [Link],
if we don’t want to save value of a non-static data member then make it
transient.
3. Constructor of object is never called when an object is deserialized.
4. SerialVersionUID The Serialization runtime associates a version number
with each Serializable class called a SerialVersionUID, which is used during
Deserialization to verify that sender and receiver of a serialized object have
loaded classes for that object which are compatible with respect to
serialization. If the receiver has loaded a class for the object that has different
UID than that of corresponding sender’s class, the Deserialization will result
in an InvalidClassException. A Serializable class can declare its own UID
explicitly by declaring a field [Link] must be static, final and of type long.
[Link] The serialver is a tool that comes with JDK. It is used to get
serialVersionUID number for Java classes.
22
23
24
hashCode()
•Objects that are equal must have the same hash code within a running process
•Unequal objects must have different hash codes – WRONG!
•Objects with the same hash code must be equal – WRONG!
•The contract allows for unequal objects to share the same hash code, such as the “A“
and “µ” objects
•Whenever you implement equals, you MUST also implement hashCode
•An object’s hash code allows algorithms and data structures to put objects into
compartments.
•Whenever two different objects have the same hash code, we call this a collision. A
collision is nothing critical, it just means that there is more than one object in a single
bucket, so a HashMap lookup has to look again to find the right object. A lot of
collisions will degrade the performance of a system, but they won’t lead to incorrect
results.
25
The equals() Method of Object Class
The equals() method compares two objects for equality and returns true if they are equal.
The equals() method provided in the Object class uses the identity operator (==) to
determine whether two objects are equal. For primitive data types, this gives the correct
result. For objects, however, it does not. The equals() method provided by Object tests
whether the object references are equal—that is, if the objects compared are the exact same
object . To test whether two objects are equal in the sense of equivalency (containing the same
information), you must override the equals() method. Here is an example of a Book class that
overrides equals():
public class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) return
[Link]((Book)[Link]()); else return false; } }
Consider this code that tests two instances of the Book class for equality:
Book firstBook = new Book("0201914670"); Book secondBook = new
Book("0201914670"); if ([Link](secondBook)) { [Link]("objects are
equal"); } else { [Link]("objects are not equal"); }
This program displays objects are equal even though firstBook and secondBook reference two
distinct objects. They are considered equal because the objects compared contain the same
ISBN number. You should always override the equals() method if the identity operator is not
appropriate for your class.
26 Note: If you override equals(), you must override hashCode() as well.
Initialization blocks in Java
Instance variable Initialization other than Constructor option
•Initializer blocks for instance variables:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor.
•Static Initialization Blocks
Instance variables can be initialized in constructors,
where error handling or other logic can be used. To provide the
same capability for class variables, the Java programming language
includes static initialization blocks.
A static initialization block is a normal block of code enclosed in
braces, { }, and preceded by the static keyword.
static { Code …. }
27
The instanceof operator compares an
Operators Precedence object to a specified of type. We can use
unary ++expr --expr +expr -expr ~ ! it to test if an object is an instance of a
particular class, an instance of a
multiplicative */% subclass, or an instance of a class that
additive +- implements a particular interface.
class Parent {}
shift << >> class Child extends Parent implements
relational < > <= >= instanceof MyInterface {}
interface MyInterface {}
equality == !=
public class Demo {public static void
bitwise AND & main(String[] args)
bitwise exclusive OR ^ {Parent obj1 = new Parent();
Parent obj2 = new Child();
bitwise inclusive OR | [Link]("obj1 instanceof
logical AND && Parent: "+(obj1 instanceof Parent));}}
package myjava;
public class Driver {public static void main(String[] args) {
Character c=' ';
[Link]([Link](c));
}}//true
Escape Sequences
Escape Sequence Description
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
31
\\ Insert a backslash character in the text at this point.
Constructors: All classes have at least one constructor. If a class does not
explicitly declare any, the Java compiler automatically provides a no-argument
constructor, called the default constructor.A class contains constructors that are
invoked to create objects from the class blueprint. a constructor is called by
the new operator: it creates space in memory for the object and initializes its
[Link] new operator requires a single, postfix argument: a call to a
constructor. The name of the constructor provides the name of the class to
instantiate. The new operator returns a reference to the object it created.
•This default constructor calls the class parent's no-argument constructor, or
the Object constructor if the class has no other parent.
• Name is same as class name. It has no return type. It has2 types
(default, parameterized).Constructors are not members, so they
are not inherited by subclasses, but the constructor of the super
class can be invoked from the subclass.
•Constructor is used to initialize an object when parameters are
passed to it .
32
The javap command disassembles a class file. The javap
command displays information about the fields, constructors and
methods present in a class file.
33
Garbage Collection:An object is eligible for garbage collection when there
are no more references to that object. Remember that a program can have
multiple references to the same object; all references to an object must be
dropped before the object is eligible for garbage collection.
The Java runtime environment has a garbage collector that periodically frees
the memory used by objects that are no longer referenced. The garbage
collector does its job automatically when it determines that the time is right.
Inheritance Rules:
• Each Class is allowed to have 1 direct super class and each super class can
have unlimited Subclasses. Multiple Inheritance not allowed.
• Private members of Super class are not accessible by Subclass directly
however can be accessed indirectly.
• Members with default access modifier in Super class are also
not accessible by sub classes of other packages.
Inheritance Types in JAVA:
• Single Level, Multilevel, Hierarchical
34 signature (name, plus the number and the type of its parameters)
Multi Level Inheritance
35
.class literal in java
class literal is a special syntax in Java that allows you to obtain a Class object
representing a specific class, interface, array, or primitive type at runtime. It's
formed by appending .class to the name of the type.
[Link]
where Type can be : A class name (e.g., [Link], [Link])
An interface name (e.g., [Link])
An array type (e.g., int[].class, String[].class)
A primitive type (e.g., [Link], [Link], [Link])
Class<String> stringClass = [Link];
Class<int[]> intArrayClass = int[].class;
Class Object: The Class object provides information about the class at runtime, such
as its name, methods, fields, and constructors.
Reflection: Class literals are essential for reflection, which allows you to
dynamically inspect and manipulate classes at runtime.
Generics:You can use generics with class literals to specify the type of the Class
object.
36
Reflection API(to access private field outside class)
•For every type of object, the Java virtual machine instantiates an immutable
instance of [Link], which provides methods to examine the runtime
properties of the object including its members and type information. it is the
entry point for all of the Reflection APIs.
•The entry point for all reflection operations is [Link]. With the
exception of [Link], none of the classes
in [Link] have public [Link] get to these classes, it is
necessary to invoke appropriate methods on Class.
•Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
•The [Link] and [Link] packages provide classes for java reflection.
•Using reflection, one can break the principles of encapsulation. It is possible
to access the private methods and fields of a class using reflection. Thus,
reflection may leak important data to the outside world, which is dangerous.
For example, if one access the private members of a class and sets null value to
it, then the other user of the same class can get the NullReferenceException,
and this behaviour is not expected.
37
Accessing Field Method and Constructor using Reflection API
38
Polymorphism in Java :(method overloading ,overriding and hiding)
Method Overloading in JAVA:
• If 2 methods of a class have same name but different signature , it is called
method overloading in Java. Both methods may exist in same class, or both are
in subclass or 1 in super class and 1 in sub class.
41
super Key word :
•If a sub class method overrides super class method , we can invoke overridden method of
super class in subclass by using super key word .
•It also avoid name conflict between member variable of super class & subclass.
Class A
{
public void f1()
{}
}
Class B extends A
{
public void f1()
{ super.f1();
}
Class C
{
Public static void main (String args [ ])
{
B obj =new B();
Obj.f1();
}
}
42
Calling super class constructor and passing argument using Scanner
46
Interface with field ,abstract method, default method and static method
47
Local Classes
We can define a local class inside any block A local class in a method body,
a for loop, or an if clause. A local class is declared locally within a block of
Java code, rather than as a member of a class. ... The defining characteristic of a
local class is that it is local to a block of code. Like a local variable, a local class is
valid only within the scope defined by its enclosing block.
Anonymous Class :
•They are like local classes except that they do not have a name. Use them if you
need to use a local class only once, and for which only a single object is created.
•While local classes are class declarations, anonymous classes are expressions,
which means that we define the class in another [Link] anonymous class
is an expression. The syntax of an anonymous class expression is like the
invocation of a constructor, except that there is a class definition contained in a
block of code.
•An anonymous class has access to the members of its enclosing [Link] cannot
declare static initializers or member interfaces in an anonymous class. An
anonymous class can have static members provided that they are constant
variables.
48
Local Classes, Anonymous Classes,
Lambda Expressions & Nested Classes
•Local class: Use it if we need to create more than one instance of a
class, access its constructor.
•Anonymous class: Use it if we need to declare fields or additional
methods in JDK 10 or later else will have single overriden method of
parent class/interface.
•Lambda expression: Use it if we need a simple instance of a functional
interface[Functional interface can declare only single method ]
and none of the preceding criteria apply (for example, do not need a
constructor, a named type, fields, or additional methods).
•Nested class:Use a non-static nested class (or inner class) if we require
access to an enclosing instance's non-public fields and methods.
•Use a static nested class if we don't require this access.
49
Anonymous Class in Java: Class without any name
51
Lambda Expression in Java
Interface with Single function declaration is called Functional Interface
52
Arrays : int []arr=new int[5] ;// here arr is reference variable .
• int []arr=new int [] { 1,4,7,8,9}; //no need to mention element count.
•We can store primitive type or reference type in an array in Java.
•length variable also exist inside Array body .
53
2D Array : Array of arrays{{},{}}
54
Jagged Array in Java
55
String Class
“String Object is Immutable in Java ”: Popular Methods in String Class:
toUpperCase(),toLowerCase(), equals(),equalsIgnoreCase(), compareTo()
57
Regular Expression
• A regular expression is a sequence of characters that forms a
search pattern ,while search for data in a text, we can use this
search pattern to describe what we are searching for.
• A regular expression can be a single character, or a more
complicated pattern.
• Regular expressions can be used to perform all types of text
search and text replace operations.
• The package includes the following classes:[Link]
• Pattern Class - Defines a pattern (to be used in a search)
• Matcher Class - Used to search for the pattern
• PatternSyntaxException Class - Indicates syntax error in a regular
expression pattern
58
Regular Expression Patterns
Flags in the compile() method
Pattern.CASE_INSENSITIVE - The case of letters will be ignored when
performing a search.
[Link] - Special characters in the pattern will not have any special
meaning and will be treated as ordinary characters when performing a search.
Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE
flag to also ignore the case of letters outside of the English alphabet
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9
59
Quantifier Description
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s
60 Find a whitespace character
Find String
61
String replacement
62
Generics
Generics enable types (classes and interfaces) to be parameters when defining classes,
interfaces and methods. Much like the more familiar formal parameters used in method
declarations, type parameters provide a way for you to re-use the same code with different
inputs. The difference is that the inputs to formal parameters are values, while the inputs to
type parameters are types. Type parameter is also called Type Variable.
Stronger type checks at compile time.<> is called Diamond .
A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which
can be difficult to find. A type variable can be any non-primitive type you specify: any class
type, any interface type, any array type.
64
Wild card
In generic code, the question mark (?), called
the wildcard, represents an unknown type. The
wildcard can be used in a variety of situations:
as the type of a parameter, field, or local
variable; sometimes as a return type (though it
is better programming practice to be more
specific).
There are 3 types of wildcards in Java: Upper
bounded wildcards, Lower Bounded Wildcards,
65 and Unbounded Wildcards.
Upper
Upper
Upper bound-Generics
bound
bound -Generics
Example-Generics
66
Lowerbound
Lower bound-Generics
-Generics
67
Data Collection Framework : The Collections Framework is a
sophisticated hierarchy of interfaces and
classes that provide state-of-the-art
technology for managing groups of objects.
•Add objects to collection
•Remove objects from collection
•Search for an object in collection
•Retrieve/get object from collection
•Iterate through the collection
68
Collection
Lists:
The List interface extends Collection to define an ordered collection with
duplicates allowed. ArrayList, LinkedList and vector are classes
implementing List interface.
Sets:
The Set interface extends the Collection interface. It will make sure that an
instance of Set contains no duplicate elements.
Queues:
A queue is a first-in, first-out data structure. Elements are appended to the end
of the queue and are removed from the beginning of the queue.
Maps:
A map is a container that stores the elements along with the
keys. The keys are like indexes.
69
ArrayList
ListIterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements. boolean hasNext(): Returns true if there is at
least one more element in the collection being traversed.
Object next() :This method returns the next object in the collection.
•The default constructor creates an ArrayList with a capacity of 10 items.
•ArrayList names = new ArrayList();
•ArrayList names = new ArrayList(int size);
Method Purpose
public void add(Object) public void add(int, Adds an item to an ArrayList. The default version adds an item
Object) at the next available location; an overloaded version allows you
to specify a position at which to add the item
71
Passing another List as argument , inserting
element on particular index,and Sorting
using [Link]() method
72
ArrayList of Array type objects and Student type objects
73
Filter Collections data using stream().filter() method
74
Linked list : It has a concept of nodes and data. Here Node is storing
values of next node while data stores the value it is holding.
LinkedList may iterate more slowly than an ArrayList, but it's a good choice
when you need fast insertion and deletion.
Constructor:
LinkedList( );
LinkedList(Collection<? extends E> c)
Method Description
76
Comparison between ArrayList and Linked List
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked list to
store the elements. store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is removed ArrayList because it uses a doubly linked list, so no
from the array, all the other elements are shifted in shifting is required in memory.
memory.
3) An ArrayList class can act as a list only because LinkedList class can act as a list and queue both
it implements List only. because it implements List and Deque interfaces.
4)ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
5) The memory location for the elements of an The location for the elements of a linked list is
ArrayList is contiguous. not contiguous.
6) Generally, when an ArrayList is initialized, a There is no case of default capacity in a LinkedList.
default capacity of 10 is assigned to the ArrayList. In LinkedList, an empty list is created when
a LinkedList is initialized.
7) To be precise, an ArrayList is a resizable LinkedList implements the doubly linked list of the
array. list interface.
77
HashSet: A hash table stores information by using a mechanism called
hashing. In hashing, the informational content of a key is used to determine a
unique value, called its hash code. The hash code is then used as the index at
which the data associated with the key is stored. The transformation of the key
into its hash code is performed automatically.
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object
being inserted, so the more efficient your hashCode() implementation the
better access performance. A Set cannot contain duplicate elements.
HashSet() // Default constructor, the default capacity is 16.
HashSet(Collection c) // It creates HashSet from collection c.
HashSet( int capacity) // it creates HashSet with initial capacity mentioned
Method Purpose
public boolean add(Object o) Adds an object to a HashSet if already not present in HashSet.
79
Queue Interface
The Java Queue interface, [Link] represents a data structure designed to
have elements inserted at the end of the queue, and elements removed from the
beginning of the queue.
It represents an ordered sequence of objects just like a Java List.
Following Queue implementations in the Java Collections API:
• [Link]
• [Link]
Linked List is a pretty standard queue implementation. Elements in the queue are
stored internally in a standard linked list data structure. This makes it fast to insert
elements at the end (tail) of the list, and remove elements from the beginning
(head) of the list.
•PriorityQueue stores its elements internally according to their natural order (if
they implement Comparable).
80
ArrayDeque Methods
METHOD DESCRIPTION
add(Element e) The method inserts a particular element at the end of the deque.
addFirst(Element e) The method inserts particular element at the start of the deque.
contains(Obj) The method checks whether a deque contains the element or not
remove(Object o) Removes a single instance of the specified element from this deque.
81
removeFirst() The method returns the first element and also removes it
Array Deque Implementation
82
PriorityQueue
Method Description
boolean add(object) It is used to insert the specified element into this queue
and return true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
• The Priority queue does not follow the FIFO rule rather arrange the
elements based on their priority.
•Priority Queue can store comparable objects ( class which implements
Comparable interface) to arrange them in correct priorities.
83
Priority Queue Program
86
Exception Handling
• 2 Types of exceptions : checked & unchecked exceptions.
• Programmer exceptions are raised using throw keyword and handled
within catch block other blocks are try & finally .
• For each try block there may be 1 or >1 catch block but only 1 finally block.
• catch block and finally block must always appear in conjunction (put together) .
•Throwable Class define Constructor to set messages and a method getmessage() to retrieve
an exception.
87
Handle runtime errors and continue
executing other parts of the program.
88
Type of Exception Handling
• Default throw and default catch built in (program ends).
• Default throw and programmer catch
• Programmer throw and default catch
• Programmer throw and Programmer catch.
Below 3 blocks can be used inside any method.
• Try block {} where exception may occur.
• Catch block{} to ensure program does not end after exception.
• Finally {} :Guaranteed execution irrespective of exception in program.
Default throw & programmer catch::
89
Programmer throw and default catch
When programmer think it should be treated as an exception.
syntax : throw<throwable instance> ;exception reference must be of
throwable class or its subclass. A details message can be passed to
constructor () when exception object is created .
90
Programmer throw & Programmer Catch & Finally Block
91
Checked Exception
• Compile time exception -to be checked at compile time itself
Forces programmers to deal with the exception that may be thrown (File
handling).Programmer must manage with try & catch block or inform Java to
handle it. throws keyword is required only to convince compiler and usage of
throws keyword does not prevent abnormal termination of program . By
throws keyword we can provide information to java about the exception.
Syntax : method name () throws <Exception 1> ,<Exception 2>
92
Checked Exception Program : throws keyword /try catch block
93
Checked Exception Program : Use of try & catch block
instead of throws keyword :
94
File Handling
Create Read Update Delete Operation(CRUD)
95
File Handling: Writing to File
96
Writing to the File in Append Mode
97
File Handling: Reading from File
A read() method reads the next byte of the data from the input stream and
returns int value in the range of 0 to 255 (ASCII Code). If no byte is available
98because the end of the stream has been reached, returned value is -1.
Threads :: A Thread is a very light-weighted process that allows a
program to operate more efficiently by running multiple tasks simultaneously.
• Independent path of execution within a program , many threads can run
concurrently (virtually) within a program and multi threading means two or
more tasks running concurrently in a program .
2 ways to create threads in JAVA.
•By extending Thread class ([Link])
• By Implementing Runnable interface
• Process: create a thread , attach a code(s) to a thread and executing thread.
Thread ends with execution of run method.
Threads States :New ,Runnable , Not Runnable , Dead
•Another benefit of using thread is that if a thread gets an exception or an
error at the time of its execution, it doesn't affect the execution of the other
threads. All the threads share a common memory and have their own stack,
local variables and program counter. When multiple threads are executed in
parallel at the same time, this process is known as Multithreading.
99
Running 2 threads concurrently
100
Synchonized &[Link]( mili seconds) method
101
GUI:Graphical User Interface allow user to interact with screen using graphical
component (visual indicators like picture) rather than normal text.
API : Application Programming Interface:[Link](Abstract Windowing Toolkit) [Link]
Classes in AWT:
[Link] package contains the core AWT graphics [Link] Component classes such as
Button ,TextField and [Link] Container classes such as Frame,Panel and Dialog .
•Layout Manager classes such as Flow Layout, Grid Layout, Border Layout.
•Custom Graphics classes such as Graphics,Color and Font.
AWT events:
[Link] package supports event handling .
•Event classes such as ActionEvent,MouseEvent,KeyEvent,WindowsEvent.
•Event Listener classes such as ActionListener,MouseListener,KeyListener,WindowsListener.
Container:
A Frame is the top level container of AWT GUI .
•A Frame has a title bar containing an icon,a title, min /max and close button and optional
menu bar and content display area.
•A Panel is a rectangular area or partition used to group GUI components.
•All components like Button ,Label must be kept inside a container, to do that Every container
has an method called add ( Button b).
102
Frame Panel and Components
103
Applet :: An applet is a Java program that runs in a Web browser.
import [Link].*;
import [Link].*;
public class AppletTest extends Applet{
public void init(){
//initialization
}
public void start (){
//start or resume execution
}
public void stop(){
//suspend execution
{
public void destroy(){
//perform shutdown activity
}
public void paint (Graphics g){
[Link]("A simple Applet", 20, 20);
}
104
}
Swing:It is a GUI widget toolkit for Java. It is part of Oracle's Java
Foundation Classes – an API for providing a graphical user interface for Java
programs. Swing was developed to provide a more sophisticated set of GUI
components than the earlier Abstract Window Toolkit.
Swing Event Handling :
•Event describes the change in state of any object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or Dragging a mouse, etc.
Component of Handling:3 main components
•Events : An event is a change in state of an object.
•Events Source : Event source is an object that generates an event.
•Listeners : A listener is an object that listens to the event.
•A source generates an Event and send it to one or more listeners registered with the source.
Once event is received by the listener, they process the event and then return
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent
105 KeyListener
To retain IconImage in JAR File ( put image folder under root directory of
project and add this folder to project class path using Build path option).
Project=new=>folder(for images)
=>folder name=>finish.
Project=>Build path=>configure build path=>Source
=>Add Folder=>click the folder to be included
=>OK=>Apply and Close.
106
Jar File at Desktop of a Computer for Customer Use::
Project =>export=> Select=> Java=>Runnable JAR file=> Launch
Configuration(Driver-class Name) &Export Destination path =>finish
107
Adding Font Style and Color
108
Digital Watch
109
Java Practice
110
Variable length Argument in Java
Definition : public void MethodName(type ... variableName) { }
a. only one var-length parameter should be present in a single definition.
b. A method can have variable length parameters with other parameters too, but one should
ensure that there exists only one varargs parameter that should be written last in the
parameter list of the method declaration.
c. static void fun2(String str, int ...numbers)
111
Armstrong numbers in the range of 0 and 500. An Armstrong number is a
number such that the sum of its digits raised to the third power is equal to the number itself.
For example, 371 is an Armstrong number, since 3**3 + 7**3 + 1**3 = 371.
Armstrong number program
x^3+y^3+z^3=xyz
113
Strong Number between 1-100000
114
Prime numbers from 0-50 (number not divisible by other than itself and 1)
Number can not be divided by 0 and all are divisible by 1
therefore 0 and 1 are excluded from prime list
115
Prime Number Program
116
Fibonacci Series in Java
117
Thanks!
118