Java Notes for beginners [Notes PDF]

 

What is Java

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by
Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling
is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the Oak name to Java.

History of Java

The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the
Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc. However, it was suited for internet programming. Later,
Java technology was incorporated by Netscape.
    The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was
developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members
started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e -business solutions, etc. There are
given significant points that describe the history of Java.

1)
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called
Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called
"Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called
Oak and was developed as a part of the Green project.
Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.


Features of Java

1) Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection
in Java.
2) Pure Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporates both data and behavior
.
3) Platform Independent
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code
is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).

4) Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox

5) Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java
robust.

6) Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.

7) Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.

8) High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code.

9) Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used
for creating distributed applications.

10) Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.

11) Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

• 

C++ Vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system programming. Java is mainly used for application programming. It is
widely used in window, web-based, enterprise and
mobile applications.
C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports multiple inheritance.
C++ supports
operator overloading.
Java doesn't support multiple inheritance through
class. It can be achieved by
interfaces in java.
Java doesn't support operator overloading.
C++ supports pointers. You can write pointer program
in C++.
Java supports pointer internally. However, you can't
write the pointer program in java. It means java has
restricted pointer support in java.
C++ uses compiler only. Java uses compiler and interpreter both.
C++ supports both call by value and call by reference. Java supports call by value only. There is no call by
reference in java.

First Java Program
Demo.java
class Demo
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}

Variables
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a
combination of "vary + able" that means its value can be changed.
Eg.
Int x=50;//Here x is variable
Types of Variables
There are three types of variables in java:
o local variable
o instance variable
o static variable

o 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.

o 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 Arithmetic Operator
o Shift Operator
o Relational Operator
o Bitwise Operator
o Logical Operator
o Ternary Operator
o Assignment Operator
o Increment and Decrement Operator
o Conditional Statements

1) if
2) if else
3) nested if else
4) else if ladder
5) switch
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
}
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
} e
lse
{
//code if condition is false
}
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types
like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch 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;
}

o Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
1) for loop
2) while loop
3) do-while loop
Java for Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.
There are three types of for loops in java.
o Simple For Loop
o For-each or Enhanced For Loop
o Labeled For Loop

Java Simple for Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}

Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
Java for-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because
we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array)
{
//code to be executed
}

Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have
nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}

Java while Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}

Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java
do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);

o Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the program
control resumes at the next statement following the loop.
The Java
break is used to break loop or switch statement. It breaks the current flow of the program at specified
condition. In case of inner loop, it breaks only inner loop.

o Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the next iteration of the
loop immediately. It can be used with for loop or while loop.
The Java
continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
---------------------------------------------------------------------------------

o What is an object in Java
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can
be physical or logical (tangible and intangible). The example of an intangible object is the banking system.

o What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects
are created. It is a logical entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

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.
Syntax : new Demo();

---------------------------------------------------------------------------------
Constructors in Java :-
1. It is a special type of method which is used to initialize the object.
2. Constructor name must be the same as its class name.
3. Constructor is called when an instance of the class is created.
4. A Constructor does not have explicit return type.
5. A Java constructor cannot be abstract, static, final, and synchronized.
Types Of Constructor :
1. Default Constructor :- A constructor is called "Default Constructor" when it doesn't have any
parameter.
2.
Parameterized Constructor :- A constructor which has a specific number of parameters is called a
parameterized constructor.
3.
Copy Constructor : A constructor which is used to copy values of one object into another object is
called as copy constructor.

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.
---------------------------------------------------------------------------------
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the
class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable
If you declare any variable as static, it is known as a static variable.
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 stude nts, etc.
o The static variable gets memory only once in the class area at the time of class loading.
class Student
{
int rollno;
String name;
static String college="IMR";
}

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.

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 classloading.
-----------------------------------------------------------------------------------------------------------------------------------
this keyword in java :-
this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
-----------------------------------------------------------------------------------------------------------------------------
Java Arrays
Normally, an array is a collection of similar type of elements which have a contiguous memory location.
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.
Types of Array in java
There are two types of array.
o One Dimensional Array (1D array)
o Multidimensional Array

One(Single) Dimensional Array in Java
Instantiation of an Array in Java
datatype arrayname[];
arrayname=
new datatype[size];

MultiDimensional Dimensional Array in Java
Datatype arrayname[][];
Arrayname=new datatype[row_size][col_size];

Anonymous Array in Java
Array without name is called as Anonymous array.
--------------------------------------------------------------------------------------------------------------------------
Java Command Line Arguments
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.
--------------------------------------------------------------------------------------
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading
.
If we have to perform only one operation, having same name of the methods increases the readability of the
program.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
--------------------------------------------------------------------------------------------------------------------------

