SlideShare a Scribd company logo
• 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 projectto 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 projectin June 1991. The
small team of sun engineerscalled 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. Accordingto 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 objectsbecause 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 differenttypes 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 runson 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 checkingmechanism in Java. All these points make Java
robust.
6) Architecture-neutral
Java is architecture neutral because there are no implementation dependentfeatures, 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 usersto create distributed applications in Java. RMI and EJB are used
for creating distributed applications.
10) Multi-threaded
A thread is like a separate program, executingconcurrently. 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. Java doesn't support multiple inheritance through
class. It can be achieved by interfaces in java.
C++ supports operator overloading. 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(Stringargs[])
{
System.out.println("HelloWorld");
}
}
• 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 differentsizes 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 performoperations. 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 DecrementOperator
o ConditionalStatements
1) if
2) if else
3) nestedif else
4) else if ladder
5) switch
Java If Statement
The Java if statement tests the condition. It executesthe 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 executesthe 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
}
Java Nested if statement
The nested if statement representsthe if block within another if block. Here,the inner if block condition
executesonly 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 executesone 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/decrementvalue.
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 currentflow of the program at specified
condition. In case of inner loop, it breaks only inner loop.
o Java ContinueStatement
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 currentflow 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
Anonymousobject
Anonymous simply means nameless. An object which has no reference isknown 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 explicitreturn 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 differenttask. 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 students, 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 refersto the currentobject.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer currentclass instance variable.
2. this can be used to invoke currentclass method (implicitly)
3. this() can be used to invoke currentclass 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 Overloadingin 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 numberof characters in a given String.
Example :- String s=”Hello”;
s.length()
Output:- 5
2. toUpperCase():- Itconvertswhole string into capital letters.
Example :- String s=”Hello”;
s.toUpperCase()
Output:- HELLO
3. toLowerCase() :- Itconvertswhole stringinto small case letters.
Example :- String s=”Hello”;
s.toLowerCase()
Output:- hello
4. charAt() :- It returnscharacter at givenposition.
Example :- String s=”Hello”;
s.charAt(1)
Output:- e
5. indexOf() :- Itreturnsindex of givencharacter.
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 exceptit 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 providesthe 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 representsdate 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 CalendarClass
Java Calendar class is an abstract class that providesmethods 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.GregorianCalendarClass 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(Classclass) :-
1. Java Reflection is a process of examining or modifying the behavior of a class at run time.
2. The java.lang.Class class providesmany 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.
Methodsof Classclass :-
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(Stringargs[]) throwsException
{
Class c1=Class.forName("java.util.Scanner");
System.out.println("Methodsof Scannerclassare as follows............");
Methodm[]=c1.getMethods();
for(Methodm1:m)
System.out.println(m1.getName());
}
}
--------------------------------------------------------------------------------------------------------------------------
Java Hashtableclass
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 providesvarious 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 DataInputStreamClass
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 acquiresall the propertiesand behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
Inheritance representsthe 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 extendsSuperclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derivesfrom 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 providesthe 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 overridingis used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overridingis 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 abstract
and non-abstract methods (method with the body).
Abstractionin Java:-
Abstraction is a processof 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 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. 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 the 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 implementsan 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 representa 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 requiresless 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 Handlingin Java
1. The ExceptionHandling in Java is one of the powerfulmechanismtohandle the runtime
errors so that normal flow of the application can be maintained.
2. Exceptionis an abnormal condition.In Java, an exceptionisan eventthatdisruptsthe
normal flowof the program. Itis an objectwhichis thrownat runtime.
3. ExceptionHandling is a mechanismto handle runtime errorssuch 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.Accordingto 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 exceptRuntimeException 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 exceptionse.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 whichmeans we can't use catch block alone. It can be followedby finally
block later.
finally The "finally" block is used to execute the important code of the program.
It is executed whether anexception 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 anexception.
t specifies that there may occur anexception in the method. It is always used with
method signature.
File Handling in Java
Java beingone of the mostpopular programminglanguagesprovidesextensive supporttovarious
functionalitieslike database, sockets,etc.One suchfunctionality is File Handling in Java.File
Handling is necessarytoperformvarioustaskson a file, such as read,write,etc.
What is File HandlinginJava?
File handling in Java implies reading from and writing data to a file. The File class from the java.io
package, allows us to workwith differentformatsof files.Inorderto use the File class, you need to
create an objectof the class and specifythe filename or directoryname.
For example:
import java.io.*;
class Demo
{
public static void main(Stringargs[])
{
File f=newFile(“filename.txt”);
System.out.println(f.getName());
System.out.println(f.getPath());
}
}
Java usesthe conceptof a streamto make I/Ooperationson a file. Solet’s now understandwhatis a
Streamin Java.
What is a Stream?
In Java,Streamis a sequence of datawhich can be of twotypes.
1. Byte Stream
This mainly incorporates with byte data. When an input is provided and executed with byte data,
thenit is called the file handling processwith 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 processwitha character stream.
Java File Methods
Belowtable depictsthe various methodsthatare usedforperformingoperationsonJava 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 Operationsin Java
Basically, youcan performfouroperationson a file. Theyare as follows:
1. Create a File
2. Readingdata from file
3. Write to a file
4. Appenddatato a file
Reading and Writing Files
As describedearlier,a streamcan be definedasa sequence of data.The InputStream is usedto read
data froma source and the OutputStream is usedfor writing data to a destination.
Here is a hierarchyof classesto deal with Inputand Outputstreams.
-----------------------------------------------------------------------------------------------
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 resourcesof 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 componentin AWT that can contain anothercomponents
like buttons,textfields,labelsetc.The classesthat extendsContainerclassare knownas container
such as Frame,Dialog and Panel.
Window:- The windowis the container that have no bordersand menubars.You must use frame,
dialog or anotherwindowforcreating a window.
Panel :- The Panel is the container that doesn'tcontaintitle bar andmenubars. It can have other
componentslike button,textfieldetc.
Frame :- The Frame is the containerthat contain title bar andcan have menubars.It can have other
componentslike button,textfieldetc.
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 extendingFrame class :-
import java.awt.*;
class Demo extendsFrame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public static void main(Stringargs[])
{
Demod1=newDemo();
}
}
Graphics class :-
It is residesin java.awtpackage.
The Graphics class is the abstract super class for all graphics contexts which allow an application to
draw ontocomponentsthatcan be realized onvarious devices,oronto off-screenimagesaswell.
A Graphics object encapsulates all state information required for the basic rendering operations
that Java supports.State informationincludesthe following properties.
• The Componentobjectonwhichto draw.
• A translation origin for renderingandclipping coordinates.
• The current clip.
• The current color.
• The current font.
• The current logical pixel operationfunction.
• The current XORalternation color
Methodsof Graphicsclass :-
1. drawLine(intx1,int y1, int x2, int y2)
2. drawOval(intx,int y, int width, int height)
3. fillOval(int x,int y,int width,int height)
4. drawRect(intx,int y, int width,int height)
5. fillRect(int x,int y, int width,int height)
6. setColor(Colorc)
7. setFont(Fontfont)
8. drawString(Stringstr,int x,int y)
9. dispose()
10. drawArc(intx,int y, int width, int height,int startAngle,int arcAngle)
11. drawImage(Imageimg,int x,int y, int width,int height,ImageObserverobserver)
Font class :-
1. The Font class statesfonts,which are usedto rendertextin a visible way.
2. It is residesin java.awt package.
Font f = new Font("Arial", Font.BOLD, 24);
paint() method :-Whenever wewantto performgraphicalactivity on theframethen weuse
paintmethod.Paint() method takesonly oneargumentof typeGraphicsclass.
Syntax :-
public void paint(Graphicsg)
{
------
------
}
Program to draw shapes on the frame(line,rectangle,circle) :-
import java.awt.*;
class Demo extendsFrame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public void paint(Graphicsg)
{
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(Stringargs[])
{
Demod1=newDemo();
}
}
---------------------------------------------------------------------------------------------------------------------------
Java Swing
1. Java Swingprovidesplatform-independentandlightweightcomponents.
2. The javax.swing package providesclassesfor javaswing APIsuch as JFrame, JButton,
JTextField,JTextArea,JRadioButton,JCheckbox,JMenu,JColorChooseretc.
Differencebetween 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 representsdata, 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 twoways 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 extendsJFrame
{
Demo()
{
setVisible(true);
setSize(500,500);
setBackground(Color.yellow);
}
public void paint(Graphicsg)
{
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(Stringargs[])
{
Demod1=newDemo();
}
}
-----------------------------------------------------------------------------------------------------------------------------
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.
Advantageof Applet
There are manyadvantagesof applet.Theyare as follows:
1. It worksat client side so lessresponse time.
2. Secured
3. It can be executedbybrowsersrunningundermanyplateforms,includingLinux, Windows,
Mac Os etc.
Lifecycle of Applet :-
Q.Explain Life cycle of JavaApplet.
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 provides4 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 todraw shapesonthe Applet:-
import java.awt.*;
import java.applet.*;
publicclass Demo extendsApplet
{
publicvoid paint(Graphicsg)
{
g.drawLine(50,50,50,200);
g.drawRect(100,100,150,150);
g.drawOval(100,100,150,150);
g.drawString("Hello",80,80);
}
publicvoid init()
{
Demo d1=newDemo();
}
}
-----------------------------------------------------------------------------------------------------------------------------------

More Related Content

What's hot

Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
mahir jain
 
Java Collections
Java  Collections Java  Collections
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
R. Sosa
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
Ravi_Kant_Sahu
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 
core java
core javacore java
core java
Roushan Sinha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
Prof. Dr. K. Adisesha
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
Core java
Core java Core java
Core java
Ravi varma
 
Oops in java
Oops in javaOops in java
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
How keywords and reserved words differ?
How keywords and reserved words differ?How keywords and reserved words differ?
How keywords and reserved words differ?
Ajay Chimmani
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Lovely Professional University
 

What's hot (20)

Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
core java
core javacore java
core java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Core java
Core java Core java
Core java
 
Oops in java
Oops in javaOops in java
Oops in java
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
How keywords and reserved words differ?
How keywords and reserved words differ?How keywords and reserved words differ?
How keywords and reserved words differ?
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 

Similar to Java notes | All Basics |

java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
JitendraYadav351971
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
SuganthiDPSGRKCW
 
Java Tutorial to Learn Java Programming
Java Tutorial to Learn Java ProgrammingJava Tutorial to Learn Java Programming
Java Tutorial to Learn Java Programming
business Corporate
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Java basic
Java basicJava basic
Java basic
Pooja Thakur
 
Java (1)
Java (1)Java (1)
Java (1)
Samraiz Tejani
 
Getting Started with JAVA
Getting Started with JAVAGetting Started with JAVA
Getting Started with JAVA
ShivamPathak318367
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
manish kumar
 
Java buzzwords.pptx
Java buzzwords.pptxJava buzzwords.pptx
Java buzzwords.pptx
BHARATH KUMAR
 
1 .java basic
1 .java basic1 .java basic
1 .java basic
Indu Sharma Bhardwaj
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
prat0ham
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
Mukesh Tekwani
 
Java Basics
Java BasicsJava Basics
Java Basics
Fahad Shahzad
 
Java
JavaJava
Java
seenak
 
Presentation on java
Presentation on javaPresentation on java
Presentation on java
william john
 
Java programming language
Java programming languageJava programming language
Java programming language
SubhashKumar329
 
java slides
java slidesjava slides
java slides
RizwanTariq18
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
prstsomnath22
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
yearninginjava
 
Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
SanthiNivas
 

Similar to Java notes | All Basics | (20)

java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Java Tutorial to Learn Java Programming
Java Tutorial to Learn Java ProgrammingJava Tutorial to Learn Java Programming
Java Tutorial to Learn Java Programming
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Java basic
Java basicJava basic
Java basic
 
Java (1)
Java (1)Java (1)
Java (1)
 
Getting Started with JAVA
Getting Started with JAVAGetting Started with JAVA
Getting Started with JAVA
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 
Java buzzwords.pptx
Java buzzwords.pptxJava buzzwords.pptx
Java buzzwords.pptx
 
1 .java basic
1 .java basic1 .java basic
1 .java basic
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java
JavaJava
Java
 
Presentation on java
Presentation on javaPresentation on java
Presentation on java
 
Java programming language
Java programming languageJava programming language
Java programming language
 
java slides
java slidesjava slides
java slides
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
 

Recently uploaded

NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
nitinpv4ai
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
National Information Standards Organization (NISO)
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
nitinpv4ai
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Henry Hollis
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
indexPub
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 

Recently uploaded (20)

NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)Oliver Asks for More by Charles Dickens (9)
Oliver Asks for More by Charles Dickens (9)
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsxData Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
 

