You are on page 1of 5

Object Any entity that has state and behavior is known as an Simple Java programming language is very simple

is very simple and easy to learn, .High performance Java provides high performance with the help of main: It is the name of Java main method. It is the identifier that the JVM
object. For example, a chair, pen, table, keyboard, bike, etc. It understand, and code. Most of the syntaxes in java follow basic features like JVM, interpretation, and its simplicity. looks for as the starting point of the java program. It’s not a keyword.
can be physical or logical.An Object can be defined as an programming language C and object-oriented programming concepts are class GeeksforGeeks {
instance of a class. An object contains an address and takes up similar to C++. In a java programming language, many complicated Distributed Java programming language supports TCP/IP protocols which public static void myMain(String[] args)
some space in memory. Objects can communicate without features like pointers, operator overloading, structures, unions, etc. have enable the java to support the distributed environment of the Internet. Java {
knowing the details of each other's data or code. The only been removed. One of the most useful features is the garbage collector it also supports Remote Method Invocation (RMI), this feature enables a System.out.println("I am a Geek");
makes java more simple. program to invoke methods across a network. } }
necessary thing is the type of message accepted and the type
of response returned by the objects.Example: A dog is an Dynamic Java is said to be dynamic because the java byte code may be
Secure Java is said to be more secure programming language because it
object because it has states like color, name, breed, etc. as dynamically updated on a running system and it has a dynamic memory String[] args: It stores Java command line arguments and is an array of
does not have pointers concept, java provides a feature "applet" which
well as behaviours like wagging the tail, barking, eating, etc. allocation and deallocation (objects and garbage collector). type java.lang.String class. Here, the name of the String array is args but it is
can be embedded into a web application. The applet in java does not allow
access to other parts of the computer, which keeps away from harmful not fixed and user can use any name in place of it.
Class Collection of objects is called class. It is a logical entity.A Public: It is an Access modifier, which specifies from where and who can class GeeksforGeeks {
programs like viruses and unauthorized access.
class can also be defined as a blueprint from which you can access the method. Making the main() method public makes it globally // javac GeeksforGeeks.java
create an individual object. Class doesn't consume any space. available. It is made public so that JVM can invoke it from outside the class // java GeeksforGeeks 1 2 3
Portable Portability is one of the core features of java which enables the
as it is not present in the current class. public static void main(String[] args)
java programs to run on any computer or operating system. For example,
Inheritance When one object acquires all the properties and class GeeksforGeeks { {
an applet developed using java runs on a wide variety of CPUs, operating
behaviours of a parent object, it is known as inheritance. It private static void main(String[] args) for (String elem : args)
systems, and browsers connected to the Internet.
provides code reusability. It is used to achieve runtime { System.out.println(elem);
polymorphism. System.out.println("I am a Geek"); }}
Object-oriented Java is said to be a pure object-oriented programming
} }
language. In java, everything is an object. It supports all the features of
Polymorphism if one task is performed in different ways, it is Static: It is a keyword which is when associated with a method, makes it a Data types specify the different sizes and values that can be
the object-oriented programming paradigm. The primitive data types java
known as polymorphism. For example: to convince the also implemented as objects using wrapper classes, but still, it allows
class related method. The main() method is static so that JVM can invoke it stored in the variable. There are two types of data types in
customer differently, to draw something, for example, shape, primitive data types to archive high-performance. without instantiating the class. This also saves the unnecessary wastage of Java:
triangle, rectangle, etc.In Java, we use method overloading memory which would have been used by the object declared only for
Robust Java is more robust because the java code can be executed on a calling the main() method by the JVM. 1. Primitive data types: The primitive data types include
and method overriding to achieve polymorphism.Another
variety of environments, java has a strong memory management class GeeksforGeeks { boolean, char, byte, short, int, long, float and double.
example can be to speak something; for example, a cat speaks public void main(String[] args)
meow, dog barks woof, etc. mechanism (garbage collector), java is a strictly typed language, it has a 2. Non-primitive data types: The non-primitive data types
strong set of exception handling mechanism, and many more. { include Classes, Interfaces, and Arrays.
System.out.println("I am a Geek");
Abstraction Hiding internal details and showing functionality is } }
Architecture-neutral (or) Platform Independent Java has invented to Byte Data Type The byte data type is an example of primitive
known as abstraction. For example phone call, we don't know Void: It is a keyword and used to specify that a method doesn’t return
archive "write once; run anywhere, any time, forever". The java provides data type. It isan 8-bit signed two's complement integer. Its
the internal processing.In Java, we use abstract class and anything. As main() method doesn’t return anything, its return type is void.
JVM (Java Virtual Machine) to to archive architectural-neutral or platform- value-range lies between -128 to 127 (inclusive). Its minimum
interface to achieve abstraction. independent. The JVM allows the java program created using one As soon as the main() method terminates, the java program terminates too. value is -128 and maximum value is 127. Its default value is
operating system can be executed on any other operating system. Hence, it doesn’t make any sense to return from main() method as JVM
0.The byte data type is used to save memory in large arrays
Encapsulation Binding (or wrapping) code and data together into can’t do anything with the return value of it.
where the memory savings is most required. It saves space
a single unit are known as encapsulation. For example, a Multi-threaded Java supports multi-threading programming, which allows class GeeksforGeeks {
public static int main(String[] args) because a byte is 4 times smaller than an integer. It can also
capsule, it is wrapped with different medicines.A java class is us to write programs that do multiple operations simultaneously.
{ be used in place of "int" data type.
the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private Interpreted Java enables the creation of cross-platform programs by System.out.println("I am a Geek");
return 1; Short Data TypeThe short data type is a 16-bit signed two's
here. compiling into an intermediate representation called Java bytecode. The
} } complement integer. Its value-range lies between -32,768 to
byte code is interpreted to any machine code so that it runs on the native
machine 32,767 (inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.The short data

type can also be used to save memory just like byte data type. Arrays: Arrays in Java are homogeneous data structures implemented in 12. 0101
1) Method overloading is Method overriding is used to
A short data type is 2 times smaller than an integer. Java as objects. Arrays store one or more values of a specific data type
13. & 0111 used to increase the provide the specific
and provide indexed access to store the same. A specific element in an
Int Data Type The int data type is a 32-bit signed two's array is accessed by its index 14. ________ readability of the implementation of the method
complement integer. Its value-range lies between - program. that is already provided by its
Classes: A class in Java is a blueprint which includes all your data. A 0101 = 5 (In decimal) super class.
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and class contains fields(variables) and methods to describe the behavior of Bitwise XOR (^) –
an object. This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR 2) Method overloading is Method overriding occurs in two
maximum value is 2,147,483,647. Its default value is 0.The int
of input values, i.e, if corresponding bits are different, it gives 1, else it performed within class. classes that have IS-A
data type is generally used as a default data type for integral Interface: Like a class, an interface can have methods and variables, but gives 0. (inheritance) relationship.
values unless if there is no problem about memory. the methods declared in interface are by default abstract (only method For example,
signature, no body). 15. a = 5 = 0101 (In Binary) 3) In case of method In case of method
Long Data Type The long data type is a 64-bit two's complement overloading, parameter overriding, parameter must be
integer. Its value-range lies between - Bitwise operators are used to perform manipulation of individual bits of a 16. b = 7 = 0111 (In Binary) must be different. same.
9,223,372,036,854,775,808(-2^63) to number. They can be used with any of the integral types (char, short, int, 17.
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum etc). They are used when performing update and query operations of Binary 4) Method overloading is Method overriding is the
value is - 9,223,372,036,854,775,808and maximum value is indexed tree. 18. Bitwise XOR Operation of 5 and 7 the example of compile example of run time
9,223,372,036,854,775,807. Its default value is 0. The long 19. 0101 time polymorphism. polymorphism.
Bitwise OR (|) –
data type is used when you need a range of values more than
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of 20. ^ 0111
those provided by int. 5) In java, method Return type must be same or
input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
21. ________ overloading can't be covariant in method overriding.
Float Data Type The float data type is a single-precision 32-bit For example,
1. a = 5 = 0101 (In Binary) performed by changing
IEEE 754 floating point.Its value range is unlimited. It is 0010 = 2 (In decimal)
return type of the
recommended to use a float (instead of double) if you need to 2. b = 7 = 0111 (In Binary) Bitwise Complement (~) – method only. Return
save memory in large arrays of floating point numbers. The 3. This operator is unary operator, denoted by ‘~’. It returns the one’s type can be same or
float data type should never be used for precise values, such as compliment representation of the input value, i.e, with all bits inversed, different in method
currency. Its default value is 0.0F. 4. Bitwise OR Operation of 5 and 7 means it makes every 0 to 1, and every 1 to 0. overloading. But you
5. 0101 For example, must have to change
Double Data Type The double data type is a double-precision 64-
6. | 0111 the parameter.
bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like 7. ________ a = 5 = 0101 (In Binary)
float. The double data type also should never be used for There are two types of modifiers in Java: access
0111 = 7 (In decimal) modifiers and non-access modifiers.
precise values, such as currency. Its default value is 0.0d.
Bitwise AND (&) – Bitwise Compliment Operation of 5
The access modifiers in Java specifies the accessibility or scope
Char Data Type The char data type is a single 16-bit Unicode This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of
character. Its value-range lies between '\u0000' (or 0) to of a field, method, constructor, or class. We can change the
input values, i.e, if both bits are 1, it gives 1, else it gives 0.
'\uffff' (or 65,535 inclusive).The char data type is used to store For example, ~ 0101 access level of fields, constructors, methods, and class by
characters. 8. a = 5 = 0101 (In Binary) applying the access modifier on it.
________
Strings: String is a sequence of characters. But in Java, a string is an 9. b = 7 = 0111 (In Binary) 1010 = 10 (In decimal) There are four types of Java access modifiers:
object that represents a sequence of characters. 10.
The java.lang.String class is used to create a string object No. Method Overloading Method Overriding
11. Bitwise AND Operation of 5 and 7
1. Private: The access level of a private modifier is only It provides more accessibility than the default modifer. 3. class 30. Honda1 honda= new Honda1();
within the class. It cannot be accessed from outside the 31. honda.run();
class. Public The final keyword can be applied with the variables, a final 32. }
2. Default: The access level of a default modifier is only variable that have no value it is called blank final variable or 33. }
The public access modifier is accessible everywhere. It has the uninitialized final variable. It can be initialized in the
within the package. It cannot be accessed from outside Super Keyword in Java
widest scope among all other modifiers. constructor only. The blank final variable can be static also
the package. If you do not specify any access level, it will
be the default. which will be initialized in the static block only. We will have The super keyword in Java is a reference variable which is used
detailed learning of these. Let's first learn the basics of final to refer immediate parent class object.
3. Protected: The access level of a protected modifier is
Access A static method can A non-static method can access keyword.
within the package and outside the package through child
access only static both static as well as non-static Whenever you create the instance of subclass, an instance of
class. If you do not make the child class, it cannot be 1. class Bike9{
1 members and can not members. parent class is created implicitly which is referred by super
accessed from outside the package. 2. final int speedlimit=90;//final variable
access non-static reference variable.
4. Public: The access level of a public modifier is 3. void run(){
members.
everywhere. It can be accessed from within the class, 4. speedlimit=400; Usage of Java super Keyword
outside the class, within the package and outside the 5. }
package. Binding Static method uses Non-static method uses run time 6. public static void main(String args[]){ 1. super can be used to refer immediate parent class
2 complie time binding binding or dynamic binding. 7. Bike9 obj=new Bike9(); instance variable.
Private or early binding. 8. obj.run(); 2. super can be used to invoke immediate parent class
9. } method.
The private access modifier is accessible only within the class.
10. }/ 3. super() can be used to invoke immediate parent class
Overriding A static method A non-static method can be
Simple example of private access modifier cannot be overridden overridden being dynamic binding. 11. class Bike{ constructor.
3 12. final void run(){System.out.println("running");}
being compile time
If you make any class constructor private, you cannot create the 13. } super is used to refer immediate parent class instance variable.
binding.
instance of that class from outside the class. 14.
15. class Honda extends Bike{ 2) super can be used to invoke parent class method
Default Memory Static method A non-static method may occupy 16. void run(){System.out.println("running safely with
allocation occupies less space more space. Memory allocation super is used to invoke parent class constructor.
100kmph");}
If you don't use any modifier, it is treated as default by default. 4 and memory happens when method is invoked 17. A constructor in Java is a special method that is used to
The default modifier is accessible only within package. It allocation happens and memory is deallocated once 18. public static void main(String args[]){
once. method is executed completely. initialize objects. The constructor is called when an object of a
cannot be accessed from outside the package. It provides more 19. Honda honda= new Honda(); class is created. It can be used to set initial values for object
accessibility than private. But, it is more restrictive than 20. honda.run(); attributes:
protected, and public. 21. }
Keyword A static method is A normal method is not required to
5 declared using static have any special keyword. 22. } Example
Protected
keyword. 23.
24. final class Bike{} Create a constructor:
The protected access modifier is accessible within package and
outside the package but through inheritance only. 25.
public class Main {
The final keyword in java is used to restrict the user. The java 26. class Honda1 extends Bike{
The protected access modifier can be applied on the data final keyword can be used in many context. Final can be: 27. void run(){System.out.println("running safely with int x;
member, method and constructor. It can't be applied on the 100kmph");}
class. 1. variable 28. public Main() {
2. method 29. public static void main(String args[]){

public append(String s) is used to append the specified


x = 5; synchronized string with this string. The append() In this process, an overridden method is called through the
codePointAt() Returns the Unicode of the character at int
StringBuffer method is overloaded like reference variable of a superclass. The determination of the
} the specified index
append(char), append(boolean), method to be called is based on the object being referred to by
append(int), append(float), the reference variable.
codePointBefore() Returns the Unicode of the character int
append(double) etc.
public static void main(String[] args) { before the specified index Let's first understand the upcasting before Runtime
public insert(int offset, is used to insert the specified string Polymorphism.
Main myObj = new Main();
synchronized String s) with this string at the specified codePointCount() Returns the Unicode in the specified text int
Upcasting
System.out.println(myObj.x); StringBuffer position. The insert() method is range of this String
overloaded like insert(int, char), If the reference variable of Parent class refers to the object of
} insert(int, boolean), insert(int, int), compareTo() Compares two strings lexicographically int Child class, it is known as upcasting.
} insert(int, float), insert(int, double)
etc. 1. class A{}
compareToIgnoreCase() Compares two strings lexicographically, int
The this keyword refers to the current object in a method or 2. class B extends A{}
public replace(int is used to replace the string from ignoring case differences
constructor. 1. A a=new B();//upcasting
synchronized startIndex, int specified startIndex and endIndex.
The most common use of the this keyword is to eliminate the StringBuffer endIndex, String concat() Appends a string to the end of another String
For upcasting, we can use the reference variable of class type
str) string
confusion between class attributes and parameters with the or an interface type. For Example:
same name (because a class attribute is shadowed by a public delete(int is used to delete the string from
method or constructor parameter). If you omit the keyword in contains() Checks whether a string contains a boolean 1. interface I{}
synchronized startIndex, int specified startIndex and endIndex.
the example above, the output would be "0" instead of "5". sequence of characters 2. class A{}
StringBuffer endIndex)
3. class B extends A implements I{}
this can also be used to: Object class in Java
public reverse() is used to reverse the string. contentEquals() Checks whether a string contains the boolean
 Invoke current class constructor synchronized exact same sequence of characters of the
The Object class is the parent class of all the classes in java by
 Invoke current class method StringBuffer specified CharSequence or StringBuffer
default. In other words, it is the topmost class of java.
 Return the current class object
public int capacity() is used to return the current
 Pass an argument in the method call copyValueOf() Returns a String that represents the String The Object class is beneficial if you want to refer any object
capacity.
 Pass an argument in the constructor call characters of the character array whose type you don't know. Notice that parent class reference
variable can refer the child class object, know as upcasting.
 public class Main {
 int x; The String class has a set of built-in methods that you can use endsWith() Checks whether a string ends with the boolean
Let's take an example, there is getObject() method that returns
 public Main(int x) { on strings. specified character(s)
an object but it can be of any type like Employee,Student etc,
 this.x = x; } we can use Object class reference to refer that object.
 public static void main(String[] args) { Method Description Return equals() Compares two strings. Returns true if the boolean
 Main myObj = new Main(5); Type strings are equal, and false if not
 System.out.println("Value of x = " + myObj.x);
 }} The Object class is the parent class of all the classes in java by
charAt() Returns the character at the specified char
Dynamic Method Dispatch is a process in which a call to an default. In other words, it is the topmost class of java.
index (position)
overridden method is resolved at runtime rather than compile-
time.
The Object class is beneficial if you want to refer any object public final void notifyAll() wakes up all the threads, waiting on 3. Hierarchical Inheritance
whose type you don't know. Notice that parent class reference
this object's monitor.
variable can refer the child class object, know as upcasting. In hierarchical inheritance, multiple subclasses extend from a single
public final void wait(long causes the current thread to wait superclass. For example,
Let's take an example, there is getObject() method that returns timeout)throws for the specified milliseconds, until
an object but it can be of any type like Employee,Student etc, InterruptedException another thread notifies (invokes
we can use Object class reference to refer that object. For
notify() or notifyAll() method).
example:
public final void wait(long causes the current thread to wait
1. Object obj=getObject(); Java Single Inheritance
timeout,int nanos)throws for the specified milliseconds and
InterruptedException nanoseconds, until another thread
The Object class provides some common behaviors to all the
notifies (invokes notify() or
objects such as object can be compared, object can be cloned,
notifyAll() method).
object can be notified etc.
public final void wait()throws causes the current thread to wait,
InterruptedException until another thread notifies 2. Multilevel Inheritance Java Hierarchical Inheritance
Methods of Object class (invokes notify() or notifyAll()
In multilevel inheritance, a subclass extends from a superclass and then the
method).
The Object class provides many methods. They are as follows: same subclass acts as a superclass for another class. For example,
protected void is invoked by the garbage collector
Method Description finalize()throws Throwable before object is being garbage
collected. 4. Multiple Inheritance
public final Class getClass() returns the Class class object of this
object. The Class class can further In multiple inheritance, a single subclass extends from multiple
be used to get the metadata of this superclasses. For example,
class.
Types of inheritance
public int hashCode() returns the hashcode number for
this object. There are five types of inheritance.

public boolean equals(Object compares the given object to this 1. Single Inheritance
obj) object.
In single inheritance, a single subclass extends from a single superclass. For
protected Object clone() creates and returns the exact copy example,
throws (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of Java Multilevel Inheritance Java Multiple Inheritance
this object.

public final void notify() wakes up single thread, waiting on


this object's monitor.

Note: Java doesn't support multiple inheritance. However, we can achieve  java.lang − This package provides the language basics. class c1(){ class c1{
 java.util − This packages provides classes and interfaces (API’s) public void m1(){ public void m1() {
multiple inheritance using interfaces. To learn more, visit Java implements System.out.println("m1 of c1"); System.out.println("m1 of c1");
related to collection frame work, events, data structure and other
multiple inheritance. utility classes such as date. } }
 java.io − This packages provides classes and interfaces for file public static void main(string args[]){ }
operations, and other input and output operations. c1 obj = new c1();
obj.m1(); Step 9) To execute the code mention the fully qualified name of the class i.e.
 java.math − This packages provides classes and interfaces for } the package name followed by the sub-package name followed by the class
multiprecision arithmetics. } name -
 java.nio − This packages provides classes and interfaces the Non-
5. Hybrid Inheritance java p1.p2.c1
blocking I/O framework for Java Here,
Hybrid inheritance is a combination of two or more types of inheritance.  java.net − This packages provides classes and interfaces related 1. package pack;
to networking. 1. To put a class into a package, at the first line of code define package 2. public class A{
For example, p1 3. public void msg(){System.out.println("Hello");}
 java.security − This packages provides classes and interfaces
such as key generation, encryption and decryption which belongs 2. Create a class c1 4. }
to security frame work. 3. Defining a method m1 which prints a line.
4. Defining the main method 1. //save by B.java
 java.sql − This packages provides classes and interfaces for 5. Creating an object of class c1 2. package mypack;
accessing/manipulating the data stored in databases and data 6. Calling method m1 3. import pack.*;
sources. 4.
 java.awt − This packages provides classes and interfaces to create Step 2) In next step, save this file as demo.java 5. class B{
GUI components in Java. 6. public static void main(String args[]){
 java.text − This packages provides classes and interfaces to Step 3) In this step, we compile the file. 7. A obj = new A();
handle text, dates, numbers, and messages. 8. obj.msg();
The compilation is completed. A class file c1 is created. However, no 9. }
 java.rmi − Provides the RMI package. package is created? Next step has the solution 10. }
 java.time − The main API for dates, times, instants, and durations.
 java.beans − The java.beans package contains classes and Step 4) Now we have to create a package, use the command Class Interface
interfaces related to JavaBeans components. A class describes the attributes and An interface contains behaviors that a
Step 5) When you execute the code, it creates a package p1. When you open behaviors of an object. class implements.
Creating a package is a simple task as follows the java package p1 inside you will see the c1.class file. A class may contain abstract methods, An interface contains only abstract
concrete methods. methods.
 Choose the name of the package Step 6) Compile the same file using the following code Members of a class can be public, All the members of the interface are
 Include the package command as the first line of code in your Java private, protected or default. public by default.