Java String class
String is a standard class in Java.
Syntax : String obj=new String(“Hello”);
Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring(), equals(), equalsIgnoreCase(), trim() etc.
The java.lang.String class implements
Serializable, Comparable and CharSequence interfaces.
Methods of String class :-
1. length() :- It counts total number of characters in a given String.
Example :- String s=”Hello”;
s.length()
Output :- 5
2. toUpperCase() :- It converts whole string into
capital letters.
Example :- String s=”Hello”;
s.toUpperCase()
Output :- HELLO
3. toLowerCase() :- It converts whole string into
small case letters.
Example :- String s=”Hello”;
s.toLowerCase()
Output :- hello
4. charAt() :- It returns character at given position.
Example :- String s=”Hello”;
s.charAt(1)
Output :- e
5. indexOf() :- It returns index of given character.
Example :- String s=”IMR”;
s.indexOf(‘R’)
Output :- 2
--------------------------------------------------------------------------------------------------------------------------

Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as
String class except it is mutable i.e. it can be changed.
Methods :-
1. append(String s)
2. insert(int offset, String s)
3. replace(int startIndex, int endIndex, String str)
4. delete(int startIndex, int endIndex)
5. reverse()
6. capacity()
7. charAt(int index)
8. length()
9. substring(int beginIndex)

What is mutable string ?
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are
used for creating mutable string.

-----------------------------------------------------------------------------------------------------------------------------------
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
The eight classes of the
java.lang package are known as wrapper classes in Java. The list of eight wrapper
classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
--------------------------------------------------------------------------------------------------------------------------
Java Random class
Java Random class is used to generate a stream of pseudorandom numbers. The algorithms implemented by
Random class use a protected utility method than can supply up to 32 pseudorandomly generated bits on each
invocation.
Methods –
doubles(),ints(),longs(),next(),nextBoolean(),nextByte(),nextDouble(),nextFloat(),
nextInt(),nextLong()
--------------------------------------------------------------------------------------------------------------------------
Java Vector Class
Java Vector class comes under the java.util package. The vector class implements a growable array of objects.
Like an array, it contains the component that can be accessed using an integer index.
The following are the list of vector class methods:
add(),addAll(),addElement(),capacity(),clear(),clone(),contains(),copyInto(),
elementAt(),equals(),indexOf(),insertElementAt()
--------------------------------------------------------------------------------------------------------------------------
Stack Class in Java
Java Collection framework provides a Stack class which models and implements Stack data structure. The class
is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class
provides three more functions of empty, search and peek. The class can also be said to extend Vector and
treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass
of Vector.
Methods:=
1. push()
2. pop()
--------------------------------------------------------------------------------------------------------------------------
java.util.Date

The java.util.Date class represents date and time in java. It provides constructors and methods to deal with
date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been deprecated.
Methods:-
boolean after(Date date), boolean before(Date date), Object clone(),int compareTo(Date
date), boolean equals(Date date)
, long getTime(),int hashCode(),void setTime(long
time)
--------------------------------------------------------------------------------------------------------------------------
Java Calendar Class

Java Calendar class is an abstract class that provides methods for converting date between a specific instant in
time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable interface.
public void add(int field, int amount)
public boolean after (Object when)

public boolean before(Object when)
public int get(int field)
public String getCalendarType()
public int getActualMaximum(int field)
--------------------------------------------------------------------------------------------------------------------------
Java.util.GregorianCalendar Class in Java
GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either
from interface or abstract class) of a
Calendar that implements the most widely used Gregorian Calendar with
which we are familiar.
The major difference between
GregorianCalendar and Calendar classes are that the Calendar Class being an
abstract class cannot be instantiated. So an object of the
Calendar Class is initialized as:
Calendar cal = Calendar.getInstance();
So an object of the GregorianCalendar Class is initialized as:
GregorianCalendar gcal = new GregorianCalendar();
--------------------------------------------------------------------------------------------------------------------------
Java Reflection(Class class) :-

1. Java Reflection is a process of examining or modifying the behavior of a class at run time.
2. The
java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
3. The java.lang and java.lang.reflect packages provide classes for java reflection.
Methods of Class class :-
1. getName()
2. forName(String className)throws ClassNotFoundException
3. getDeclaredFields()
4. getDeclaredMethods()
5. getDeclaredConstructors()
6. isArray()
import java.lang.reflect.*;
class Demo
{
public static void main(String args[]) throws Exception
{
Class c1=Class.forName("java.util.Scanner");
System.out.println("Methods of Scanner class are as follows............");
Method m[]=c1.getMethods();
for(Method m1:m)
System.out.println(m1.getName());
}
}