Java notes | All Basics |

  • 1. • 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 projectto 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 projectin June 1991. The small team of sun engineerscalled 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.
  • 2. 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. Accordingto 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 objectsbecause 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 differenttypes 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
  • 3. 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 runson 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 checkingmechanism in Java. All these points make Java robust. 6) Architecture-neutral Java is architecture neutral because there are no implementation dependentfeatures, 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 usersto create distributed applications in Java. RMI and EJB are used for creating distributed applications. 10) Multi-threaded A thread is like a separate program, executingconcurrently. 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).
  • 4. • 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. Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java. C++ supports operator overloading. 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(Stringargs[]) { System.out.println("HelloWorld"); } } • 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
  • 5. o Data Types in Java Data types specify the differentsizes 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 performoperations. 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 DecrementOperator
  • 6. o ConditionalStatements 1) if 2) if else 3) nestedif else 4) else if ladder 5) switch Java If Statement The Java if statement tests the condition. It executesthe 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 executesthe 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 } Java Nested if statement The nested if statement representsthe if block within another if block. Here,the inner if block condition executesonly when outer if block condition is true. Syntax: if(condition){ //code to be executed if(condition){ //code to be executed } }
  • 7. Java Switch Statement The Java switch statement executesone 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/decrementvalue. Syntax:
  • 8. 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 }
  • 9. 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 currentflow of the program at specified condition. In case of inner loop, it breaks only inner loop. o Java ContinueStatement 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 currentflow 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
  • 10. o Nested class and interface Anonymousobject Anonymous simply means nameless. An object which has no reference isknown 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 explicitreturn 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 differenttask. 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
  • 11. 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 students, 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 refersto the currentobject. Usage of java this keyword Here is given the 6 usage of java this keyword. 1. this can be used to refer currentclass instance variable. 2. this can be used to invoke currentclass method (implicitly) 3. this() can be used to invoke currentclass constructor.
  • 12. 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
  • 13. 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 Overloadingin 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.
  • 14. Methods of String class :- 1. length() :- It counts total numberof characters in a given String. Example :- String s=”Hello”; s.length() Output:- 5 2. toUpperCase():- Itconvertswhole string into capital letters. Example :- String s=”Hello”; s.toUpperCase() Output:- HELLO 3. toLowerCase() :- Itconvertswhole stringinto small case letters. Example :- String s=”Hello”; s.toLowerCase() Output:- hello 4. charAt() :- It returnscharacter at givenposition. Example :- String s=”Hello”; s.charAt(1) Output:- e 5. indexOf() :- Itreturnsindex of givencharacter. 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 exceptit 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)
  • 15. 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 providesthe 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() --------------------------------------------------------------------------------------------------------------------------
  • 16. 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 representsdate 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 CalendarClass Java Calendar class is an abstract class that providesmethods 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)
  • 17. public boolean before(Object when) public int get(int field) public String getCalendarType() public int getActualMaximum(int field) -------------------------------------------------------------------------------------------------------------------------- Java.util.GregorianCalendarClass 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(Classclass) :- 1. Java Reflection is a process of examining or modifying the behavior of a class at run time. 2. The java.lang.Class class providesmany 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. Methodsof Classclass :- 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(Stringargs[]) throwsException { Class c1=Class.forName("java.util.Scanner"); System.out.println("Methodsof Scannerclassare as follows............"); Methodm[]=c1.getMethods(); for(Methodm1:m) System.out.println(m1.getName()); } }
  • 18. -------------------------------------------------------------------------------------------------------------------------- Java Hashtableclass 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;
  • 19. 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 providesvarious 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()
  • 20. 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 DataInputStreamClass 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);
  • 21. 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 acquiresall the propertiesand behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). Inheritance representsthe 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 extendsSuperclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derivesfrom 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.
  • 22. -------------------------------------------------------------------------------------------------------------------------- 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 providesthe specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
  • 23. Usage of Java Method Overriding o Method overridingis used to provide the specific implementation of a method which is already provided by its superclass. o Method overridingis 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 abstract and non-abstract methods (method with the body). Abstractionin Java:- Abstraction is a processof 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.
  • 24. -------------------------------------------------------------------------------------------------------------------------- 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 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. 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.
  • 25. 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 the 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 implementsan 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.
  • 26. -------------------------------------------------------------------------------------------------------------------------- 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 representa 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 requiresless code to write. --------------------------------------------------------------------------------------------------------------------------
  • 27. 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 Handlingin Java 1. The ExceptionHandling in Java is one of the powerfulmechanismtohandle the runtime errors so that normal flow of the application can be maintained. 2. Exceptionis an abnormal condition.In Java, an exceptionisan eventthatdisruptsthe normal flowof the program. Itis an objectwhichis thrownat runtime. 3. ExceptionHandling is a mechanismto handle runtime errorssuch 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:
  • 28. Types of Java Exceptions There are mainly two types of exceptions: checked and unchecked.Here, an error is considered as the unchecked exception.Accordingto Oracle,there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception
  • 29. Difference between Checked and Unchecked Exceptions 1) Checked Exception The classes which directly inherit Throwable class exceptRuntimeException 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 exceptionse.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 whichmeans we can't use catch block alone. It can be followedby finally block later. finally The "finally" block is used to execute the important code of the program. It is executed whether anexception 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 anexception. t specifies that there may occur anexception in the method. It is always used with method signature. File Handling in Java Java beingone of the mostpopular programminglanguagesprovidesextensive supporttovarious functionalitieslike database, sockets,etc.One suchfunctionality is File Handling in Java.File Handling is necessarytoperformvarioustaskson a file, such as read,write,etc. What is File HandlinginJava?
  • 30. File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to workwith differentformatsof files.Inorderto use the File class, you need to create an objectof the class and specifythe filename or directoryname. For example: import java.io.*; class Demo { public static void main(Stringargs[]) { File f=newFile(“filename.txt”); System.out.println(f.getName()); System.out.println(f.getPath()); } } Java usesthe conceptof a streamto make I/Ooperationson a file. Solet’s now understandwhatis a Streamin Java. What is a Stream? In Java,Streamis a sequence of datawhich can be of twotypes. 1. Byte Stream This mainly incorporates with byte data. When an input is provided and executed with byte data, thenit is called the file handling processwith 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 processwitha character stream. Java File Methods Belowtable depictsthe various methodsthatare usedforperformingoperationsonJava 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
  • 31. File Operationsin Java Basically, youcan performfouroperationson a file. Theyare as follows: 1. Create a File 2. Readingdata from file 3. Write to a file 4. Appenddatato a file Reading and Writing Files As describedearlier,a streamcan be definedasa sequence of data.The InputStream is usedto read data froma source and the OutputStream is usedfor writing data to a destination. Here is a hierarchyof classesto deal with Inputand Outputstreams. ----------------------------------------------------------------------------------------------- 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 resourcesof OS. 4. The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
  • 32. Java AWT Hierarchy Container:- The Container is a componentin AWT that can contain anothercomponents like buttons,textfields,labelsetc.The classesthat extendsContainerclassare knownas container such as Frame,Dialog and Panel. Window:- The windowis the container that have no bordersand menubars.You must use frame, dialog or anotherwindowforcreating a window. Panel :- The Panel is the container that doesn'tcontaintitle bar andmenubars. It can have other componentslike button,textfieldetc. Frame :- The Frame is the containerthat contain title bar andcan have menubars.It can have other componentslike button,textfieldetc.
  • 33. 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 extendingFrame class :- import java.awt.*; class Demo extendsFrame { Demo() { setVisible(true); setSize(500,500); setBackground(Color.yellow); } public static void main(Stringargs[]) { Demod1=newDemo(); } } Graphics class :- It is residesin java.awtpackage. The Graphics class is the abstract super class for all graphics contexts which allow an application to draw ontocomponentsthatcan be realized onvarious devices,oronto off-screenimagesaswell.
  • 34. A Graphics object encapsulates all state information required for the basic rendering operations that Java supports.State informationincludesthe following properties. • The Componentobjectonwhichto draw. • A translation origin for renderingandclipping coordinates. • The current clip. • The current color. • The current font. • The current logical pixel operationfunction. • The current XORalternation color Methodsof Graphicsclass :- 1. drawLine(intx1,int y1, int x2, int y2) 2. drawOval(intx,int y, int width, int height) 3. fillOval(int x,int y,int width,int height) 4. drawRect(intx,int y, int width,int height) 5. fillRect(int x,int y, int width,int height) 6. setColor(Colorc) 7. setFont(Fontfont) 8. drawString(Stringstr,int x,int y) 9. dispose() 10. drawArc(intx,int y, int width, int height,int startAngle,int arcAngle) 11. drawImage(Imageimg,int x,int y, int width,int height,ImageObserverobserver) Font class :- 1. The Font class statesfonts,which are usedto rendertextin a visible way. 2. It is residesin java.awt package. Font f = new Font("Arial", Font.BOLD, 24); paint() method :-Whenever wewantto performgraphicalactivity on theframethen weuse paintmethod.Paint() method takesonly oneargumentof typeGraphicsclass. Syntax :- public void paint(Graphicsg) { ------ ------ } Program to draw shapes on the frame(line,rectangle,circle) :-
  • 35. import java.awt.*; class Demo extendsFrame { Demo() { setVisible(true); setSize(500,500); setBackground(Color.yellow); } public void paint(Graphicsg) { 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(Stringargs[]) { Demod1=newDemo(); } } --------------------------------------------------------------------------------------------------------------------------- Java Swing 1. Java Swingprovidesplatform-independentandlightweightcomponents. 2. The javax.swing package providesclassesfor javaswing APIsuch as JFrame, JButton, JTextField,JTextArea,JRadioButton,JCheckbox,JMenu,JColorChooseretc. Differencebetween 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 representsdata, view represents presentation and controller acts as an interface between model and view. Swing follows MVC.
  • 36. Hierarchy of Java Swing classes Java Swing Examples There are twoways 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 extendsJFrame { Demo() { setVisible(true); setSize(500,500); setBackground(Color.yellow); } public void paint(Graphicsg)
  • 37. { 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(Stringargs[]) { Demod1=newDemo(); } } ----------------------------------------------------------------------------------------------------------------------------- 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. Advantageof Applet There are manyadvantagesof applet.Theyare as follows: 1. It worksat client side so lessresponse time. 2. Secured 3. It can be executedbybrowsersrunningundermanyplateforms,includingLinux, Windows, Mac Os etc. Lifecycle of Applet :- Q.Explain Life cycle of JavaApplet. 1. Applet is initialized. 2. Applet is started. 3. Applet is painted. 4. Applet is stopped. 5. Applet is destroyed.
  • 38. For creating any applet java.applet package must be must be inherited. It provides4 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 todraw shapesonthe Applet:- import java.awt.*; import java.applet.*; publicclass Demo extendsApplet { publicvoid paint(Graphicsg) { g.drawLine(50,50,50,200); g.drawRect(100,100,150,150); g.drawOval(100,100,150,150); g.drawString("Hello",80,80); } publicvoid init() { Demo d1=newDemo(); } } -----------------------------------------------------------------------------------------------------------------------------------