Professional Documents
Culture Documents
An interface can have methods and variables just like the class but the methods declared in
interface are by default abstract (only method signature, no body).
Also, the variables declared in an interface are public, static & final by default.
The class that implements interface must implement all the methods of that interface.
We can’t instantiate an interface in java. That means we cannot create the object of an
interface.
Also, java programming language does not allow you to extend more than one class,
However you can implement more than one interfaces in your class.
interface MyInterface class Demo implements MyInterface
{ {
/* This class must have to implement both the abstract
/* compiler will treat them as: methods
* else you will get compilation error
* public abstract void method1(); */
public void method1()
* public abstract void method2(); {
*/ System.out.println("implementation of method1");
}
public void method1(); public void method2()
{
public void method2(); System.out.println("implementation of method2");
} }
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}
Interface variables must be initialized at Inside any implementation class, you
the time of declaration otherwise cannot change the variables declared in
compiler will throw an error. interface because by default, they are
public, static and final.
Class that implements any interface must implement all the methods of that
interface, else the class should be declared abstract.
Packages in java
A package as the name suggests is a pack(group) of classes, interfaces and other
packages.
In java we use packages to organize our classes and interfaces. We have two types of
packages in Java: built-in packages and the packages we can create (also known as
user defined package).
Better Organization: Again, in large java projects where we have several hundreds
of classes, it is always required to group the similar types of classes in a
meaningful package name so that you can organize your project better and when
you need something you can quickly locate it and use it, which improves the
efficiency.
Name Conflicts: We can define two classes with the same name in different
packages so to avoid name collision, we can use packages
You can create a class Calculator inside a package name letmecalculate.
To create a class inside a package, declare the package name in the first statement in your
program. A class can have only one package declaration.
Calculator.java file created inside a package letmecalculate
package letmecalculate;
Lets say I have created another package inside letmecalculate and the sub package name is
multiply. So if I create a class in this subpackage it should have this package declaration in the
beginning:
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;
}
}
Now if I need to use this Multiplication class I have to either import the package like this:
import letmecalculate.multiply;
Exception handling in java
An Exception is an unwanted event that interrupts the normal flow of the
program.
The good thing about exceptions is that they can be handled in Java. By
handling the exceptions we can provide a meaningful message to the user
about the issue rather than a system generated message, which may not be
understandable to a user.
There can be several reasons that can cause a program to throw exception.
For example: Opening a non-existing file in your program, Network
connection problem, bad input data provided by user etc.
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled
them or not. If these exceptions are not handled/declared in the program, you will get
compilation error. For example, SQLException, IOException, ClassNotFoundException
etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has
handled them or not but it’s the responsibility of the programmer to handle these
exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Java handles exceptions by using following keywords:
try
catch
finally block
Throw and
throws clause
Try block Catch block
A catch block is where you handle the exceptions, this
The try block contains set of block must follow the try block. A single try block can
statements where an exception can have several catch blocks associated with it. You can
occur. A try block is always followed catch different exceptions in different catch blocks.
by a catch block, which handles the When an exception occurs in try block, the
corresponding catch block that handles that particular
exception. exception executes. For example if an arithmetic
A try block must be followed by catch exception occurs in try block then the statements
enclosed in catch block for arithmetic exception
blocks or finally block or both. executes.
Output:
class Example
{ Number should not be divided by zero
public static void main(String args[]) { This is finally block
try{ Out of try-catch-finally
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }
The throws does the same thing that try-catch But suppose you have several such methods that can
does but there are some cases where you would cause exceptions, in that case it would be tedious to
prefer throws over try-catch. For example:
write these try-catch for each method. The code will
Lets say we have a method myMethod() that has
statements that can throw either become unnecessary long and will be less-readable.
ArithmeticException or NullPointerException, in
this case you can use try-catch as shown below: One way to overcome this problem is by using throws
like this: declare the exceptions in the method signature
public void myMethod() using throws and handle the exceptions where you are
{ calling this method by using try-catch.
try {
// Statements that might throw an exception Another advantage of using this approach is that you will
} be forced to handle the exception when you call this
catch (ArithmeticException e) { method, all the exceptions that are declared using
// Exception handling statements throws, must be handled where you are calling this
method else you will get compilation error.
}
catch (NullPointerException e) {
// Exception handling statements
}
}
import java.io.*;
public void myMethod() throws ArithmeticException, NullPointerException
class ThrowExample {
{
void myMethod(int num)throws IOException,
// Statements that might throw an exception
ClassNotFoundException{
}
if(num==1)
public static void main(String args[]) {
throw new IOException("IOException Occurred");
try {
else
myMethod();
throw new
} ClassNotFoundException("ClassNotFoundException");
catch (ArithmeticException e) { }
// Exception handling statements }
}
catch (NullPointerException e) { public class Example1{
// Exception handling statements public static void main(String args[]){
} try{
} ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}}
Output:
String literal
Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive.
boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case
insensitive comparison.
int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.
boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or
not.
boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.
boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified
fromIndex..
int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
int indexOf(String str): This method returns the index of first occurrence of specified substring str.
int lastindexOf(String str): Returns the index of last occurrence of string str.
String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the
specified index.
String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and
ends with the character at endIndex.
String concat(String str): Concatenates the specified string “str” at the end of the string.
String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar
with the newChar.
String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
public String intern(): This method searches the specified string in the memory pool and if it is found then it
returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.
public boolean isEmpty(): This method returns true if the given string has 0 length. If the length of the specified
Java String is non-zero then it returns false.
public static String join(): This method joins the given strings using the specified delimiter and returns the
concatenated Java String
String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given
regular expression “regex” with the specified replacement string.
String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular
expression regex with the replacement string.
String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given
regular expression. limit is a result threshold here.
String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold
limit.
String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given
locale.
public static String format(): This method returns a formatted java String
String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character
array.
static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments –
initial offset of subarray and length of subarray.
void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest
array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
static String valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.
boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.
boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the
extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of
resulted bytes.
byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.
int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the
character itself.
boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It
throws NullPointerException of ‘s’ is null.
String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
Multithreading in java
A thread is a light-weight smallest part of a process that can run concurrently
with the other parts(other threads) of the same process.
Threads are independent because they all have separate path of execution
that’s the reason if an exception occurs in one thread, it doesn’t affect the
execution of other threads. All threads of a process share the common memory.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and
again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state. A thread in the blocked state is unable to perform any execution. If there are
a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to
determine which thread to choose and which one to reject, and the chosen thread is then
given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left
earlier.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead
thread.
Creating a thread in Java
There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.
When two or more threads need access to a shared resource there should
be some way that the resource will be used only by one resource at a time.
The process to achieve this is called synchronization.
2) wait() tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The
highest priority thread will run first.
public class JoinExample {
class MyClass implements Runnable{
public static void main(String[] args) {
Thread th1 = new Thread(new MyClass(), "th1"); @Override
Thread th2 = new Thread(new MyClass(), "th2"); public void run() {
Thread th3 = new Thread(new MyClass(), "th3"); Thread t = Thread.currentThread();
// Start first thread immediately System.out.println("Thread started: "+t.getName());
th1.start(); try {
/* Start second thread(th2) once first thread(th1) is dead */ Thread.sleep(4000);
try { th1.join(); } } catch (InterruptedException ie) {
catch (InterruptedException ie) {
ie.printStackTrace();
}
ie.printStackTrace(); }
System.out.println("Thread ended: "+t.getName());
th2.start();
/* Start third thread(th3) once second thread(th2) * is dead */
}
try { th2.join(); }
} catch (InterruptedException ie) { ie.printStackTrace(); Output:
}
th3.start(); Thread started: th1
// Displaying a message once third thread is dead Thread ended: th1
try { th3.join(); Thread started: th2
} catch (InterruptedException ie) { Thread ended: th2
ie.printStackTrace(); }
Thread started: th3
Thread ended: th3
System.out.println("All three threads have finished execution");
All three threads have finished execution
}
}
Java AWT https://www.youtube.com/watch?v=QEMBucYSi9s+notes from this only
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating
Graphical User Interface (GUI) for java programs.
Java AWT calls native platform (Operating systems) subroutine for creating
components such as textbox, checkbox, button etc.
For example an AWT GUI having a button would have a different look and feel across
platforms like windows, Mac OS & Unix, this is because these platforms have different
look and feel for their native buttons and AWT directly calls their native subroutine
that creates the button.
AWT components are considered heavy weight because they are being generated by
underlying operating system (OS). For example if you are instantiating a text box in
AWT that means you are actually asking OS to create a text box for you.
AWT hierarchy
Components and containers
All the elements like buttons, text fields, scrollbars etc are known as
components.
In AWT we have classes for each component as shown in the above diagram. To
have everything placed on a screen to a particular position, we have to add
them to a container.
As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window,
Frame, Dialog and Panel.
Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist
without an associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components. An instance of the Panel class provides a container to which to
add components.
Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing
an application in AWT.
We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.
import java.awt.*;
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");
// setting button position on screen
b.setBounds(50,50,50,50);
//adding button into frame
add(b);
//Setting Frame width and height
setSize(500,300);
//Setting the title of Frame
setTitle("This is my First AWT example");
//Setting the layout for the Frame
setLayout(new FlowLayout());
/* By default frame is not visible so we are setting the visibility
to true to make it visible. */
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}}
import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
//adding label to the frame
fr.add(lb);
//Creating Text Field
TextField t = new TextField();
//adding text field to the frame
fr.add(t);
//setting frame size
fr.setSize(500, 300);
//Setting the layout for the Frame
fr.setLayout(new FlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}}
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event.
Event handling has three main components,
• Events: An event is a change in state of an object.
A source produces an event and sends it with the source to one or more
listeners. Once the listener receives the event, the event will be processed and
returned. Many Java packages, such as java.util, java.awt and java.awt.event,
support events.
Delegation event model
The modern approach to handling events is based
on the delegation event model, which defines
standard and consistent mechanisms to generate
and process events. Its concept is quite simple: a
source generates an event and sends it to one or
more listeners.
public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet
To execute the applet by appletviewer tool, create an
There are two ways to run an applet By html file. applet that contains applet tag in comment and compile it.
To execute the applet by html file, create an applet and compile it.
After that create an html file and place the applet code in html file.
Now click the html file.
<html> <body>
<applet code="First.class" width="300" height="300">
</applet> </body> </html>
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
public abstract void drawArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used draw a import java.applet.Applet;
circular or elliptical arc.
import java.awt.*;
public abstract void fillArc(int x, int y, int width, int public class GraphicsDemo extends Applet{
height, int startAngle, int arcAngle): is used to fill a
circular or elliptical arc.
public void paint(Graphics g){
public abstract void setColor(Color c): is used to set the g.setColor(Color.red);
graphics current color to the specified color. g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
public abstract void setFont(Font font): is used to set the g.fillRect(170,100,30,30);
graphics current font to the specified font. g.drawOval(70,200,30,30);
g.setColor(Color.pink);
<html> g.fillOval(170,200,30,30);
<body> g.drawArc(90,150,30,30,30,270);
<applet code="GraphicsDemo.class" width="300" height="300"> g.fillArc(270,150,30,30,0,180);
</applet>
</body> } }
</html>