Notesjavadocx__2024_11_26_22_44_32
Notesjavadocx__2024_11_26_22_44_32
Notesjavadocx__2024_11_26_22_44_32
Lecture Notes/OHPs/PPTs
Introduction to Java
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. Java is to be Write Once, Run Anywhere..
The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations were built to
suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for
Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java
ME respectively. Java was developed by James Gosling.
Initially it was named as Oak.
Features of Java
● Simple
● Object-Oriented
● Portable
● Platform Independent
● Secured
● Robust
● Distributed
● Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).Java has
removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc. There is no need to remove unreferenced objects because there
is an Automatic Garbage Collection in Java.
Object Oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour Object-oriented programming (OOPs)
is a methodology that simplifies software development and maintenance by providing
some rules.
● Basic concepts of OOPs are:
● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because there are no explicit pointers.
Robust
Robust simply means strong. Java is robust because It uses strong memory
management.There is a lack of pointers that avoids security problems. There is automatic
garbage collection in java which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.There are exception handling
and the type checking mechanism in Java. All these points make Java robust.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
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).
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set
top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside
Gosling's office, also went by the name ‘Green’ and ended up later being renamed as
Java, from a list of random words. Sun released the first public implementation as Java
1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-
times on popular platforms. On 13 November, 2006, Sun released much of Java as free
and open source software under the terms of the GNU General Public License (GPL). On
8 May, 2007, Sun finished the process, making all of Java's core code free and
opensource, aside from a small portion of code to which Sun did not hold the copyright.
To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available
First java program
class Simple {
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
//This is my first program
/*this is My first program in java. In
this print
only a message*/
Explanation
● Public-It is an access specifier. We should use a public keyword before the main()
method so that JVM can identify the execution point of the program. If we use private,
protected, and default before the main() method, it will not be visible to JVM.
● Static-You can make a method static by using the keyword static. We should call
the main() method without creating an object. Static methods are the method which
invokes without creating the objects, so we do not need any object to call the main()
method.
● Void -In Java, every method has the return type. Void keyword acknowledges the
compiler that main() method does not return any value.
● Main()-It is a default signature which is predefined in the JVM. It is called by JVM
to execute a program line by line and end the execution after completion of this method..
● String args[]-The main() method also accepts some data from the user. It accepts a
group of strings, which is called a string array. It is used to hold the command line
arguments in the form of string values.
Question :: What happens if the main() method is written without String args[]?
Answer:: The program will compile, but not run, because JVM will not recognize the
main() method. Remember JVM always looks for the main() method with a string type
array as a parameter.
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:
1. Open notepad and add the code as above.
2. Save the file as: simple.java.
3. Open a command prompt window and go to the directory where you saved the
class.
4. Assume it's C:\
5. Type javac simple.java and press enter to compile your code. If there are no errors
in your code, the command prompt will take you to the next line (Assumption : The path
variable is set).
6. Now,type java simple' to run your program.
7. You will be able to see ' Hello World ' printed on the window.
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All
characters available inside any comment are ignored by Java compiler
Java Editions
● JAVA SE(Standard Edition)-To develop client side stand alone applications.
● JAVA ME(Micro Edition)-To develop applications for mobile devices.
● JAVA EE(Enterprise Edition)-To develop server side applications such as Java
servlets and Java server pages.
● JAVA SE(Standard Edition)-To develop client side stand alone applications.
● JAVA ME(Micro Edition)-To develop applications for mobile devices.
● JAVA EE(Enterprise Edition)-To develop server side applications such as Java
servlets and Java server pages.
Java Virtual Machine (JVM)
JVM is a engine that provides runtime environment to drive the Java Code or
applications. It converts Java bytecode into machines language. JVM is a part of Java
Run Environment (JRE). In other programming languages, the compiler produces
machine code for a particular system
JRE(Java Runtime Environment)
JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.”
The Java Runtime Environment provides the minimum requirements for executing a
Java application; it consists of the Java Virtual Machine (JVM), core classes, and
supporting files.
Data types In Java
Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values. In java we have two categories of data type:
1) Primitive data types
2) Non-primitive data types
Arrays and Strings are non-primitive data types, we will discuss them later
in the coming tutorials. Here we will discuss primitive data types and literals in Java.
Java is a statically typed language. A language is statically typed, if the data type of a
variable is known at compile time. This means that you must specify the type of the
variable (Declare the variable) before use it.
Example::
int num;
char name;
string abc;
So in order to use the variable num, name, abc in our program, we must declare it first as
shown above. It is a good programming practice to declare all the variables (that you are
going to use) in the beginning of the program.
1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double. Java developers included these data types to maintain the portability of java as
the size of these primitive data types do not change from one operating system to another.
● byte, short, int and long data types are used for storing whole numbers.
● float and double are used for fractional numbers.
● char is used for storing characters(letters).
● boolean data type is used for variables that holds either true or false.
● Byte:This can hold whole number between -128 and 127. Mostly used to save
memory and when you are certain that the numbers would be in the limit specified by
byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {
byte num;
char name;
num = 113;
name =”k”
System.out.println(num);
System.out.println(“name”);
}
}
Output:
113 k
Try the same program by assigning value assigning 150 value to variable num, you
would get type mismatch error because the value 150 is out of the range of byte data
type. The range of byte as I mentioned above is -128 to 127.
● short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte
short num = 45678;
● int: Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {
short num;
num = 150;
System.out.println(num);
}
}
Output:
150
The byte data type couldn’t hold the value 150 but a short data type can because it has a
wider range.
long:
Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {
boolean b = false;
System.out.println(b);
}
}
Output:
false
char: holds characters.
size: 2 bytes
class JavaExample {
public static void main(String[] args) {
char ch = 'Z';
System.out.println(ch);
}
}
Output:
Z
Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is an Integer literal.
char ch = 'A';
Here A is a char literal
● Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;
● Float Literals
Used for data type float and double.
double num1 = 22.4;
float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
● Char and String Literal
Used for char and String type.
char ch = 'Z';
String str = "BeginnersBook";
Variable
A variable is a name which is associated with a value that can be changed. For example
when I write int i=10; here variable name is i which is associated with value 10, int is a
data type that represents that this variable can hold integer values.
How to Declare a variable in Java
1) Variables naming cannot contain white spaces, for example: int num ber = 100; is
invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one words
do it like this: int smallNumber; int bigNumber;
4) Variable names are case sensitive in Java.
Java Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:
● Keywords
● Identifiers
● Constants
● Special Symbols
● Operators
Keywords:Keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing so,
we are trying to assign a new meaning to the keyword which is not
allowed. Java language support following keywords:
result = ~number;
System.out.println(result);
}
}
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding bits are
different, it gives 1. If corresponding bits are same, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
if (i > 15)
System.out.println("10 is less than 15");
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements
means an if statement inside an if statement. Yes, java allows us to nest if statements
within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example nested if
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Example –if else if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Switch case
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Switch case example
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Jump Statements
Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.
Break: In Java, break is majorly used for:
Terminate a sequence in a switch statement .
To exit a loop.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the innermost
loop.
Break example
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Continue:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the
loop’s end. The continue statement performs such an action.
Example of continue
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
if (t)
return;
class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: The main outside the class
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name with
the class name which has main() method.
class Rectangle
{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Constructor in JAVA
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
● Default constructor (no-arg constructor)
● Parameterized constructor
Default Constructor::A constructor is called "Default Constructor" when it doesn't have
any parameter.
Syntax of default constructor:
<class_name>()
{
}
Example-Default Constructor
● class Student3{
● int id;
● String name;
● //method to display the value of id and name
● void display(){System.out.println(id+" "+name);}
●
● public static void main(String args[]){
● //creating objects
● Student3 s1=new Student3();
● Student3 s2=new Student3();
● //displaying values of the object
● s1.display();
● s2.display();
● }
}
Parameterized Constructor::A constructor which has a specific number of parameters
is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Example
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate
super class.
Example of Child class referring Parent class property using super keyword
In this example we will only focus on accessing the parent class property or variables.
class Parent
{
String name;
}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Parent
Child
Super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate
super class.
Example
class Parent
{
String name;
}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Abstraction 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).
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
● Interface (100%)
● Abstract class
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
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of
the method.
Example of abstract class
abstract class A
{
}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known
as an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Terms used in Inheritance
● Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
● 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.
● 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.
● 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.
Syntax
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Example
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
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.
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends
the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class
extends the child class. For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class
A.
Multiple Inheritance: refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both
classes A and B. Java doesn’t support multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single
program. For example class A & B extends class C and another class D extends class A
then this is a hybrid inheritance example because it is a combination of single and
hierarchical inheritance.
Single Inheritance
When a class extends to another class then it forms single inheritance. In the below
example, we have two classes in which class A extends to class B that forms single
inheritance.
class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}
}
}
a=10
Here, we can notice that show() method is declared in class A, but using child class
Demo object, we can call it. That shows the inheritance between these two classes.
Multilevel Inheritance
When a class extends to another class that also extends some other class forms a
multilevel inheritance. For example a class C extends to class B that also extends to class
A and all the data members an methods of class A and B are now accessible in class C.
Example:
class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}
class B extends A{
int b = 10;
void showB() {
System.out.println("b = "+b);
}
}
class A{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}
class B extends A{
int b = 10;
void showB() {
System.out.println("b = "+b);
}
}
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.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
● It is used to achieve abstraction.
● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.
Syntax for Interface
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>{
The static keyword in JAVA is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
The static can be:
● Variable (also known as a class variable)
● Method (also known as a class method)
Java static variable ::If you declare any variable as static, it is known as a static
variable.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.The static variable gets memory only once in the class area
at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Example
class Student{
int rollno;
String name;
String college="CGC";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects.If we make it static, this field will get the memory only
once.
Example
class Student{
int rollno;//instance variable
String name;
static String college ="CGC";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display ()
{
{System.out.println(rollno+" "+name+" "+college);
}
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
1. class abc {
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
11. By Using equals() Method
12. class abc{
13. public static void main(String args[]){
14. String s1="Sachin";
15. String s2="Sachin";
16. String s3=new String("Sachin");
17. String s4="Saurav";
18. System.out.println(s1.equals(s2));//true
19. System.out.println(s1.equals(s3));//true
20. System.out.println(s1.equals(s4));//false
21. }
22. }
By using == method
The == operator compares references not values.
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpoo
l)
8. }
9. }
Java String substring()
The Java String class substring() method returns a part of the string.We pass beginIndex
and endIndex number position in the Java substring method where beginIndex is
inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0,
whereas the endIndex starts from 1.
There are two types of substring methods in Java string.
public String substring(int startIndex) // type - 1
and
public String substring(int startIndex, int endIndex) // type - 2
APPLETS
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Explanation
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.
5. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
11. html>
12. <body>
13. <applet code="First.class" width="300" height="300">
14. </applet>
15. </body>
16. </html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is
not required but it is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
Program-1(Applet LifeCycle)
import java.applet.*;
import java.awt.*;
public class AppletLifeCycle extends Applet {
public void init()
{
System.out.println("init() called");
}
public void start ()
{
System.out.println("start() called");
Program-2(Graphics)
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Welcome",50, 50);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}
Program-3
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
//g.setColor(Color.black);
g.drawString("Welcome",50, 50);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(20,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple exam
event handling in applet that prints a message by click on the button.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300"> </applet>
</body>
</html>
Program-1(Event Handling)
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.List;
import java.awt.TextArea;
import java.awt.TextField;
class Myframe extends Frame
{
Myframe()
{
FlowLayout l1=new FlowLayout();
setLayout(l1);
Label label1=new Label("Name");
TextField t1=new TextField("BCA -5",10);
t1.setEchoChar('*');//Method used for password textfield
add(label1);
add(t1);
add(text);
add(b1);
add(c1);
add(c2);
add(gender);
add(female);
add(male);
add(choice);
add(lst1);
}
}
Program-2
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Program-3
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){