Java Hybrid Inheritance javac –d .. demo.java
Source File. interface MyInterface
Here, we have combined hierarchical and multiple inheritance to form a  The Source file contains the classes, interfaces, etc you want to {
include in the package Here ".." indicates the parent directory. In our case file will be saved in
parent directory which is C Drive /* compiler will treat them as:
hybrid inheritance.  Compile to create the Java packages * public abstract void method1();
Predefined packages Step 7) Now let's say you want to create a sub package p2 within our * public abstract void method2();
Step 1) Consider the following package program in Java: */
Java provides various predefined classes and interfaces (API’s) existing java package p1. Then we will modify our code as
public void method1();
organized under packages. These are known as predefined packages, package p1;
package p1.p2; public void method2();
following is the list of predefined packages in java −
}
class Demo implements MyInterface  Provides communication − One of the uses of the interface is to 6. FileReader fr = new 1) Checked Exception
{ provide communication. Through interface you can specify how FileReader("input.txt");
/* This class must have to implement both the abstract you want the methods and fields of a particular type. 7. BufferedReader br = new The classes which directly inherit Throwable class except
methods  Multiple inheritance − Java doesn’t support multiple inheritance, BufferedReader(fr); RuntimeException and Error are known as checked exceptions
* else you will get compilation error using interfaces you can achieve multiple inheritance 8. FileWriter fw = new e.g. IOException, SQLException etc. Checked exceptions are
*/ FileWriter("output.txt", true); checked at compile-time.
public void method1() Simple example of StringTokenizer class 9. String s;
{ 10. while ((s = br.readLine()) != null) 2) Unchecked Exception
System.out.println("implementation of method1"); Let's see the simple example of StringTokenizer class that {
} tokenizes a string "my name is khan" on the basis of whitespace. 11. fw.write(s); The classes which inherit RuntimeException are known as
public void method2() 12. fw.flush();}br.close(); unchecked exceptions e.g. ArithmeticException,
{ 1. import java.util.StringTokenizer; fw.close(); System.out.println("file copied"); NullPointerException, ArrayIndexOutOfBoundsException etc.
System.out.println("implementation of method2"); 2. public class Simple{ 13. } catch (IOException e) { Unchecked exceptions are not checked at compile-time, but they
} 3. public static void main(String args[]){ 14. e.printStackTrace();}}} are checked at runtime.
public static void main(String arg[]) 4. StringTokenizer st = new StringTokenizer("my name is
{ khan"," "); Exception Handling in Java 3) Error
MyInterface obj = new Demo(); 5. while (st.hasMoreTokens()) {
obj.method1(); The Exception Handling in Java is one of the Error is irrecoverable e.g. OutOfMemoryError,
6. System.out.println(st.nextToken());
} powerful mechanism to handle the runtime errors so that normal VirtualMachineError, AssertionError etc.
7. }
} 8. } flow of the application can be maintained.
.
An interface in Java is a specification of method prototypes. Whenever Byte Streams
In this page, we will learn about Java exceptions, its type and
you need to guide the programmer or, make a contract specifying how the Java byte streams are used to perform input and output of 8-bit bytes. the difference between checked and unchecked exceptions.
methods and fields of a type should be you can define an interface. Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream. Advantage of Exception Handling Java Exception Keywords
To create an object of this type you need to implement this interface,
provide body for all the abstract methods of the interface and obtain the Character Streams There are 5 keywords which are used in handling exceptions in
object of the implementing class. The core advantage of exception handling is to maintain the
Java Byte streams are used to perform input and output of 8-bit bytes, normal flow of the application. An exception normally disrupts Java.
All the methods of the interface are public and abstract and, we will define whereas Java Character streams are used to perform input and output for the normal flow of the application that is why we use exception
an interface using the interface keyword as shown below − 16-bit Unicode. Though there are many classes related to character handling Keyword Description
streams but the most frequently used classes
interface MyInterface{ are, FileReader and FileWriter. Though internally FileReader uses Types of Java Exceptions try The "try" keyword is used to specify a block where we
FileInputStream and FileWriter uses FileOutputStream but here the major
public void display(); should place exception code. The try block must be
difference is that FileReader reads two bytes at a time and FileWriter There are mainly two types of exceptions: checked and followed by either catch or finally. It means, we can't use
public void setName(String name); writes two bytes at a time. unchecked. Here, an error is considered as the unchecked try block alone.
exception. According to Oracle, there are three types of
public void setAge(int age); 1. import java.io.BufferedReader;import
exceptions: catch The "catch" block is used to handle the exception. It must
java.io.FileReader;
} 2. import java.io.FileWriter;import java.io.IOException; be preceded by try block which means we can't use catch
1. Checked Exception block alone. It can be followed by finally block later.
3. public class FileCopyExample {
Purpose of the interface 2. Unchecked Exception
4. public static void main(String[] args) {
5. try { 3. Error

{ } 2) Runnable The thread is in runnable state after invocation of


finally The "finally" block is used to execute the important code }
public static void main(String[] args) start() method, but the thread scheduler has not selected it to
of the program. It is executed whether an exception is { class MyException extends Exception{ be the running thread.
handled or not. int x,y; String str1;
//Create scanner object to obtain input from keyboard 3) Running The thread is in running state if the thread scheduler
throw The "throw" keyword is used to throw an exception.
Scanner input=new Scanner(System.in); MyException(String str2) { has selected it.
throws The "throws" keyword is used to declare exceptions. It try str1=str2;
doesn't throw an exception. It specifies that there may
{ } 4) Non-Runnable (Blocked) This is the state when the thread is
System.out.print("Enter first integer : "); public String toString(){ still alive, but is currently not eligible to run.
occur an exception in the method. It is always used with
x=input.nextInt(); //Read first integer return ("MyException Occurred: "+str1) ;
method signature. System.out.print("Enter second integer : "); } 5) Terminated A thread is in terminated or dead state when its
Built-in exceptions are the exceptions which are available in Java libraries. y=input.nextInt(); //Read second integer } run() method exits
These exceptions are suitable to explain certain error situations. Below is the System.out.println(x + " / " + y +" = " + (x/y));
list of important built-in exceptions in Java. } class Example1{ 1. class Multi extends Thread{
catch(ArithmeticException e) public static void main(String args[]){ 2. public void run(){
1. ArithmeticException It is thrown when an exceptional condition
{ try{ 3. System.out.println("thread is running...");
has occurred in an arithmetic operation.
System.out.println("Denominator Cannot be Zero while System.out.println("Starting of try block"); 4. }
2. ArrayIndexOutOfBoundsException It is thrown to indicate that Integer Division");
an array has been accessed with an illegal index. The index is throw new MyException("This is My error 5. public static void main(String args[]){
} Message"); 6. Multi t1=new Multi();
either negative or greater than or equal to the size of the array. }
3. ClassNotFoundException This Exception is raised when we try } 7. t1.start();
} catch(MyException exp){
to access a class whose definition is not found 8. }
class Main { System.out.println("Catch Block") ;
4. FileNotFoundException This Exception is raised when a file is public static void main (String args[]) { 9. }
not accessible or does not open. System.out.println(exp) ;
//try block
5. IOException It is thrown when an input-output operation failed } The setPriority() method of thread class is used to change the
try
or interrupted } thread's priority. Every thread has a priority which is represented
{
6. InterruptedException It is thrown when a thread is waiting , } by the integer number between 1 to 10.
System.out.println ("::Try Block::");
sleeping , or doing some processing , and it is interrupted. int data = 125 / 5;
7. NoSuchFieldException It is thrown when a class does not contain System.out.println ("Result:" + data); Thread class provides 3 constant properties:
the field (or variable) specified } 1. New
8. NoSuchMethodException It is thrown when accessing a method //catch block 1. public static int MIN_PRIORITY: It is the maximum priority
2. Runnable
which is not found. catch (NullPointerException e) { of a thread. The value of it is 1.
3. Running
9. NullPointerException This exception is raised when referring to System.out.println ("::Catch Block::"); 2. public static int NORM_PRIORITY: It is the normal priority
System.out.println (e); 4. Non-Runnable (Blocked) of a thread. The value of it is 5.
the members of a null object. Null represents nothing
10. NumberFormatException This exception is raised when a } 5. Terminated 3. public static int MAX_PRIORITY: It is the minimum priority
method could not convert a string into a numeric format. //finally block of a thread. The value of it is 10.
11. RuntimeException This represents any exception which occurs finally { 6. New
during runtime. System.out.println (":: Finally 7. The thread is in new state if you create an instance of Thread class but We can also set the priority of thread between 1 to 10. This
12. StringIndexOutOfBoundsException It is thrown by String class Block::"); before the invocation of start() method. priority is known as custom priority or user defined priorit
methods to indicate that an index is either negative than the size System.out.println ("No
of the string Exception::finally block executed");
import java.util.Scanner; }
public class DivideByZeroException System.out.println ("rest of the code...");
Synchronization in Java public final void notify()

Synchronization in java is the capability to control the access of Inter-thread communication in Java The method execution sequence when an applet is closed is:
multiple threads to any shared resource.
Inter-thread communication or Co-operation is all about 3) notifyAll() method Wakes up all threads that are waiting on this  stop()
Java Synchronization is better option where we want to allow allowing synchronized threads to communicate with each object's monitor. Syntax:  destroy()
only one thread to access the shared resource. other.Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its critical public final void notifyAll()
1. The synchronization is mainly used to To prevent thread section and another thread is allowed to enter (or lock) in the 1. import java.applet.Applet;
interference. Lifecycle of Java Applet 2. import java.awt.Graphics;
same critical section to be executed.It is implemented by
2. To prevent consistency problem. following methods of Object class: 3. public class First extends Applet{
1. Applet is initialized.
3. When we start two or more threads within a program, there may be 4.
o wait()notify()notifyAll() 2. Applet is started. 5. public void paint(Graphics g){
a situation when multiple threads try to access the same resource
and finally they can produce unforeseen result due to concurrency 3. Applet is painted. 6. g.drawString("welcome",150,150);
1) wait() method Causes current thread to release the lock and wait 4. Applet is stopped. 7. } }
issues. For example, if multiple threads try to write within a same
until either another thread invokes the notify() method or the
file then they may corrupt the data because one of the threads can 5. Applet is destroyed. JAVA APPLICATION JAVA APPLET
override data or while one thread is opening the same file at the notifyAll() method for this object, or a specified amount of time
same time another thread might be closing the same file. has elapsed. init(): The init() method is the first method to execute when the applet is
executed. Variable declaration and initialization operations are Applets are small Java programs
4. So there is a need to synchronize the action of multiple threads and The current thread must own this object's monitor, so it must be performed in this method.
make sure that only one thread can access the resource at a given called from the synchronized method only otherwise it will throw Applications are just like a that are designed to be included
point in time. This is implemented using a concept called monitors. exception. start(): The start() method contains the actual code of the applet that
Each object in Java is associated with a monitor, which a thread should run. The start() method executes immediately after Java programs that can be with the HTML web document.
can lock or unlock. Only one thread at a time may hold a lock on a the init() method. It also executes whenever the applet is restored,
monitor. Method Description maximized or moving from one tab to another tab in the browser. execute independently without They require a Java-enabled web
5. Java programming language provides a very handy way of creating public final void waits until stop(): The stop() method stops the execution of the applet. The stop()
threads and synchronizing their task by using synchronized blocks. wait()throws object is method executes when the applet is minimized or when moving from using the web browser. browser for execution.
You keep shared resources within this block. Following is the one tab to another in the browser.
InterruptedException notified.
general form of the synchronized statement −
destroy(): The destroy() method executes when the applet window is Application program requires
6. Syntax public final void waits for
closed or when the tab containing the webpage is closed. stop() method
7. synchronized(objectidentifier) { wait(long the a main function for its Applet does not require a main
executes just before when destroy() method is invoked. The destroy()
8. // Access shared variables and other shared timeout)throws specified method removes the applet object from memory.
resources InterruptedException amount of execution. function for its execution.
9. } time. paint(): The paint() method is used to redraw the output on the applet
10. Here, the objectidentifier is a reference to an object whose display area. The paint() method executes after the execution
lock associates with the monitor that the synchronized statement of start() method and whenever the applet or browser is resized. Java application programs
represents. Now we are going to see two examples, where we will 2) notify() method Wakes up a single thread that is waiting on this The method executin sequence when an applet is executed is:
print a counter using two different threads. When threads are not have the full access to the Applets don’t have local disk and
object's monitor. If any threads are waiting on this object, one
synchronized, they print counter value which is not in sequence, but of them is chosen to be awakened. The choice is arbitrary and  init()
when we print counter by putting inside synchronized() block, then local file system and network. network access.
occurs at the discretion of the implementation. Syntax:  start()
it prints counter very much in sequence for both the threads.  paint()

8. g.drawString(str,50, 50);  Java Swing is the advanced and optimized version of AWT and it
JAVA APPLICATION JAVA APPLET
9. } is built on top of AWT. Still, many AWT classes are used in Swing
10. either directly or indirectly. It is important to do the basics of AWT
Applets can only access the 11. } before proceeding to Java Swing. Otherwise, we cannot
Object<-component<-container<-panel<-applet<-japplet understand the underlying facts about several control delegations
Applications can access all browser specific services. They while GUI in Java.

kinds of resources available don’t have access to the local

on the system. system.

Applications can executes the

programs from the local Applets cannot execute programs

system. from the local machine.

An application program is

needed to perform some task An applet program is needed to

directly for the user. perform small tasks or the part of it.

We can get any information from the HTML file as a parameter.


For this purpose, Applet class provides a method named
getParameter(). Syntax:

1. public String getParameter(String parameterName)


 First of all, by a heavy-weight, it means the code will take
Example of using parameter in Applet: comparatively more time to load and it will consume more System
resources. AWT is considered to be heavy-weight because its
components are dependent on the underlying Operating System.
1. import java.applet.Applet; For instance, When we create an object
2. import java.awt.Graphics; of java.awt.Checkbox class, its underlying Operating System will
3. generate a checkbox for us. This is also the reason, AWT
components are platform dependent.
4. public class UseParam extends Applet{
5.  On the other hand, most of the Java Swing components are
6. public void paint(Graphics g){ implemented in Java itself. Some of the top level components like
7. String str=getParameter("msg"); windows are dependent on the Operating System. But still, the
overall program is comparatively light-weight than AWT.

You might also like