--------------------------------------------------------------------------------------------------------------------------
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and
implements the Map interface.
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified
by calling the hashcode() method. A Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
Hashtable class Parameters
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Methods :
1. int hashCode()
2. boolean remove(Object key, Object value)
3. boolean isEmpty()
4. V get(Object key)
5. V put(K key, V value)
--------------------------------------------------------------------------------------------------------------------------
Java Math class
Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(),
tan(), round(), ceil(), floor(), abs() etc.
If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.
For other arithmetic operations like increment, decrement, divide, absolute value, and negation overflow occur
only with a specific minimum or maximum value. It should be checked against the maximum and minimum value as
appropriate.
class Demo
{
public static void main(String args[])
{
double x = 28;
double y = 4;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println(
"Square root of y is: " + Math.sqrt(y));
System.out.println(
"Logarithm of x is: " + Math.log(x));
}
}
--------------------------------------------------------------------------------------------------------------------------
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read input from the
keyboard, the java.util.Scanner class is one of them.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is
the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive
types such as int, long, double, byte, float, short, etc.
Methods :-
1. nextInt()
2. nextByte()
3. nextShort()
4. next()
5. nextLine()
6. nextDouble()
7. nextFloat()
8. nextBoolean()
How to create Object of Scanner
Scanner obj = new Scanner(System.in);
--------------------------------------------------------------------------------------------------------------------------
Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read
data line by line by readLine() method. It makes the performance fast. It inherits
Reader class.
Methods :-
1. int read()
2. int read(char[] cbuf, int off, int len)
3. boolean markSupported()
4. String readLine()
5. boolean ready()
6. long skip(long n)
7. void reset()

8. void mark(int readAheadLimit)
9. void close()
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=
new FileReader("D:\\testout.txt");
BufferedReader br=
new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((
char)i);
}
br.close();
fr.close();
}
}
--------------------------------------------------------------------------------------------------------------------------
Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machine -
independent way.
Java application generally uses the data output stream to write data that can later be read by a data input
stream.
Methods :-
1. int read(byte[] b)
2. int read(byte[] b, int off, int len)
3. int readInt()
4. byte readByte()
5. char readChar()
6. double readDouble()
7. boolean readBoolean()
8. int skipBytes(int x)
import java.io.*;
public class Demo1 {
public static void main(String[] args) throws IOException {
InputStream input =
new FileInputStream("D:\\testout.txt");
DataInputStream inst =
new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);

for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+
"-");
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
Inheritance represents the
IS-A relationship which is also known as a parent-child relationship.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The
extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

--------------------------------------------------------------------------------------------------------------------------
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java
.
In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
--------------------------------------------------------------------------------------------------------------------------
Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstrac t
and non-abstract methods (method with the body).
Abstraction in Java :-
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
--------------------------------------------------------------------------------------------------------------------------
final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final
can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is c alled 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. We will have detailed learning of these. Let's first
learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
2) Java final method
If you make any method as final, you cannot override it.
3) Java final class
If you make any class as final, you cannot extend it.
--------------------------------------------------------------------------------------------------------------------------
Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is
a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all th e methods in
an interface are declared with the empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
--------------------------------------------------------------------------------------------------------------------------
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but
a
class implements an interface.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

--------------------------------------------------------------------------------------------------------------------------
Java Inner Classes
1. Java inner class or nested class is a class which is declared inside the another class or interface.
2. We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
3. Additionally, it can access all the members of outer class including private data members and
methods.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Advantage of java inner classes :-
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is
it can access all the members (data members
and methods) of outer class
including private.
2) Nested classes are used
to develop more readable and maintainable code because it logically group classes
and interfaces in one place only.
3)
Code Optimization: It requires less code to write.
--------------------------------------------------------------------------------------------------------------------------
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[]){
System.out.println(
"Welcome to package");
}
}
--------------------------------------------------------------------------------------------------------------------------
Exception Handling in Java
1. The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
2. Exception is an abnormal condition. In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is thrown at runtime.
3. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses:
Exception and Error. A hierarchy of Java Exception classes are given below:

Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception

Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile -time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception.
t specifies that there may occur an exception in the method. It is always used with
method signature.

File Handling in Java
Java being one of the most popular programming languages provides extensive support to various
functionalities like database, sockets, etc. One such functionality is File Handling in Java. File
Handling is necessary to perform various tasks on a file, such as read, write, etc.
What is File Handling in Java?
File handling in Java implies reading from and writing data to a file. The File class from the java.io
package
, allows us to work with different formats of files. In order to use the File class, you need to
create an object of the class and specify the filename or directory name.
For example:
import java.io.*;
class Demo
{
public static void main(String args[])
{
File f=new File(“filename.txt”);
System.out.println(f.getName());
System.out.println(f.getPath());
}
}
Java uses the concept of a stream to make I/O operations on a file. So let’s now understand what is a
Stream in Java.
What is a Stream?
In Java, Stream is a sequence of data which can be of two types.
1. Byte Stream
This mainly incorporates with byte data. When an input is provided and executed with byte data,
then it is called the file handling process with a byte stream.
2. Character Stream
Character Stream is a stream which incorporates with characters. Processing of input data with
character is called the file handling process with a character stream.
Java File Methods
Below table depicts the various methods that are used for performing operations on Java files.
Method Type Description
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

