Java Note(MCA)
Java Note(MCA)
Java Example
class Simple
{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output: Hello Java
Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates a dynamic page is called
a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF,
etc. technologies are used for creating web applications in Java.
3) Enterprise Application
4) Mobile Application
Features of Java
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
What is an object in Java
An entity that has state and behaviour is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). An object is an instance of a class.
Class in Java
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Method in Java
Advantage of Method
o Code Reusability
o Code Optimization
Inheritance: It is a mechanism in which one object acquires all the properties
and behaviours of a parent object. Moreover, you can add new methods and
fields in your current class also. Inheritance represents IS-A relationship which
is also known as a parent-child relationship.
Use inheritance in java
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because no explicit pointer is present.
Robust
Architecture-neutral
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
KEY DIFFERENCE:
C++ uses only compiler, whereas Java uses compiler and interpreter both.
C++ supports both operator overloading & method overloading whereas
Java only supports method overloading.
C++ supports manual object management with the help of new and delete
keywords whereas Java has built-in automatic garbage collection.
C++ supports structures and union whereas Java doesn’t support .
Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.All the classes,
interfaces, packages, methods and fields of Java programming language are
given according to the Java naming convention. If you fail to follow these
conventions, it may generate confusion or erroneous code.By using standard
Java naming conventions, you make your code easier to read for yourself and
other programmers.
The following are the key rules that must be followed by every identifier:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.Variable is a name of memory
location.
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. A
local variable can’t be defined with “static” keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static. It is called an instance variable
because its value is instance specific and is not shared among instances.
3) Static variable
Ex:
public class Demo
{
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[])
{
//local variable
int marks = 72;
}
}
Data Types in Java
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example:
+, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
OUTPUT
-11
9
False
true
The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.
The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.
EX:
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is
true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is
true or false.
Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming. It is the only conditional operator which
takes three operands.
Java Ternary Operator Example
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
JavaControl Statements
If-else Statement
The Java if statement is used to test the condition. It
checks boolean condition: true or false. There are various types of if statement
in Java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is
true.
Syntax:
if(condition){
//code to be executed
}
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
System.out.print("Age is greater than 18");
}
}
Output:
Age is greater than 18
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Ex:1
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A gr
ade and +.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
The Java switch statement executes one statement from multiple conditions. It is
like if-else-if ladder statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Output:20
Loops in Java
o for loop
o while loop
o do-while loop
Introduction The Java for loop is The Java while loop is The Java do while loop
a control flow a control flow is a control flow
statement that statement that executes statement that executes a
iterates a part of a part of the programs part of the programs at
the programs multipl repeatedly on the basis least once and the further
e times. of given boolean execution depends upon
condition. the given boolean
condition.
Output:
*
**
***
****
*****
Syntax:
for(Type var:array){
//code to be executed
}
Example:
Syntax: continue;
11
12
13
21
23
31
32
33
Java comments are the statements that are not executed by the compiler and
interpreter.
Syntax:
Syntax:
/*
This
is
multi line
comment
*/
Example:
Syntax:
/**
This
is
documentation
comment
*/
Ways to initialize object
There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
3) Object and Class Example: Initialization through a constructor
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea()
{System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
Anonymous object
Anonymous simply means nameless. An object which has no reference is
known as an anonymous object. It can be used at the time of object creation
only.If you have to use an object only once, an anonymous object is a good
approach. For example:
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial is 120
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
Rules for creating Java constructor
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
A constructor must not have a return A method must have a return type.
type.
The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.
The constructor name must be same as The method name may or may not be
the class name. same as the class name.
There are many ways to copy the values of one object into another in Java. They
are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another
using Java constructor.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Yes, it is the current class instance (You cannot use return type yet it returns a
value).
Yes, like object creation, starting a thread, calling a method, etc. You can
perform any operation in the constructor as you perform in the method.
Is there Constructor class in Java?
Yes.
Java provides a Constructor class which can be used to get the internal
information of a constructor in the class. It is found in the java.lang.reflect
package.
Java static keyword
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading,if any object changes the value of the static variable, it will
retain its value.
//Java Program to illustrate the use of static variable
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value
of it.
// Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:125
Restrictions for the static method
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
OUTPUT: COMPILER ERROR
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a
non-static method, JVM creates an object first then call main() method that will
lead the problem of extra memory allocation.
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of class loading.
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6.
Since JDK 1.7, it is not possible to execute a Java class without the main
method.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
OUTPUT: static block is invoked
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Java Arrays
Java array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array. Array in Java is index-based, the
first element of the array is stored at the 0th index, 2nd element is stored on 1st
index and so on.
Advantages
o Code Optimization: It makes the code optimized , we can retrieve or
sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization of Array
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
33
3
4
5
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare
the array while passing an array to the method.
public class TestAnonymousArray{
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to metho
d
}}
Output:
10
22
44
66
Output:
123
245
445
Output:
012
3456
78
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
268
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is
multiplied by all the columns of the second matrix which can be understood by
the image given below.
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}}
Output:
666
12 12 12
18 18 18
String
When it comes to Java, a string is considered as an object that defines a
sequence of char values. In Java, arrays are unchangeable, likewise strings are
unchangeable(immutable) as well. In any case, if a modification happens in a
string, a completely new string is constructed. Java defines a class called String
in java.lang package. It allows to create and manipulate String objects.
Examples:
String myString = “Joy with Java”;
System.out.println(myString);
System.out.println(“Welcome”);
System.out.println(“Welcome” + “ “+ myString);
String aString = “An example of string is ” + myString;
Program:
import java.lang; // It is by default imported in all programs.
class BasicStringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
String myString = “Joy with Java”;
System.out.println(myString);
System.out.println(“Welcome”);
System.out.println(“Welcome” + “ “ + myString);
}
}
Operations on strings such as
1. Trimming
2. Concatenating
3. Converting
4. Comparing
5. Replacing, etc.
Constructors of String
String() Initializes a newly created String object so that it represents an
empty character sequence.
String(byte[] bytes) Constructs a new String by decoding the specified array
of bytes usingthe platform's default char set.
String(byte[] bytes, Charset charset) Constructs a new String by decoding
the specified array of bytes usingthe specified char set.
String(byte[] ascii, int hibyte) This method does not properly convert bytes
into characters. As ofJDK 1.1, the preferred way to do this is via the String
constructors that take a Charset, charset name, or that use the platform's default
charset.
String(byte[] bytes, int offset, int length) Constructs a new String by
decoding the specified subarray of bytes using the platform's default char set.
String(StringBuffer buffer) Allocates a new string that contains the
sequence of characterscurrently contained in the string buffer argument.
String(byte[] bytes, int offset,int length, Charset charset)Constructs a new
String by decoding the specified subarray of bytes using the specified charset.
Important methods of String class
Example 1 : length() of String
Example 4 : toLowerCase()
String toLowerCase() Converts all the characters in the String to lower case.
Example 6:trim()
String trim() Returns the copy of the String, by removing whitespaces at both
ends. It does not affectwhitespaces in the middle.
String replace(char old, char new) Returns new string by replacing all
occurrences of old withnew.
Output Code
70 -
32
-32
Example 11 : substring()
String substring(int i) Returns the sub string starting from the character with i-th
index.
public class SubstringDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
String data = text.substring(3);
System.out.print(data);
}
}
Output Code
A STRUCTURE WITH JAVA
Example 12 : substring()
String substring(int i, int j) Returns the substring from character with i to j-1
indices.
public class SubstringAnyDemo{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
String data = text.substring(5,14);
System.out.print(data);
}
}
Output Code
STRUCTURE
Example 13 : indexOf() method
int indexOf(String s, int i) Returns the index within the string of the first
occurrence of the specified string,
starting at the specified index.
public class Example{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
int output = text.indexOf("T",4);
System.out.print(output);
}
}
Output Code
6
Example 14 : lastIndexOf()
int lastIndexOf(String s) Returns the index within the string of the last
occurrence of the specified string.
public class Example{
public static void main(String args[]){
String text = "DATA STRUCTURE WITH JAVA";
int output = text.lastIndexOf("T");
System.out.print(output);
}
}
Output Code
17
Example 15 : String to Int,Float
public class StringToIntegerDemo{
public static void main(String args[]){
String number = "95";
int num = Integer.parseInt(number);
int output = num + 5;
System.out.println(output);
String number1= "95.59";
float num1= Float.parseFloat(number1);
System.out.println(num1);
}
}
Output Code
100
95.59
Example 18 : to String
// The following program demonstrates binary, hexadecimal, and octal
conversion:
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " +
Integer.toBinaryString(num));
System.out.println(num + " in octal: " +
Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " +
Integer.toHexString(num));
}
}
Output Code
19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0
StringBuffer
StringBuffer is the equivalent class of the class string. The class StringBuffer
delivers more functionality to the other class strings. We can make changes here
because the StringBuffer is mutable.
String StringBuffer
String is immutable. It is mutable.
Here the length of the string class is Here the length can be modified
static. whenever required, as it is dynamic in
behaviour.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex
and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
Output:
olleH
The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
The ensureCapacity() method of the StringBuffer class ensures that the given
capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+
2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
JVM (Java Virtual Machine) Architecture
JVM Architecture
JVMcontainsclass loader, memory area, execution engine etc.
1) Classloader
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your
own classloader, you need to extend the ClassLoader class.
2) Class(Method) Area
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
6) Native Method Stack
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT
compiles parts of the byte code that have similar functionality at the same
time, and hence reduces the amount of time needed for compilation.
8) Java Native Interface
/**
* This is a javadoc comment
**/
We can also use standard HTML tags within a java-doc comment. However, we
don't use heading tags such as <h1>, <h2> and <h6>, or a horizontal rule <hr>.
An example that shows document API
In this example; we can create a simple class that contains a documentation
comment and shows how to create a documented API.
1. package com.mypack;
2. public Class APIDocEx
3. {
4. public static void square(int x)
5. {
6. System.out.println(x * x);
7. }
8. }
Output
To create the document API, we need to use the javadoc tool as in the
following.
In a command prompt write the following:
javadoc M.java
After generating the documented API. We will now see many HTML files
created. Now we need to open the index.html file to get the information about
the classes. The figure below shows the following.
Inheritance in Java
OUTPUT:
Programmer salary is:40000
Bonus of Programmer is:1000
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As
you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Output:
meowing...
eating...
Interface in Java:
There are mainly three reasons to use interface. They are given below.
Output:
Hello
Output:
Hello
Welcome
Interface inheritance:
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}}
Output:
Hello
Welcome
Output:
drawing rectangle
default method
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:
drawing rectangle
27
Member access rules in Java
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Private Constructor
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the
package but through inheritance only.
It provides more accessibility than the default modifier.
Example of protected access modifier
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
this keyword in Java
1) this: to refer current class instance variable
this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and formal parameters, this keyword
resolves the problem of ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
OUTPUT: hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It
is used to reuse the constructor. In other words, it is used for constructor
chaining.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
4) this: to pass as an argument in the method
class Test
{
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
OUTPUT: black
white
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark(); }}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
Output:
animal is created
dog is created
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final variable.
It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only.
1) Java final variable
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
} }
Output:Compile Time Error
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run(); }}
Output:Compile Time Error
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running
Bike(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike(); }}
output: 70
If you declare any parameter as final, you cannot change the value of it.
class Bik{
int cube(final int n){
n=n+2;//can't be changed as n is final
}
public static void main(String args[]){
Bike b=new Bike();
b.cube(5);
}}
Output:Compile Time Error
If a class has multiple methods having same name but different in parameters, it
is known as MethodOverloading.Method overloading increases the readability
of the program.
Different ways to overload the method
import java.util.*;
class overload
{
Scanner sc=new Scanner(System.in);
void Add()
{
System.out.println("Eneter a number");
int x=sc.nextInt();
System.out.println("Eneter a number");
int y=sc.nextInt();
System.out.println("Result="+(x+y));
}
int Add(int x,inty,int z)
{return(x+y+z);}
}
class OverloadDemo
{
public static void main(String args[])
{
overload ob1=new overload();
ob1.Add();
System.out.println("Additionof three
integers="+ob1.Add(10,20,30));
}
}
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that each
constructor performs a different task. They are differentiated by the compiler by
the number of parameters in the list and their types.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
Yes, by method overloading. You can have any number of main methods in a
class by method overloading. But JVM calls main() method which receives
string array as arguments only. Let's see the simple example:
class TestOverloading{
public static void main(String[] args){System.out.println("HELLO JAVA");}
public static void main(String args){System.out.println("HII");}
public static void main(){System.out.println("HELLO WORLD");}
}
The method must have the same parameter as in the parent class.
Output:
It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to
the heap area.
Can we override java main method?
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
} }
Output:
drawing rectangle...
drawing circle...
drawing triangle.
The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it
compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.
Simple example of java instanceof
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println (s instanceof Simple1);//true
}
}
Output:true
Abstract class in Java:
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
Another example:
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest of SBI
is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest of PNB
is: "+b.getRateOfInterest()+" %");
}}
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
} }
running safely
gear changed
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
8) A Java abstract class can have Members of a Java interface are public by
class members like private, protected, default.
etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages. The import keyword is used to make the classes
and interface of another package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Reading and Writing at Console in Java
Input from Console
There are several ways to read data given by the user at the console. They are:
Scanner class
BufferedReader class
Console class
Scanner Class
This is the most common and preferred method to take input. It is used to read
input from the console. However, it was initially brought up for the purpose of
parsing strings and primitive data types.
import java.util.Scanner;
publicclass ReadWriteConsole {
publicstaticvoid main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter some string: ");
String myString = in.nextLine();
System.out.println("Please enter some integer: ");
int myInt = in.nextInt(); //This parses to integer
System.out.println("Please enter some float: ");
float myFloat = in.nextFloat(); //This parses to float
System.out.println("*******Validation Part*******");
System.out.println("Your input string: "+myString);
System.out.println("Your input int: "+myInt);
System.out.println("Your input float: "+myFloat);
}
}
Output:
Please enter some string:
trident
Please enter some integer:
89
Please enter some float:
80.8
*******Validation Part*******
Your input string: trident
Your input int: 89
Your input float: 80.8
BufferedReader Class
This is the classical way to take input, which was part of JDK's first release.
Here, we instantiate the BufferedReader class by wrapping
an InputStreamReader which wraps the standard console input stream. It
buffers the input for efficient reading. It is accompanied by static methods of
Wrapper classes to read corresponding data types.
import java.io.*;
publicclass ReadWriteConsole
{
publicstaticvoid main(String args[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter some string: ");
String myString = in.readLine();
System.out.println("Please enter some integer: ");
int myInt = Integer.parseInt(in.readLine());
System.out.println("Please enter some float: ");
float myFloat = Float.parseFloat(in.readLine());
System.out.println("*******Validation Part*******");
System.out.println("Your input string: "+myString);
System.out.println("Your input int: "+myInt);
System.out.println("Your input float: "+myFloat);
}
}
Output
Please enter some string:
trident
Please enter some integer:
88
Please enter some float:
8.9
*******Validation Part*******
Your input string: trident
Your input int: 88
Your input float: 8.9
Console Class
The Java Console class is be used to get input from console. It provides
methods to read texts and passwords.If you read password using Console class,
it will not be displayed to the user.
import java.io.*;
public class Main
{
public static void main(String[] args) {
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
System.out.println("Enter your age: ");
int n1=Integer.parseInt(c.readLine());
System.out.println(n1);
}
}
Using Command line argument :
The java command-line argument is an argument i.e. passed at the time of
running the java program. The arguments passed from the console can be
received in the java program and it can be used as an input. So, it provides a
convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
import java.io.*;
publicclass ReadWriteConsole
{
publicstaticvoid main(String args[]) throws IOException
{
for(int i=1;i<=5;i++)
System.out.print(i);
for(inti=1;i<=5;i++)
System.out.println(i);
for(int x=65;x<=70;x++){
System.out.write(x);
System.out.write('\n');
}
}
}
File Handling in Java
In Java, with the help of File Class, we can work with files. This File Class is
inside the java.io package. The File class can be used by creating an object of
the class and then specifying the name of the file.
Why File Handling is Required?
File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a
file.
File Operations
We can perform the following operation on a file:
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
import java.io.File;
import java.io.IOException;
publicclass IOClass
{
publicstaticvoid main(String[] args)
{
try
{
File f0 = new File("D:Myfile.txt");
if (f0.createNewFile())
System.out.println("File " + f0.getName() + " is created successfully.");
else
{
System.out.println("File is already exist in the directory.");
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
System.out.println("Is file writeable?: " + f0.canWrite());
System.out.println("Is file readable " + f0.canRead());
System.out.println("The size of the file in bytes is: " + f0.length());
}
}
catch (IOException exception)
{
System.out.println("An unexpected error is occurred.");
}
}
}
What is a Stream in Java?
Stream in Java Programming Language is the sequence of the objects that are
pipelined to get desired results.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
The Stream is not a data structure instead it just takes input from collections of
I/O. Stream doesn’t change the original methods or data structure it just
pipelines it and provides our result.
There are two brands of Stream in Java Programming Language:
1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source.
The Input Stream provides the set of Objects and pipelines together to provide
us the functionality of Input the collection in I/O File.
2. Output Stream:
The Output Stream provides the functionality of writing the data to the
Destination. The Output Stream provides the set of Objects and pipelines
together to provide us the functionality of Output to the collection in I/O File.
}
Filecopy program(Using Character stream classes)
import java.io.*;
publicclass IOClassReadWrite {
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
Byte Stream
Byte Stream is mainly consolidated with byte data. The byte data is nothing but
an 8-bits data. Java Byte Stream is used to perform the input and output in the
form of an 8-bits byte.This stream takes the input and computes it in the form of
byte data. There are many classes in Java that provide the byte stream but we
recommend using FileInputStream and FileOutputStream.
Some important Byte stream classes.
import java.io.*;
publicclass Bytestream
{
publicstaticvoid main(String[] args) throws IOException
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}
}
Filecopy program(Using Byte stream classes)
import java.io.*;
publicclass IOClassWrite
{
publicstaticvoid main(String[] args) throws IOException
{
FileInputStream source = null;
FileOutputStream dest = null;
try {
source = new FileInputStream("D:Myfile.txt");
dest = new FileOutputStream("D:destination.txt");
int temp;
while ((temp = source.read()) != -1)
dest.write(temp);
System.out.println("Successfully copied");
}
finally
{
if (source != null)
source.close();
if (dest != null)
dest.close();
}
}
Reading/Writing Primitive types of data
import java.io.*;
publicclass MultipleData
{
In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime. The Exception Handling in Java is
one of the powerful mechanisms to handle the runtime errors so that normal
flow of the application can be maintained ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
There are two types of exceptions: checked exception and unchecked exception.
The main difference between checked and unchecked exception is that the
checked exceptions are checked at compile-time while unchecked exceptions
are checked at runtime.
1.Checked Exception
2.Unchecked Exception
3.Error
Unchecked exceptions are not checked at compile time. Most of the times this
exception occurs due to the bad data provided by user during the user-program
interaction. It is up to the programmer to judge the conditions in advance, that
can cause such exceptions and handle them appropriately. All Unchecked
exceptions are direct sub classes of RuntimeException class.
The classes which inherit RuntimeException are known as unchecked
exceptionse.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBou
ndsException etc.
3) Error
Keyword Description
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
Output:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Output:
As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example :Here, we handle the exception using the parent class exception.
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Output:
Output:
Here, we can see that the catch block didn't contain the exception code. So,
enclose exception code within a try block and use catch block only to handle the
exceptions.
Example:
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.
Output:
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is invoked.
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
} }
Output:
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs"
);
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}}
Output:
Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).
class MultipleCatchBlock4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 co
mpleted");}
System.out.println("rest of the code...");
}}
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement”);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}}
Output:
going to divide
java.lang.ArithmeticException: / by zero
other statement
normal flow..
Java finally block
Java finally block is a block that is used to execute important code such as
closing connection, stream etc. Java finally block is always executed whether
exception is handled or not. Java finally block follows try or catch block.
Ex:
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
throw exception;
Output:
Output
The throws keyword indicates what exception type may be thrown by a method.
publicvoidmyMethod() throwsArithmeticException, NullPointerException
{
// Statements that might throw an exception
}
publicclassExample1{
publicstaticvoidmain(Stringargs[]){
try{
ThrowExampleobj=newThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException: IOExceptionOccurred
Differences between throw and throws.
Sr. Key throw throws
No.
finally: In Java, finally is a block used to place important code that will be
executed whether or not an exception is handled.
Ex:
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc(); }}
Multithreading
Thread is an execution unit that is part of a process. A process can have
multiple threads, all executing at the same time. It is a unit of execution in
concurrent programming. A thread is a flow of execution through the process
code, with its own program counter that keeps track of which instruction to
execute next, system registers which hold its current working variables, and a
stack which contains the execution history. Threads provide a way to improve
application performance through parallelism.
Advantages of Thread
A thread goes through various stages in its lifecycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete
life cycle of a thread.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Th
class extends Object class and implements Runnable interface.
miliseconds.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended t
executed by a thread. Runnable interface have only one method named run().
FileName: Multi.java
Output:
thread is running...
2)Java Thread Example by implementing Runnable interface
FileName: Multi3.java
Output:
thread is running...
Output:
My first thread
4) Using the Thread Class: Thread(Runnable r, String name)
FileName: MyThread2.java
Output:
My new thread
Now the thread is running ...
Java Synchronization
Synchronization is a process of handling resource accessibility by multiple
thread requests. The main purpose of synchronization is to avoid thread
interference. At times when more than one thread try to access a shared
resource, we need to ensure that resource will be used by only one thread at a
time. The process by which this is achieved is called synchronization. The
synchronization keyword in java creates a block of code referred to as critical
section.
class First
{
synchronizedpublicvoid display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println ("]");
}
}
Output
[welcome]
[programmer]
[new]
Difference between synchronized keyword and
synchronized block
When we use synchronized keyword with a method, it acquires a lock in the
object for the whole method. It means that no other thread can use any
synchronized method until the current thread, which has invoked it's
synchronized method, has finished its execution.
synchronized block acquires a lock in the object only between parentheses after
the synchronized keyword. This means that no other thread can acquire a lock
on the locked object until the synchronized block exits. But other threads can
access the rest of the code of the method.
Ex:Synchronized block
class First
{
publicvoid display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println( e);
}
System.out.println ("]");
}
}
class Second extends Thread
{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
publicvoid run()
{
synchronized(fobj)
{
fobj.display(msg);
}
}
}
publicclass JavaSynchronize {
publicstaticvoid main(String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second(fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}
Output
[welcome]
[programmer]
[new]
Interthread Communication: Itis all about allowing
Output
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
Java join() method
The join() method in Java is provided by the java.lang.Thread class that permits
one thread to wait until the other thread to finish its execution. Suppose th be
the object the class Thread whose thread is doing its execution currently, then
the th.join(); statement ensures that th is finished before the program does the
execution of the next statement.
Ex:
class CustomThread implements Runnable {
publicvoid run() {
System.out.println(Thread.currentThread().getName() + " started.");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println(Thread.currentThread().getName() + " exited.");
}
}
publicclass ThreadJoin {
publicstaticvoid main(String[] args) throws InterruptedException {
CustomThread th=new CustomThread();
Thread t1 = new Thread( th, "Thread-1");
t1.start();
t1.join();
Thread t2 = new Thread( new CustomThread(), "Thread-2");
t2.start();
t2.join();
Thread t3 = new Thread( new CustomThread(), "Thread-3");
t3.start();
}
}
Output
Thread-1 started.
Thread-1 exited.
Thread-2 started.
Thread-2 exited.
Thread-3 started.
Thread-3 exited.
A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block.
public class Main
{
private int data=30;//instance variable
void display()
{
class Local
{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[])
{
Main obj=new Main();
obj.display();
}
}
Java Member Inner Class
In this example, we are creating a msg() method in the member inner class that
is accessing the private data member of the outer class.
Output:
nice fruits
Java anonymous inner class example using interface
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Output:
nice fruits
Java Abstract Window Toolkit(AWT)
AWT stands for Abstract Window Toolkit, developed by Sun Microsystems in
1995 and is a platform-dependent API used to develop Graphical User Interface
or window-based applications in Java. But the disadvantage of such an approach
is that GUI designed on one platform may look different when displayed on
another platform that means AWT component are platform dependent. AWT is
the foundation upon which Swing is made i.e Swing is an improved GUI API
that extends the AWT.
Window:The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.
Panel:The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components.
Frame:The Frame is the container that contain title bar and border and can
have menu bars. It can have other components like button, text field, scrollbar
etc. Frame is most widely used container while developing an AWT application.
Creating a Frame
There are two ways to create a Frame. They are,
import java.awt.*;
publicclass AWTFrame
{
AWTFrame()
{
Frame f=new Frame();
f.setSize(400, 500); //setting size.
f.setTitle("Welcome to AWT"); //setting title.
f.setLayout(null); //set default layout for frame.
f.setVisible(true);
f. setBackground(Color.yellow);
}
publicstaticvoid main(String args[])
{
AWTFrame af = new AWTFrame();
}
}
Creating Frame window by extending Frame class
import java.awt.*;
publicclassAWTFrameextends Frame
{
AWTFrame()
{
setSize(400, 500); //setting size.
setTitle("Welcome to AWT"); //setting title.
setLayout(null); //set default layout for frame.
setVisible(true);
setBackground(Color.yellow);
}
publicstaticvoid main(String args[])
{
AWTFrame af = new AWTFrame();
}
}
NOTE:
1. While creating a frame following two attributes are must for visibility of
the frame:
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then
you need to add it to the frame by using the method - add(Component's
Object);
3. You can add the following method also for resizing the frame -
setResizable(true);
Delegation Event Model in Java
Delegation Event Model in Java, the Delegation event model is based upon
Event Source, Event Listeners, and Event Objects.
Event Source is the class used to broadcast the events.
Event Listeners are the classes that receive notifications of events.
Event Object is the class object which describes the event.
In the Delegation model, a source generates an event and forwards it to one or
more listeners, where the listener waits until they receive an event. Once the
listener gets the event, it is processed by the listener, and then they return it. The
UI elements can delegate an event's processing to a separate function.
The essential advantage of the Delegation Event Model is that the application
logic is completely separated from the interface logic.
Registering the Source With Listener in Delegation Event Model
The different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the Type of event.
MouseListener program:
import java.awt.*;
import java.awt.event.*;
public class AWTMouseEvent extends Frame implements MouseListener
{
Label l;
AWTMouseEvent()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
import java.awt.*;
import java.awt.event.*;
MouseMotionEvent()
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
dispose();
});
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
new MouseMotionEvent();
Keyboard Events
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is
notified against KeyEvent. The KeyListener interface is found in java.awt.event
package, and it has three methods.
publicvoid actionPerformed(ActionEvent e)
{
if(e.getSource()==submit)
{
String tp = trainpass.getState() ? "Applied for Train
Concession" : "Not Applied for Train Concession";
display_details.setText(sdetails);
}
}
you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.
java.awt.event Adapter classes
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Program on Adapter class:
import java.awt.*;
import java.awt.event.*;
publicclass MouseAdClass extends MouseAdapter
{
Label l;
Frame f;
MouseAdClass()
{
f=new Frame();
f.addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
f.add(l);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
f.dispose();
}
});
}
publicvoid mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
publicvoid mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
}
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing Program
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class SwingProgram extends JFrame
{
JFrame f;
JLabel lsname;
JTextField tfsname;
JCheckBox jcb1,jcb2,jcb3;
JTextArea txadrs;
JRadioButton r1,r2,r3;
JButton sub;
JToggleButton button;
JPanel panel;
JComboBox cou;
JScrollPane spane;
JDialog d;
SwingProgram()
{
//Label creation
lsname= new JLabel("Name : ");
lsname.setBounds(50,100,100, 40 );
//Textbox creation
tfsname= new JTextField();
tfsname.setBounds(130,100,150, 40);
//Checkbox creation
jcb1 = new JCheckBox("Singing");
jcb2 = new JCheckBox("Dancing");
jcb3 = new JCheckBox("Reading");
jcb1.setBounds(60,150,150, 40);
jcb2.setBounds(60,170,150, 60);
jcb3.setBounds(60,190,150, 100);
//Radiobutton creation
r1=new JRadioButton("Male");
r2=new JRadioButton("Female");
r1.setBounds(60,220,100,30);
r2.setBounds(60,250,100,30);
//TextArea creation
txadrs=new JTextArea();
txadrs.setBounds(60,300,150, 100);
//ToggleButton creation
button=new JToggleButton();
button.setBounds(10,50,100, 50);
//Listbox creation
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
JList<String> list = new JList<>(l1);
list.setBounds(200,200, 75,75);
//Combobox creation
String dept[]={"BBA","BCA","MBA","MCA"};
cou=new JComboBox(dept);
cou.setBounds(250,400,100,30);
//Panel creation & place button
panel=new JPanel();
panel.setBounds(400,80,200,200);
sub=new JButton("Submit");
sub.setBounds(420,100, 100,100);
panel.add(sub);
panel.setBackground(Color.yellow);
//Dialog box creation
d=new JDialog(f,"Dialog example",true);
JButton b=new JButton("OK");
d.add(b);
d.setSize(400,400);
d.setVisible(true);
add(cou);
add(list);
add(txadrs);
add(r1);
add(r2);
add(jcb1);
add(jcb2);
add(jcb3);
add(lsname);
add(tfsname);
add(button);
add(panel);
setTitle("Students Details");
setSize(700,650);
setLayout(null);
setVisible(true);
}
Meaning A Java Application also known as The Java applet works on the client
application program is a type of side, and runs on the browser and
program that independently makes use of another application
executes on the computer. program so that we can execute it.
Requirement of Its execution starts with the It does not require the use of any
main( ) method main( ) method only. The use of main() method. Java applet
the main( ) is mandatory. initializes through init( ) method.
Installation We need to install the Java Java applet does not need to be
application first and obviously on pre-installed.
the local computer.
Operation It performs read and write tasks It cannot run the applications on
on a variety of files located on a any local computer.
local computer.
File access It can easily access a file or data It cannot access the file or data
available on a computer system found on any local system or
or device. computer.
Security Java applications are pretty Java applets are less reliable. So,
trusted, and thus, come with no they need to be safe.
security concerns.
Java Applet
Applet is a special type of java program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
java.awt.Component class
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
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.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
} }
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java.
Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
} }
/*
<applet code="First.class" width="300" height="300">
</applet> */
c:\>javac First.java
c:\>appletviewer First.java