File Operations in Java
Basically, you can perform four operations on a file. They are as follows:
1. Create a File
2. Reading data from file
3. Write to a file
4. Append data to a file
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the
OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
-----------------------------------------------------------------------------------------------

Java AWT

1. Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
2. Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system.
3. AWT is heavyweight i.e. its components are using the resources of OS.
4. The java.awt
package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton,
CheckBox, Choice, List etc.
Java AWT Hierarchy
Container :- The Container is a component in AWT that can contain another components
like
buttons, textfields, labels etc. The classes that extends Container class are known as container
such as Frame, Dialog and Panel.
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.
Panel :- The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame :- The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)
Simple Program to draw Frame by extending Frame class :-
import java.awt.*;
class Demo extends Frame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public static void main(String args[])
{
Demo d1=new Demo();
}
}
Graphics class :-

It is resides in java.awt package.
The Graphics class is the abstract super class for all graphics contexts which allow an application to
draw onto components that can be realized on various devices, or onto off-screen images as well.

A Graphics object encapsulates all state information required for the basic rendering operations
that Java supports. State information includes the following properties.
The Component object on which to draw.
A translation origin for rendering and clipping coordinates.
The current clip.
The current color.
The current font.
The current logical pixel operation function.
The current XOR alternation color
Methods of Graphics class :-
1. drawLine(int x1, int y1, int x2, int y2)
2. drawOval(int x, int y, int width, int height)
3. fillOval(int x, int y, int width, int height)
4. drawRect(int x, int y, int width, int height)
5. fillRect(int x, int y, int width, int height)
6. setColor(Color c)
7. setFont(Font font)
8. drawString(String str, int x, int y)
9. dispose()
10. drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
11. drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Font class :-
1. The Font class states fonts, which are used to render text in a visible way.
2. It is resides in java.awt package.
Font f = new Font("Arial", Font.BOLD, 24);
paint() method :-Whenever we want to perform graphical activity on the frame then we use
paint method. Paint() method takes only one argument of type Graphics class.
Syntax :-
public void paint(Graphics g)
{
------
------
}
Program to draw shapes on the frame(line,rectangle,circle) :-
import java.awt.*;
class Demo extends Frame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawLine(50,50,50,200);
g.drawRect(200,200,250,250);
g.drawOval(200,200,250,250);
g.drawString("Hello",80,80);
}
public static void main(String args[])
{
Demo d1=new Demo();
}
}
---------------------------------------------------------------------------------------------------------------------------
Java Swing

1. Java Swing provides platform-independent and lightweight components.
2. The
javax.swing package provides classes for java swing API such as JFrame, JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing

AWT Swing
AWT components are platform-dependent. Java swing components are platform-independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane
etc.
AWT doesn't follows MVC(Model View Controller)
where model represents data, view represents
presentation and controller acts as an interface
between model and view.
Swing follows MVC.

Hierarchy of Java Swing classes

Java Swing Examples
There are two ways to create a frame:
o By creating the object of JFrame class (association)
o By extending JFrame class (inheritance)
Program to draw shapes on the JFrame :-
import java.awt.*;
import javax.swing.*;
class Demo extends JFrame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public void paint(Graphics g)

{
g.drawLine(50,50,50,200);
g.drawRect(200,200,250,250);
g.drawOval(200,200,250,250);
g.drawString("Hello",80,80);
}
public static void main(String args[])
{
Demo d1=new Demo();
}
}
-----------------------------------------------------------------------------------------------------------------------------
Java Applet

Applet is a special type of 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:
1. It works at client side so less response time.
2. Secured
3. It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

Lifecycle of Applet :-

Q.Explain Life cycle of Java Applet .
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

For creating any applet java.applet package must be must be inherited. It provides 4 life cycle methods of
applet.
1.
public void init(): is used to initialized the Applet. It is invoked only once.
2.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4.
public void destroy(): is used to destroy the Applet. It is invoked only once.
---------------------------------------------------------------------------------------------------------------------------------------------------
Program to draw shapes on the Applet :-
import java.awt.*;
import java.applet.*;
public class Demo extends Applet
{
public void paint(Graphics g)
{
g.drawLine(50,50,50,200);
g.drawRect(100,100,150,150);
g.drawOval(100,100,150,150);
g.drawString("Hello",80,80);
}
public void init()
{
Demo d1=new Demo();
}
}
----------------------------------------------------------------------------------------------------------------------------- ------

إرسال تعليق (0)
أحدث أقدم