Java Object-Oriented Programming Basics
Java Object-Oriented Programming Basics
MODULE 1
Object Oriented Programming Using Java
The Java Language:
• Java was initiated by James Gosling and others at Sun Microsystems in 1991.
• Team: Mike Sheridan and Patrick Naughton
• This language was initially called “OAK”.
• Later it was renamed as “JAVA” in 1995.
• It is one of the world’s most widely used computer language.
• From practical point of view, it is an excellent language to learn.
• Java was perfect for the Web.
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ supports both call by value and Java supports call by value only.
call by reference. There is no call by reference in java.
Features of Java
The Java Features are:
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 1
Object Oriented Programming Using Java MMC202
\
Simple
• Java is very easy to learn, and its syntax is simple,clean and easy to understand.
According to Sun Microsystem, 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 rarelyused 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 incorporate both data and behavior.
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.
Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Robust
• Java provides automatic garbage collection 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.
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 2
Object Oriented Programming Using Java MMC202
\
High Performance
• Bytecode is highly optimised.
• JVM execute Bytecode much faster
Multithreaded
• Multithreading means handling more than one job at a time.
• The main advantage of multi-threading is that it shares the same memory.
Distributed
• Java programs can be shared over the internet
• Inheritance:
o When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance.
• Polymorphism:
o we can perform a single action in different ways.
o Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
o There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
o We can perform polymorphism in java by method overloading and
method overriding.
• Encapsulation:
o Binding (or wrapping) code and data together into a single unit is
known as encapsulation.
Advantages of Inheritance
Flexibility: Inheritance makes the code flexible to change, as you will adjust only in
one place, and the rest of the code will work smoothly.
Overriding: With the help of Inheritance, you can override the methods of the base
class.
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 3
Object Oriented Programming Using Java MMC202
\
Data Hiding: The base class in Inheritance decides which data to be kept private,
such that the derived class will not be able to alter it.
Data Abstraction
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
JVM
• JVM (Java Virtual Machine) is an abstract machine
• It is called a virtual machine because it doesn't physically exist.
• It is a specification that provides a runtime environment in which Java bytecode
can be executed.
• It can also run those programs which are written in other languages and compiled
to Java bytecode.
• JVMs are available for many hardware and software platforms.
• JVM, JRE, and JDK are platform dependent because the configuration of each OS
is different from each other. However, Java is platform independent.
JRE
• JRE is an acronym for Java Runtime Environment.
• It is also written as Java RTE. The Java Runtime Environment is a set of software
tools which are used for developing Java applications.
• It is used to provide the runtime environment. It is the implementation of JVM.
• It physically exists. It contains a set of libraries + other files that JVM uses at
runtime.
JDK
JDK (Java Development Kit) is a software development kit required to develop
applications in Java.
• you download JDK, JRE is also downloaded with it.
• In addition to JRE, JDK also contains a number of development tools (compilers,
JavaDoc, Java Debugger, etc).
How Java Code Runs?
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 4
Object Oriented Programming Using Java MMC202
\
Introducing Classes:
• 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:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface
• An object is an instance of a class.
type method1(parameters){
//body of the method
}
type method2(parameters){
//body of the method
}
//…..
type methodN(parameters){
//body of the method
}
}
Objects
• A Java object is a member (also called an instance) of a Java class.
• Each object has an identity, a behavior and a state. The state of an object is stored
in fields (variables), while methods (functions) display the object's behavior.
Creating an Object
There are three steps when creating an object from a class
• Declaration - A variable declaration with a variable name with an object type.
• Instantiation - The 'new' keyword is used to create the object.
• Initialization - The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
• To create a simple java program, you need to create a class that contains main
method.
Ex1:
class Simple {
public static void main(String args[]) {
[Link]("Hello Java");
}
}
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 5
Object Oriented Programming Using Java MMC202
\
Example:
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in litres
int mpg; // fuel consumption in miles per litres
}
• A class definition creates a new data type. In this case, the new data type is called
Vehicle.
• You will use this name to declare objects of type Vehicle.
• To create a Vehicle object, you will use a statement such as the following:
• Vehicle minivan= new Vehicle();
• After this statement executes, minivan will be an instance of Vehicle.
• The dot operator(.) links the name of an object with the name of a member.
• The general form of the dot operator is
[Link]
Ex:
[Link]=16;
• In general the dot(.)operator is used to access both instance variables and
methods.
class Vehicle {
int passengers; int fuelCap; int mpg;
}
class VehicleDemo {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
int range;
[Link] = 7;
[Link] = 16;
[Link] = 21;
range = [Link] * [Link];
[Link]("Minivan can carry " + [Link] + " with
a range of " + range);
}
}
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 6
Object Oriented Programming Using Java MMC202
\
Java Comments
The java comments are statements that are not executed by the compiler and
interpreter.
Example:
class CommentExample1 {
public static void main(String[] args) {
int i=10; //Here, i is a variable
[Link](i);
}
}
Example:
class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 7
Object Oriented Programming Using Java MMC202
\
Type Meaning
boolean Represents true/false values
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 8
Object Oriented Programming Using Java MMC202
\
JAVA KEYWORDS
• In the Java programming language, a keyword is any one of 55 reserved words
that have a predefined meaning in the language; because of this, programmers
cannot use keywords as names for variables, methods, classes, or as any other
identifier.
Although const and goto are reserved words, they are not currently part of the
Java language.
Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 9
Object Oriented Programming Using Java MMC202
\
Java Variables
• A variable is a container which holds the value while the java program is executed.
• A variable is assigned with a datatype.
• There are three types of variables in java: local, instance and static.
Local Variable:
• A variable declared inside the body of the method is called local variable.
• You can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.
Instance Variable
• A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
Static variable
• A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of
the class.
class A {
int data=50;//instance variable
static int m=100;//static variable
void method() {
int n=90;//local variable }
}//end of class
class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya");
[Link]();
[Link]();
}
}
• Variables are declared using this form of statement.
type var-name;
• Here type is the date type of the variable and varname is its name.
• The type of the variable cannot be change during its lifetime.
Ex:
an int variable cannot turn into a char variable
Initializing a variable:
• follow the variable’s name with an equal sign and the value being assigned.
- The general form of initialization is shown here
type var=value;
Ex:
int count=10;
char ch =‘a’;
float f=1.2;
• When declaring two or more variables of the same type using a comma-separated
list.
Ex: int a,b=10,c,d=15;
Operators
• Operators in Java are the symbols used for performing specific operations in
Java. Operators make tasks like addition, multiplication, etc which look easy
although the implementation of these tasks is quite complex.
1. Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
• The operands of the arithmetic operators must be of a numeric type.
• You cannot use them on boolean types, but you can use them on char
types, since the char type in Java is a subset of int.
• The following table lists the arithmetic operators:
Operator Result
+ Addition
- Substraction(Also unary minus)
* Multiplication
/ Division
% Modulus
EX:2
x = 42;
y = ++x;
• In this case, y is set to 43 as you would expect, because the increment
occurs before x is assigned to y. Thus, the line y = ++x; is the equivalent
of these two statements:
x = x + 1; y = x;
• However, when written like this,
x = 42;
y = x++;
• the value of x is obtained before the increment operator is executed, so
the value of y is 42.
• Of course, in both cases x is set to 43. Here, the line y = x++; is the
equivalent of these two statements:
y = x;
x = x + 1;
Example:
00101010 42
& 00001111 15
----------------------------------
00001010 10
4. Shift Operators
5. Relational Operators:
• The relational operators determine the relationship that one operand has to the
other.
• Specifically, they determine equality and ordering. The relational operators are
shown here:
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Lessthan
>= Greaterthan or equal to
<= Lessthan or equal to
6. Logical Operators:
• The Boolean logical operators shown here operate only on boolean
operands.
Operator Result
& Logical AND
| Logical OR
! Logical NOT
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
• The logical Boolean operators, &, |, and ^, operate on boolean values in
the same way that they operate on the bits of an integer.
• The logical ! operator inverts the Boolean state:
o !true == false and !false == true.
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a; int a=10; int b=5;
int c=20;
[Link](a<b&&a<c);
[Link](a<b&a<c);
EX:
class OperatorExample {
public static void main(String args[])
{
int a=10; int b=5;
int c=20; [Link](a<b&&a++<c); [Link](a);
[Link](a<b&a++<c); [Link](a);
}
}
• The logical || operator doesn't check second condition if first condition is true.
• It checks second condition only if first one is false.
• The bitwise | operator always checks both conditions whether first condition is
true or false.
EX:
class OperatorExample {
public static void main(String args[]) {
int a=10, b=5, c=20;
[Link](a>b||a<c);
[Link](a>b|a<c);
[Link](a>b||a++<c);
[Link](a);
[Link](a>b|a++<c);
[Link](a);
}
}
Expressions
•An expression is a syntactic construction that has a value.
•Expressions are formed by combining variables, constants, and method
returned values using operators.
The Type Promotion Rules:
• With in expression, it is possible to mix two or more different types of data
as long as they are compatible with each other.
• you can mix short and long within an expression because they are both
numeric types.
• When different types of data are mixed an expression, they are all
converted to the same type.
• All char, byte and short values are promoted to int.
• If one operand is a long, the whole expression is promoted to long.
• If one operand is a float operand, the entire is promoted to float.
• If one operand is double, the result is double
Ex:
class rnsit {
public static void main(String[] args)
{
byte b; int i; b=10;
char ch1=‘a’,ch2=‘b’; ch1=(char)(ch1 + ch2);
i=b * b; // no cast needed [Link](“ i and b:” +i+ “ “
+b);
[Link](ch1);
}
}
• No cast is needed when b*b=i, because b is promoted to int when the
expression is evaluated.
• The same sort of situation also occurs when performing operations on
char.
• Without the cast, the resulting of adding ch1 and ch2 would be int, which
can’t be assigned to a char.
EX:
public class Test {
public static void main(String[] args) {
int i = 100; //occupies 4 bytes
long l = i; // occupies 8 bytes
double f = l; // occupies 8 bytes
[Link]("Int value "+i); [Link]("Long value "+l);
[Link]("Float value "+f);
}
}
OUTPUT
Int value 100
Long value 100 Float value 100.0
Explicit conversions:
• If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
• The general form of cast is (target-type)expression
• Here, target-type specifies the desired type to convert the specified value to.
• The thumb rule is, on both sides, the same data type should exist.
• EX:
class Test
{
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; int i = (int)l;
[Link]("Double value "+d); //100.04
[Link]("Long value "+l); // 100
[Link]("Int value "+i); // 100
}
}
Control Statements
• There are three types of control statements:
o Selection statements
o Iteration statements
o Jump statements
• Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
• Iteration statements enable program execution to repeat one or more statements.
• Jump statements allow your program to execute in a nonlinear fashion.
Selection statements:
Java if Statement:
• The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}
EX:
public class IfExample {
public static void main(String[] args) {
int age=20; if(age>18)
{
[Link]("Age is greater than 18");
}
}
}
Ex:
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a){
[Link](“BANGALORE");
}
elseif(a>b){
[Link](“DELHI");
} else {
[Link](“HYDERABAD");
}
}
}
Nested if statement:
public class Test {
public static void main(String args[]) {
int x = 30; int y = 10;
if( x == 30 )
{
if( y == 10 )
{
[Link](“BANGALORE"); }
}
}
}
Switch Statement
• The switch statement is Java’s multiway branch statement.
• It provides an easy way to dispatch execution to different parts of your code based
on the value of an expression.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant.
Here is the general form of a switch statement:
switch (expression)
{
case value1:
// statement sequence break;
case value2:
// statement sequence break;
..
case valueN:
// statement sequence
break; default:
// default statement sequence
}
EX:
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<5; i++) switch(i)
{
case 0:
[Link](“JAVA"); break;
case 1:
[Link](“DBMS"); break;
case 2:
[Link](“WEB");
break; case 3:
[Link](“UID"); break;
default:
[Link](“SOFWARE");
}
}
}
EX2:
• The break statement is optional.
• If you omit the break, execution will continue on into the next case.
• It is sometimes desirable to have multiple cases without break statements between
them.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++) switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4: [Link](“MOBILE"); break;
case 5:
case 6:
case 7:
case 8:
case 9:
[Link](“APPLICATIONS"); break;
default:
[Link](“ENGINEERING"); }
}
}
EX3:
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
Iteration statements:
• Java’s iteration statements are for, while, and do-while.
• These statements create what we commonly call loops.
while
• The while loop is Java’s most fundamental loop statement.
• It repeats a statement or block while its controlling expression is true.
• Here is its general form:
while(condition)
{
// body of loop
}
• The condition can be any Boolean expression.
• The body of the loop will be executed as long as the conditional expression is true.
• When condition becomes false, control passes to the
• next line of code immediately following the loop.
• The curly braces are unnecessary if only a single statement is being repeated.
EX:
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0)
{
[Link]("tick " + n); n--;
}
}
}
• The body of the while (or any other of Java’s loops) can be empty.
• This is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.
EX2 :
class NoBody {
public static void main(String args[]) {
int i, j; i = 100; j = 200;
while(++i < --j) ; // no body in this loop
[Link]("Midpoint is " + i);
}
}
OUTPUT
It generates the following output:
Midpoint is 150
do-while:
• The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop.
• Its general form is
do
{
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression.
• If this expression is true, the loop will repeat. Otherwise, the loop terminates
EX:
class DoWhileExample {
public static void main(String[] args) {
int i=11;
do
{
[Link](i);
i++;
}while(i<=10);
}
}
• Once the condition becomes false, the loop will exit and program execution will
resume on the statement following of for.
• A for loop is most commonly used when you know that a loop will execute a
predetermined number of times.
• The general form of the for loop for repeating a single statement is
• Missing pieces:
• Some interesting for loop variations are created by leaving pieces of the loop
definition empty .
• In java, it is possible for any or all of the initialization, condition or iteration portions
of the for loop to be blank.
EX:
int i; for(i=0,i<10;)
{
[Link](“value of i:“ + i ); i++;
}
Ex2:
class Big {
public static void main (String [] arg) {
int [] myArr = { 45, 5, 34, 8 } ;
int big = myArr[0];
for( int num : myArr)
if ( big<num )
big = num;
[Link](“Bigest = ” + big) ;
}
}
EX:
class ForEachExample {
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{
[Link](i);
}
}
}
Jump Statements:
• Java supports three jump statements: break, continue, and return.
• These statements transfer control to another part of your program. Break:
• In Java, the break statement has three uses.
• First, as you have seen, it terminates a statement sequence in a switch statement.
• Second, it can be used to exit a loop.
• Third, it can be used as a “civilized” form of goto.
--------------------------------------------------
class BreakLoop4 {
public static void main(String args[]) {
outer:
for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": "); for(int j=0; j<100; j++)
{
if(j == 4) break outer; [Link](j + " ");
}
[Link]("This will not print");
}
[Link]("Loops complete.");
}
}
------------------------------------------------
• Keep in mind that you cannot break to any label which is not defined for an
enclosing block.
class BreakErr {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": "); }
for(int j=0; j<100; j++) {
if(j == 10)
break one; // WRONG
[Link](j + " ");
}
}
}
Using continue
• The continue statement is used in loop control structure when you need to jump
to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
• The Java continue statement is used to continue the loop.
• It continues the current flow of the program and skips the remaining code at the
specified condition.
EX1:
class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++) {
if(i==5) {
continue;
}
[Link](i);
}
}
}
EX2:
class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
[Link]( x );
[Link]("\n");
}
}
}
• As with the break statement, continue may specify a label to describe which
enclosing loop to continue.
EX3:
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
if(j > i) {
[Link](); continue outer;
}
[Link](" " + (i * j));
}
}
[Link]();
}
}
• The continue statement in this example terminates the loop counting j and
continues with the next iteration of the loop counting i.
Return:
• The last control statement is return.
• The return statement is used to explicitly return from a method.
• That is, it causes program control to transfer back to the caller of the
method.
• At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method.
• Thus, the return statement immediately terminates the method in
which it is executed.
EX:
public class SampleReturn1 {
public int CompareNum() {
int x = 3; int y = 8;
[Link]("x = " + x + "\ny = " + y);
if(x>y)
return x;
else
return y;
}
public static void main(String ar[]) {
SampleReturn1 ob = new SampleReturn1();
int result = [Link]();
[Link]("The greater number am ong x and y is: " + result);
}
}
Java Identifiers:
• All Java components require names. Names used for classes, variables and
methods are called identifiers.
• In Java, there are several points to remember about identifiers. They are as follows:
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
• After the first character identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, 1_value
Ex:
public class Test {
public static void main(String[] args) {
int a = 20;
}
}
• In the above java code, we have 5 identifiers namely :
Test : class name.
main : method name.
String : predefined class name.
args : variable name.
a : variable name.
Literals
• In java, literals refer to fixed values that are represented in their human-readable
form.
• Literals are also commonly called constants.
• Java literals can be any of the primitive data types.
• The way each literal is represented depends on its type.
• Character constants are enclosed in single quotes.
Ex:
• char g=‘a’
• char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
• In java, single and double quotes have special meaning is there. So you cannot
use them directly.
• You have to refer backslash(\) character constants.
Ex:
char ch=‘\’’;
• Java supports other type of literal: the string
• The string literal is a set of characters enclosed by double quotes.
Ex:
String s=“mca rnsit”;
String a= "he said \"Hello\" to me."
}
}
class Rectangle {
double length;
double breadth;
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
Rectangle r3 = r2;
[Link] = 20;
[Link] = 25;
[Link]("Value of R1's Length : " + [Link]);
[Link]("Value of R2's Length : " + [Link]);
[Link]("Value of R2's Length : " + [Link]);
}
}
Methods
• A method contains the statements that define its actions.
• In well-written java code, each method performs only one task.
• You can give a method whatever name you please as long as it is a valid identifier.
• Remember that main() is reserved for the method that begins execution of your
program.
• A method will have parentheses after its name.
• For example, if a method’s name is getval,it will written getval() when its name is
used in a sentence
• The general form of a method is,
return-type name(parameter-list) {
//body of method }
• Here, ret-type specifies the type of data returned by the method.
• This can be any valid type, including class types that you can create.
• If the method does not return a value, its return type must be void.
Returning a value
• Returns values are used for a variety of purposes in programming.
• In some cases, such as sqrt(), the return value contains the outcome of some
calculation.
• In other cases, the return value simply indicate success or failure.
• In still others, it may contain a status code.
• Methods return a value to the calling routine using this form of return:
return value:
class Vehicle {
int passengers;
int fuelCap; int mpg;
int range() {
return mpg * fuelCap;
}
}
class RetMeth {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
[Link] = 7;
[Link] = 16;
[Link] = 21;
[Link] = 2;
[Link] = 14;
[Link] = 12;
range1 = [Link]();
range2 = [Link]();
[Link]("Minivan can carry " + [Link] + " with
range of " + range1 + " miles");
[Link]("Sportscar can carry " + [Link] + "
with range of " + range2 + " miles");
}
}
Constructors
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar
to a method.
• Once defined, the constructor is automatically called immediately after the object
is created, before the new operator completes.
• Constructors look a little strange because they have no return type, not even void.
• This is because the implicit return type of a class constructor is the class type itself.
• It constructs the values i.e. provides data for the object that is why it is known as
constructor.
• Typically ,you will use a constructor to give initial values to the instance variables
defined by the class.
Types of java constructors
• There are two types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
Java Default Constructor
• A constructor that have no parameter is known as
Default constructor
class Bike1 {
Bike1() {
[Link]("Bike is created");
}
public static void main(String args[]) {
Bike1 b=new Bike1();
}
}
Default constructor provides the default values to the object like 0, null etc.
depending on the type.
Ex:
class Student3 { int
id; String name;
void display() {
[Link](id+" "+name); }
public static void main(String args[]) {
Student3 s1=new Student3();
Student3 s2=new Student3();
[Link]();
[Link]();
}
}
Ex1:
class Student4 {
int id; String name;
Student4(int i,String n) {
id = i; name = n;
}
void display() {
[Link](id+" "+name);
}
public static void main(String args[]) {
Student4 s1 = new Student4(111,"Kiran");
Student4 s2 = new Student4(222,"Arya");
[Link]();
[Link]();
}
}
EX2:
class Box {
double width; double height; double depth;
Box(double w, double h, double d) {
width = w; height = h;
depth = d;
}
double volume() {
return width * height * depth; }
}
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}
Ex:1
class Student10{
int id; String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){
[Link](id+" "+name);
}
public static void main(String args[]){
Student10 s1 = new Student10(111,“kiran");
Student10 s2 = new Student10(321,"Ajay");
[Link]();
[Link]();
}
}
• In the above example, parameters(formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable
and instance variable.
Ex 1:
class Student11
{
int id; String name;
Student11(int id,String name) {
[Link] = id; [Link] = name;
}
void display() {
[Link](id+" "+name);
}
public static void main(String args[]) {
Student11 s1 = new Student11(111,"Kiran");
Student11 s2 = new Student11(222,"Ajay");
[Link]();
[Link]();
}
}
Ex2:
class A {
void m() {
[Link]("hello m");
}
void n() {
[Link]("hello n"); this.m();
}
}
class TestThis4 {
public static void main(String args[]){
A a=new A();
a.n();
}
}
Arrays:
• array is a collection of similar type of elements that have contiguous memory
location.
• Java array is an object that contains elements of similar data type.
• It is a data structure where we store similar elements. We can store only fixed set
of elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index.
A One Dimensional Array is a list of related variables. Such lists are common in
programming .
• To declare a one-dimensional array, you will use this general form:
type[] array-name=new type[size];
• Here, type declares the element type of the array.(The element type is also
sometimes referred to as the base type).
• The element type determines the data type of each element contained in the array.
• The number of elements that the array will hold is determined by size.
• Since arrays are implemented as objects,
• The creation of array is two-step process.
• First, you declare an array reference variable.
• Second, you allocate memory for the array, assigning the reference to that memory
to the array variable.
• Thus, arrays are dynamically allocated using the new operator.
Ex:
int[] sample=new int[10];
• This declaration works like an object declaration.
• The sample variable hold a reference to the memory allocated by new.
• This memory is large enough to hold 10 elements of type int.
• It is possible to break the preceding declaration in two.
int[] sample;
sample=new int[10];
Ex:
class ArrayDemo {
public static void main(String[] args) {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
[Link]("This is sample[" + i + "]: " + sample[i]);
}
}
}
• Ex2:
class MinMax {
public static void main(String[] args) {
int[] nums = new int[5];
int min, max;
nums[0] = 99;nums[1] = 200;nums[2] = 100; nums[3] = 18;nums[4] = -978;
min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) { if(nums[i] < min) min = nums[i]; if(nums[i] > max) max =
nums[i];
}
[Link]("min and max: " + min + " " + max); }
}
Contd….
• Arrays can be initialized when they are created.
• The general form for initializing a one-dimensional
array is,
type[] array-name={val1,val2,val3…..valN}
• Here, the initial value are specified by val1 through
valN.
• They are assigned in sequence, left to right, in index
order.
• Java automatically allocates an array large enough to
hold the initializers that you specify.
• There is no need to explicitly use the new operator.
• Ex:
class MinMax2 {
public static void main(String[] args) {
int[] nums = { 99,5623, 463, 287, 49 };
int min, max; min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) {
if(nums[i] < min) min = nums[i]; if(nums[i] > max) max = nums[i];
}
[Link]("Min and max: " + min + " " + max); }
}
Multidimensional arrays
• In java, multidimensional array or two dimensional
array is a array of arrays.
• A two-dimensional array can be thought of as
creating a table of data, with the data organized by
row and column.
• An individual item of data is accessed by specifying
its row and column position.
• To declare a two-dimensional array, you must specify
the size of both dimensions.
• int [][] table=new int[10][20];
Here table is declared to be a two-dimensional array of int with the size 10 and
20.
Ex:
class TwoD {
public static void main(String[] args) { int t, i;
int[][] table = new int[3][4]; for(t=0; t < 3; t++) {
for(i=0; i < 4; i++) {
table[t][i] = (t*4)+i+1; [Link](table[t][i] + " ");
} [Link]();
class Testarray3 {
public static void main(String args[]) {
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++) {
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
----------------------------
class Test5 {
public static void main(String args[]) {
int[][] a={{1,3,4},{3,4,5}};
int[][] b={{1,3,4},{3,4,5}}
int c[][]=new int[2][3];
for(int i=0;i<2;i++) {
for(int j=0;j<3;j++) {
c[i][j]=a[i][j]+b[i][j]; [Link](c[i][j]+" ");
}
[Link]();//new line
}
}
}
Ex:
class LengthDemo {
public static void main(String[] args) {
int[] list = new int[10];
int[] nums = { 1, 2, 3 };
int[][] table = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
[Link]("length of list is " + [Link]);
[Link]("length of nums is " + [Link]);
[Link]("length of table is " + [Link]);
[Link]("length of table[0] is " + table[0].length);
[Link]("length of table[1] is " + table[1].length);
[Link]("length of table[2] is " + table[2].length);
[Link]();
}
}
Overloading Methods
• If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
• There are two ways to overload the method in java By changing number of
arguments By changing the data type
EX:1
class OverloadDemo {
void test()
{
[Link]("No parameters");
}
void test(int a)
{
[Link]("a: " + a);
}
void test(int a, int b)
{
[Link]("a and b: " + a + " " + b);
}
void test(double a)
{
[Link]("double a: " + a*a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
[Link]();
[Link](10);
[Link](10, 20);
[Link](123.25);
}
}
• In some cases, Java’s automatic type conversions can play a role in overload
resolution.
EX:2
class OverloadDemo {
void test()
{
[Link]("No parameters");
}
void test(int a, int b)
{
[Link]("a and b: " + a + " " + b);
}
void test(double a)
{
[Link]("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
[Link]();
[Link](10, 20);
[Link](i);
[Link](123.2);
}
}
EX:3
class mca10 {
int arun(int a)
{
return a;
}
double arun(double a, double b)
{
return a*b;
}
}
class mca85 {
public static void main(String args[]) {
mca10 s=new mca10();
[Link]([Link](10));
[Link]([Link](20.6, 12.5));
}
}
Overloading Constructors
• In addition to overloading normal methods, you can also overload constructor
methods.
EX:
class Box {
double width; double height; double depth;
Box(double w, double h, double d)
{
width = w; height = h;
depth = d; }
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len; }
double volume()
{
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}
Recursion
• Java supports recursion. Recursion is the process of defining something in terms of
itself.
• As it relates to Java programming, recursion is the attribute that allows a method
to call itself.
• A method that calls itself is said to be recursive.
Ex 1:
class Factorial {
int fact(int n) {
I nt result; if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}
Ex 2:
class StarDrawer {
void drawStars(int n) {
if(n == 1)
[Link]("*");
else {
[Link]("*");
drawStars(n-1);
}
}
}
class StarDrawingDemo {
public static void main(String[] args) {
StarDrawer d = new StarDrawer();
[Link](1);
[Link]();
[Link](2);
[Link]();
[Link](3);
[Link]();
[Link](10);
[Link]();
}
}
Understanding static
• Normally, a class member must be accessed only in conjunction with an object of
its class.
• However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
• To create such a member, precede its declaration with the keyword static.
• We can apply java static keyword with variables, methods, blocks.
• The static can be: variable (also known as class variable) method (also known as
class method) block
• Methods declared as static have several restrictions:
Ex 1:
Static variables
class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya"); //[Link]="BBDIT";
[Link](); [Link]();
}
}
Static Methods
• If you apply static keyword with any method,it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
Ex:2 //[Link]
class Student9 {
int rollno; String name;
static String college = “BMSIT";
static void change()
{
college = “RNSIT";
}
Student9(int r, String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[])
{
[Link]();
Student9 s1 = new Student9 (111,"Kiran");
Student9 s2 = new Student9 (222,“Ravi");
Student9 s3 = new Student9 (333,“Ajay");
[Link]();
[Link]();
[Link]();
}
}
Ex 2:
class UseStatic {
static int a = 3; static int b;
static void meth(int x)
{
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically.
• In other words, it is a way to destroy the unused objects.
• To do so, we were using free() function in C language and delete() in C++.
• But, in java it is performed automatically.
• So, java provides better memory management.
• when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed.
finalize() method
• The finalize() method is invoked each time before the object is garbage collected.
• This method is called finalize(),and it can be used in very specialized case to ensure
that an object terminates cleanly.
• To add a finalizer to class, you must define the finalize() method.
• The general form:
protected void finalize()
{
//code
}
• It is important to understand that finalize( ) is only called just prior to garbage
collection.
MODULE-2
MULTIPLE INHERITANCE
Inheritance
• Java, Inheritance is an important pillar of OOP(Object-Oriented
Programming).
• It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
• In Java, Inheritance means creating new classes based on existing ones.
• A class that inherits from another class can reuse the methods and fields of
that class.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
•
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses.
• Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.
extends
Single Inheritance
• When a class inherits another class, it is known as a single inheritance.
Example:
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}
class Single
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
Multilevel Inheritance
• When there is a chain of inheritance, it is known as multilevel inheritance.
Example
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}
class Cat extends Dog
{
void ball()
{
[Link]("BCA");
}
}
class multilevel
{
public static void main(String args[])
{
Cat d=new Cat();
[Link]();
[Link]();
[Link]();
}
}
Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as
hierarchical inheritance.
Example
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}
}
}
having default access modifier are accessible only within the same package.
final method
• If you make any method as final, you cannot override it.
final class
• If you make any class as final, you cannot extend it.
[Link]();
}
}
//compile time error
toString() method
• If you want to represent any object as a string, toString() method comes into
existence.
• The toString() method returns the String representation of the object.
• If you print any object, Java compiler internally invokes the toString()
method on the object. So overriding the toString() method, returns the
desired output, it can be the state of an object etc. depending on your
implementation.
•
Example
class Student12
{
int rollno;
String name;
String city;
Student12(int rollno, String name, String city)
{
[Link]=rollno;
[Link]=name;
[Link]=city;
}
public String toString()
{
return rollno+" "+name+" "+city;
}
hashCode() Method
• The hashCode() method is a Java Integer class method which returns the
hash code for the given inputs.
It returns true if this object is same as the obj argument else it returns false
otherwise.
class kiran
{
int a=25;
}
class bangaluru
{
public static void main(String[] args)
{
kiran s1 = new kiran();
kiran s2 = new kiran();
[Link]([Link](s2)); //false
kiran s3=s1;
[Link]([Link](s3)); //true
}
}
getClass() Method
• getClass() is the method of Object class. This method returns the runtime
class of this object.
public class Objectget
{
public static void main(String[] args)
{
Object obj = new String("23");
Class a = [Link]();
[Link]("Class of Object obj is : " + [Link]());
}
}
Output: Class of Object obj is : [Link]
Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single action
in different ways.
• Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means
many forms.
• There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
• If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
• Runtime polymorphism or Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at runtime rather than compile-
time.
• In this process, an overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on the object being
referred to by the reference variable.
Upcasting
• If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting.
Example
class Bike
{
void run()
{
[Link]("running");
}
}
class Splendor extends Bike
{
void run()
{
[Link](“RNSIT");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
[Link]();
}
}
Method overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
Usage of Java Method Overriding
• Method overriding is used to provide specific implementation of a method
that is already provided by its super class.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• method must have same name as in the parent class
• method must have same parameter as in the parent class.
EX:
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
[Link]("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
[Link]();
}
}
EX:2
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
[Link]("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B sub = new B(1, 2, 3);
[Link]();
}
}
EX:3
class Animal
{
void move()
{
[Link]("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
[Link]();
[Link]("Dogs can walk and run");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Dog class
}
}
Abstract classes
• A class that is declared with abstract keyword, is known as abstract class in
java. It can have abstract and non-abstract methods (method with body).
• Before learning java abstract class, let's understand the abstraction in java
first.
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• Another way, it shows only important things to the user and hides the
internal details.
• A method that is declared as abstract and does not have implementation is
known as abstract method.
Ex:1
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Ex: 2
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
[Link]("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
[Link]("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
[Link]();
}
}
2. concat(String s)
• This method returns a String with the value of the String passed in to the
method appended to the end of the String used to invoke the method.
Example
String x = "book";
[Link]( [Link]("author") );
// output is "bookauthor"
The overloaded + and += operators perform functions similar to the
concat()method
Example,
String x = "library";
[Link]( x + " card");
// output is "library card"
String x = "United";
x += " States”
[Link]( x );
// output is "United States"
3. equalsIgnoreCase(String s)
• This method returns a boolean value (true or false) depending on whether
the value of the String in the argument is the same as the value of the String
used to invoke the method.
Example
String x = "Exit"; [Link]([Link]("EXIT")); // is "true"
[Link]([Link]("tixe")); // is "false"
4. length()
• This method returns the length of the String used to invoke the method.
Example,
String x = "01234567";
[Link]( [Link]() ); // returns "8“
Output
RnSnT
6. toLowerCase()
• This method returns a String whose value is the String used to invoke the
method, but with any uppercase characters converted to lowercase.
Example,
String x = "A New Java Book";
[Link]( [Link]() );
// output is "a new java book"
7. toUpperCase()
• This method returns a String whose value is the String used to invoke the
method, but with any lowercase characters converted touppercase.
Example,
String x = "A New Java Book"; [Link]( [Link]());
// output is"A NEW JAVA BOOK"
8. trim() method
• The String class trim() method eliminates white spaces before and after the
String.
Example
class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
[Link]([Link]());//Sachin
}
}
9. char[ ] toCharArray( )
• This method will produce an array of characters from characters of String
object.
Example
String s = “Java”;
Char [] mca = [Link]();
Parameter Passing
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• Pass by Value: In the pass by value concept, the method is called by passing
a value.
• So, it is called pass by value. It does not affect the original parameter.
• Pass by Reference: In the pass by reference concept, the method is called
using an alias or reference of the actual parameter.
• So, it is called pass by reference. It forwards the unique identifier of the
object to the method.
• If we made changes to the parameter's instance member, it would affect the
original value.
Example1:
class Test
{
void display(int i, int j)
{
i *= 2;
j += 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
Example2:
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
void Display(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 10);
[Link]("ob.a and ob.b before call: " + ob.a+ " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
Output
ob.a and ob.b before call: 15 10
ob.a and ob.b after call: 30 5
ENUMERATION:
• Enumeration is a list of named constants that define a new data type.
• An object of an enumeration type can hold only the values that are defined
by the list.
• Thus , an enumeration gives you a way to precisely define a new type of data
that has a fixed number of valid values.
• An enumeration is created using the enum keyword.
Ex:
enum Transport
{
CAR, TRUNK, TRAIN, BUS
}
• The identifiers CAR, TRUNK and so on are called enumeration constants or
enum constants.
• Each is implicitly declared as a public, static member of Transport.
• Once you have declared an enumeration, you can create a variable of that
type.
• Even though enumerations define a class type, you do not instantiate an
enum using new.
Ex:
Transport tp;
• Because tp is of type of Transport, the only values that it can be assigned
are those constants defined by the enumeration or null.
Ex:
tp= [Link];
• Here BUS is assiged to tp.
• Two enumeration constant can be compared for equality by using the ==
relational operator.
Ex:
if(tp==[Link])
• Here this statement compares the value in tp with the CAR.
• An enumeration value can also be used to control a switch statement.
Example
enum NAMES
{
RAGHU, PRASAD, DEVA, SHIVA,KIRAN
}
class EnumExample3
{
public static void main(String[] args)
{
NAMES s=[Link];
[Link](s);
}
}
D:\raghu java practice>javac [Link]
[Link]: cannot find symbol
symbol : variable RAJ
location: class NAMES
NAMES s=[Link];
^
1 error
class hello{
public enum Season
{
WINTER, SPRING, SUMMER, FALL
}
public static void main(String[] args)
{
for (Season s : [Link]())
[Link](s);
}
}
class EnumExample1{
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
public static void main(String[] args)
{
for (Season s : [Link]())
[Link](s);
Season a = [Link]("SUMMER");
[Link]("the value of a is");
[Link](a);
}
}
OUTPUT WINTER
SPRING
SUMMER
FALL
the value of a is
SUMMER
MODULE 3
Interfaces
Interface fundamentals
• In java, an interface defines a set of methods that will be implemented
by class.
• Interfaces are similar to abstract classes, except that no method can
include a body.
• This means an interface provides no implementation whatsoever of the
methods it defines.
• Once an interface is defined, any number of classes can implement it.
• One class can implement any number of class.
• An interface is defined by use of the interface keyword.
• General form of interface is access
interface name{
ret-type method-name1(param-list);
ret-type method-name2(param-list);
…… ……
ret-type method-nameN(param-list);
}
• Here, access is either public or not used. Implementing an interface
• Once an interface has been defined, one or more classes can implement
the interface.
• To implement an interface, follow these two steps.
1. In a class declaration, include an implements clause that specifies
the interface being implemented.
2. Inside the class, implement the methods defined by the interface.
General form of implements is
class classname implements interface {
//class body
}
Creating an interface
interface printable
{
void print();
}
class A6 implements printable {
public void print() {
[Link]("Hello");
}
public static void main(String args[])
{
A6 obj = new A6(); [Link]();
}
}
Example2
interface Drawable {
void draw();
}
class Rectangle implements Drawable {
public void draw() {
[Link]("drawing rectangle");
}
}
class Circle implements Drawable {
public void draw() {
[Link]("drawing circle");
}
}
class TestInterface1 {
public static void main(String args[]) {
Drawable d=new Circle(); [Link]();
}
}
Example3
interface Bank {
int rateOfInterest();
}
class SBI implements Bank {
public int rateOfInterest() {
return 8;
}
}
class PNB implements Bank {
public int rateOfInterest() {
return 9;
}
}
class TestInterface2 {
public static void main(String[] args) {
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
Implementing Multiple Interfaces
If a class implements multiple interfaces, or an interface extends multiple
interfaces i.e. known as multiple inheritance.
Ex:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print() {
[Link]("Hello"); }
public void show() {
[Link]("Welcome");
}
public static void main(String args[]) {
A7 obj = new A7();
[Link]();
[Link]();
}
}
class IFExtend {
public static void main(String[] args) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Constants in Interfaces
• The primary purpose of an interface is to declare methods that provide a
well-defined interface to functionality.
• An interface can also include variables.
• They are implicitly public, static, final and must be initialized.
• In other words, Interface fields are public, static and final by default, and
methods are public and abstract.
• Ex:
interface Const {
int min= 0;
int max = 10;
String error = "Boundary Error";
}
class ConstDemo implements Const {
public static void main(String[] args) {
int[] nums = new int[max];
Nested Interfaces
• An interface can be declared a member of another interface or of a class.
Such an interface is called member interface or a nested interface.
Ex:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable, [Link] {
public void msg() {
[Link]("Hello nested interface");
}
public void show() {
[Link]("rnsit");
}
public static void main(String args[]) {
TestNestedInterface1 a=new TestNestedInterface1();
[Link]();
[Link]();
}
}
Ex:
interface A
{
void a();
void b();
void c();
void d();
}
abstract class B implements A
{
public void c() {
[Link]("I am C");
}
}
class M extends B
{
public void a() {
[Link]("I am a");
}
Packages
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form, builtin package and user
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
• All classes in Java belong to some package. When no package has been
explicitly specified, the default (or global) package is used.
• To create a package, you will use the package statement.
• General form of the package statement is package pkg;
• Here pkg is the name of the package.
• More than one file can include the same package statement.
• You can create hierarchy of packages.
• The general form is package pack1.pack2.pack3…..packN;
• Ex: package [Link];
• must be stored in /alpha/beta/gamma specifies the path to be specified
directories.
• Ex:
package mypack;
public class Simple {
public static void main(String args[]) {
[Link]("Welcome to package");
}
}
If you want to keep the package within the same directory, you can use .
(dot).
• To compile:
javac -d directory javafilename
• To Run:
java [Link]
• For above program to complile:
javac –d . [Link]
to run: java [Link]
Access Protection
• Packages act as containers for classes and other subordinate packages.
• Classes act as containers for data and code.
• The class is Java’s smallest unit of abstraction.
• Because of the interplay between classes and packages, Java addresses
four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses.
• The three access specifiers, private, public, and protected, provide a
variety of ways to produce the many levels of access required by these
categories.
*having default access modifier are accessible only within the same
package.
Example
//[Link]
package pack; class proC
{
void msg() {
[Link]("Hello Bangalore");
}
}
//[Link]
package mypack; import pack.*;
class proD {
public static void main(String args[]) {
proC obj = new proC();
[Link]();
}
}
output
[Link]: error: proC is not public in pack;
cannot be accessed from outside package
proC obj = new proC();
Importing packages
• Using import, you can bring one or more members of a package into
view.
• The general form of import statement. import [Link];
• Here pkg is the name of the package, which can include its full path,
and classname is the name of the class being imported.
• If you want to import the entire contents of a package, use an
asterisk(*) for the class name.
Ex:
import [Link];
import mypack.*;
• In the first case,the MyClass is imported from mypack.
• In the second,all of the classes in myback are imported.
EX:
import [Link];
import [Link].*;
• All of the standard Java classes included with Java are stored in a
package called java.
• The basic language functions are stored in a package inside of the java
package called [Link].
import [Link].*;
EX:
import [Link].*;
class MyDate extends Date {}
• The same example without the import statement looks like this: class
MyDate extends [Link] {}
package pack18;
// packagename.*
public class raghu18
{
public void msg() {
[Link]("Hello rnsit");
}
}
------------------------------------------------------
package mypack12;
import pack18.*;
class prasad12
{
public static void main(String args[]) {
raghu18 obj = new raghu18();
[Link]();
}
}
//save by [Link] Using [Link]
package pack;
public class A {
public void msg(){
[Link]("Hello");
}
}
--------------------------------------------------------------------------
//save by [Link] package mypack; import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
//save by [Link] package pack; Using fully qualified name
public class A {
public void msg(){
[Link]("Hello");
}
}
------------------------------------------------------------------
//save by [Link] package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Static import
• The static import feature of Java 5 facilitate the java programmer to
access any static member of a class directly.
• There is no need to qualify it by the class name.
• Static imports are used to save your time and typing.
• If you hate to type same thing again and again then you may find such
imports interesting.
•
Example 1: Without Static Imports
class Demo1 {
public static void main(String args[]) {
double var1= [Link](5.0); double var2= [Link](30);
[Link]("Square of 5 is:"+ var1);
[Link]("Tan of 30 is:"+ var2);
}
}
OUTPUT
Square of 5 is:2.236 Tan of 30 is:-6.4053
CLASSPATH
• CLASSPATH describes the location where all the required files are available
which are used in the application.
• Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate
the required files.
• If the CLASSPATH is not set, Java Compiler will not be able to find the
required files and hence will throw the following error.
Error: Could not find or load main class <class name>
Set the CLASSPATH in JAVA in Windows • Command Prompt:
set PATH=.;C:\ProgramFiles\Java\JDK1.6.20\bin
1. Select Start
2. Goto Control Pannel
8. Select OK
MODULE 4
EXCEPTION HANDLING
}
Ex:
Without using try-catch
public class testtry
{
public static void main(String args[]) {
int data=50/0;//may throw exception
[Link]("rest of the code...");
}
}
Output:
• Exception in thread main [Link]:/ by zero
Output:
• Exception in thread main [Link]:/ by zero rest of the code...
EX:
public class testtry2 {
public static void main(String args[]) {
int[] nums = new int[4];
try{
[Link](“RNSIT”);
nums[7]=80;
[Link](“MCA”);
}
catch(ArithmeticException e) {
[Link](e);
}
[Link]("rest of the code...");
}
}
The consequences of an uncaught exception
• If your program does not catch an exception, then it will be caught by the JVM.
• The trouble is that the JVM’s default exception handler terminates execution and
displays an error message followed by a list of the methods calls that lead to the
exception.
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30;
}
catch(Exception e){
[Link]("common task completed");
}
catch(ArithmeticException e){
[Link]("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("task 2 c ompleted");
}
[Link]("rest of the code...");
}
}
OUTPUT
Compile-time error
class ExcDemo5 {
public static void main(String[] args) {
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<[Link]; i++) {
try {
[Link](numer[i] + " / " + denom[i] + " is " +
numer[i]/denom[i]);
}catch (ArrayIndexOutOfBoundsException exc){
[Link]("No matching element found.");
}
catch (Exception e){
[Link]("Some exception occurred.");
}
}
}
}
Ex:
public class Excep6 {
public static void main(String args[]) {
try {
try {
int a[]=new int[5]; a[5]=30;
}
catch(Exception e) {
[Link]("task1 is completed");
}
try {
int a[]=new int[5];
a[4]=30/0;
}
catch(ArithmeticException e) {
[Link]("task2 is completed");
}
int b[]=new int[5];
b[5]=30;
}
catch(Exception e) {
[Link]("task3 is completed");
}
}
}
Throwing an exception
• The Java throw keyword is used to explicitly throw an exception.
• we can throw either checked or unchecked exception in java by throw keyword.
• The syntax of java throw keyword is given below throw exceptob;
• Here, exceptob must be an object of an exception class derived from Throwable.
• Only object of Throwable class or its sub classes can be thrown.
Creating Instance of Throwable class
• There are two possible ways to get an instance of class Throwable,
• Using a parameter in catch block.
• Creating instance with new operator.
new NullPointerException("test");
• This constructs an instance of NullPointerException with name test.
Ex:1
public class TestThrow1 {
static void validate(int age) {
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote"); }
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}
OUTPUT
Exception in thread main [Link]:not valid
Ex:2
class Test21{
static void avg() {
try {
throw new ArithmeticException("demo");
}
catch(Exception e) {
[Link](e);
}
}
public static void main(String args[]) {
avg();
[Link]("Exception caught");
}
}
throws
• In some cases, if a method generates an exception that it does not handle, it must declare
that exception in a throws clause.
• The general form of throws is
Ex:1
import [Link].*;
class rns {
void mca()throws IOException {
throw new IOException("device error");
}
}
public class Testthrows2 {
public static void main(String args[]) {
try{
rns m=new rns(); [Link]();
}
catch(Exception e) {
[Link](e);
[Link]("normal flow...");
}
}
}
EX:2
import [Link].*;
class rnsit{
void mca(int a) throws IOException,ArithmeticException{
if(a%2==0)
throw new IOException("device error");
else
throw new ArithmeticException("error");
}
}
class Testthrows {
public static void main(String args[]) {
try{
rnsit m=new rnsit(); [Link](2);
}
catch(Exception e){
[Link](e); }
[Link]("normal flow...");
}
}
OUTPUT
[Link]:device Error normal flow…
EX3:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne(); }
catch (IllegalAccessException e) {
[Link]("Caught " + e);
}
}
}
Output
inside throwOne
caught [Link]: demo
• The other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
•
Methods defined by throwable
Exception hierarchy
• The class at the top of the exception class hierarchy is the Throwable class, which is
a direct subclass of the Object class.
• Throwable has two direct subclasses –
1. Exception
2. Error
Throwable class:
• Throwable class which is derived from Object class, is a top of exception hierarchy
from which all exception classes are derived directly or indirectly.
• It is the root of all exception classes.
• It is present in [Link] package.
Error:
• Error class is the subclass of Throwable class and a superclass of all the runtime error
classes.
• It terminates the program if there is problem-related to a system or resources (JVM).
Exception:
• It is represented by an Exception class that represents errors caused by the program
and by
• external factors.
• Exception class is a subclass of Throwable class and a superclass of all the exception
classes.
• All the exception classes are derived directly or indirectly from the Exception class.
• They originate from within the application.
•
Exception Class Hierarchy in Java
Using finally
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block must be followed by try or catch block.
Syntax:
finally{
finally code
}
Ex:1
class TestFinallyBlock {
public static void main(String args[]) {
try{
I nt data=25/5; [Link](data);
}
catch(ArithmeticException e){[Link](e);} finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Ex:2
class TestFinallyBlock1 {
public static void main(String args[]) {
try {
int data=25/0; [Link](data);
}
catch(NullPointerException e) {
[Link](e);
}
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
• OUTPUT
(finally block is always executed)
Exception in thread main
[Link]:/ by zero
For each try block there can be zero or more catch blocks, but only one finally block.
Built-in exceptions
• Exceptions that are already available in Java libraries are referred to as built-in
exception.
• These exceptions are able to define the error situation so that we can understand the
reason of getting this error.
• It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
Checked Exception
• Checked exceptions are called compiletime exceptions because these exceptions are
checked at compile-time by the compiler.
• The compiler ensures whether the programmer handles the exception or not.
• The programmer should have to handle the exception; otherwise, the system has
shown a compilation error.
UnChecked Exception
• An unchecked exception is an exception that occurs at the time of execution.
• These are also called as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper use of an API.
• Runtime exceptions are ignored at the time of compilation.
}
public static void main(String args[] {
try {
compute(1); compute(20);
}
catch (MyException e) {
[Link]("Caught " + e);
}
}
}
Output
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
• If you want to represent any object as a string, toString() method comes into existence.
• The toString() method returns the string representation of the object.
Chained Exceptions
• Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
• For example, consider a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero but the actual cause of exception was an I/O
error which caused the divisor to be zero.
• The method will throw only ArithmeticException to the caller.
• So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
• Constructors Of Throwable class Which support chained exceptions in java :
• Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
• Throwable(String msg, Throwable cause) :- Where msg is the exception message
and cause is the exception that causes the current exception.
• Methods Of Throwable class Which support chained exceptions in java :
• getCause() method :- This method returns actualcause of an exception.
• initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
[Link](a);
[Link]([Link]());
}
}
}
Output
[Link]: Exception [Link]: This is actual
cause of the exception
Container
• The Container is one of the components in AWT that contains other components like
buttons, text fields, labels, etc.
• The classes that extend the Container class are known as containers such as Frame, Dialog,
and Panel as shown in the hierarchy.
Types of containers
• Container refers to the location where components can be added like text field, button,
checkbox, etc.
• There are four types of containers available in AWT, that is, Window, Frame, Dialog, and
Panel.
• As shown in the hierarchy above, Frame and Dialog are subclasses of the Window class.
1. Window: The window is a container that does not have borders and menu bars. In order to create
a window, you can use frame, dialog or another window.
2. Panel: The Panel is the container/class that doesn’t contain the title bar and menu bars. It has
other components like buttons, text fields, etc.
3. Dialog: The Dialog is the container or class having a border and title. We cannot create an
instance of the Dialog class without an associated instance of the respective Frame class.
4. Frame: The Frame is the container or class containing the title bar and might also have menu
bars. It can also have other components like text field, button, etc.
Introduction to Swing
• Swing is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
API Package The AWT Component classes are The Swing component classes are
provided by the [Link] package. provided by the [Link] package.
Operating System The Components used in AWT are The Components used in Swing are
mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.
Number of The Java AWT provides a smaller Java Swing provides a greater number
Components number of components in of components than AWT, such as
comparison to Swing. list, scroll panes, tables, color
choosers, etc.
Full-Form Java AWT stands for Abstract Java Swing is mainly referred to as
Window Toolkit. Java Foundation Classes (JFC).
Functionality and Java AWT many features that are Swing components provide the
Implementation completely developed by the higher-level inbuilt functions for the
developer. It serves as a thin layer developer that facilitates the coder to
of development on the top of the write less code.
OS.
Memory Java AWT needs a higher amount Java Swing needs less memory space
of memory for the execution. as compared to Java AWT.
Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.
Method Description
public void setLayout(LayoutManager sets the layout manager for the component.
m)
Container
• The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• It is basically a screen where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a container
inside container.
JFrame:
• The [Link] class is a type of container which inherits the [Link] class.
• JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
[Link](new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
[Link]("Button");
[Link](label);
[Link](button);
[Link](panel);
[Link](200, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output
JDialog
• The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Syntax:
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.
Output:
JPanel
• The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.
• It doesn't have title bar.
JPanel class declaration
public class JPanel extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.
JPanel Example
import [Link].*;
import [Link].*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JButton
• The JButton class is used to create a labeled button that has platform independent
implementation.
• The application result in some action when the button is pushed. It inherits AbstractButton
class.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
Button Example
import [Link].*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
JLabel
• The object of JLabel class is a component for placing text in a container.
• It is used to display a single line of read only text.
• The text can be changed by an application but a user cannot edit it directly.
• It inherits JComponent class.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.
JLabel Example
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}
}
Output:
JTextField
• The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
JTextField Example
import [Link].*;
class TextFieldExample {
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
JTextArea
• The object of a JTextArea class is a multi line region that displays text.
• It allows the editing of multiple line text. It inherits JTextComponent class
Constructor Description
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.
Methods Description
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
JTextArea Example
import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:
LayoutManagers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.
BorderLayout
• The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center.
• Each region (area) may contain one component only.
• It is the default layout of a frame or window.
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
GridLayout
• The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns along with given horizontal and vertical gaps.
import [Link].*;
public class GridLayoutExample
{
JFrame frameObj;
GridLayoutExample()
{
frameObj = new JFrame();
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
[Link](btn1); [Link](btn2); [Link](btn3);
[Link](btn4); [Link](btn5); [Link](btn6);
[Link](btn7); [Link](btn8); [Link](btn9);
// setting the grid layout using the parameterless constructor
[Link](new GridLayout());
[Link](300, 300);
[Link](true);
}
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
FlowLayout
• The Java FlowLayout class is used to arrange the components in a line, one after another (in
a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
FlowLayoutExample()
{
frameObj = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
[Link](b1); [Link](b2); [Link](b3); [Link](b4);
[Link](b5); [Link](b6); [Link](b7); [Link](b8);
[Link](b9); [Link](b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
[Link](new FlowLayout());
[Link](300, 300);
[Link](true);
}
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
Applet
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage/Features of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
• Applet is a small and easy-to-write Java program.
• One can easily install Java applet along with various HTML documents.
• One needs a web browser (Java based) to use applets.
• Applet do not have access to the network or local disk and can only access browser-specific
services.
• It cannot perform system operations on local machines.
• Applet cannot establish access to local system.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.
Meaning A Java Application also known as The Java applet works on the client side,
application program is a type of and runs on the browser and makes use of
program that independently executes another application program so that we
on the computer. can execute it.
Requirement of Its execution starts with the main( ) It does not require the use of any main()
main( ) method method only. The use of the main( ) is method. Java applet initializes through
mandatory. init( ) method.
Execution It cannot run independently, but It cannot start independently but requires
requires JRE to run. APIs for use (Example. APIs like Web
API).
Installation We need to install the Java application Java applet does not need to be pre-
first and obviously on the local installed.
computer.
Operation It performs read and write tasks on a It cannot run the applications on any local
variety of files located on a local computer.
computer.
File access It can easily access a file or data It cannot access the file or data found on
available on a computer system or any local system or computer.
device.
Security Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.
concerns.
There are five methods of an applet life cycle, and they are:
init():
• The init() method is the first method to run that initializes the applet. It can be invoked only
once at the time of initialization.
• The web browser creates the initialized objects, i.e., the web browser (after checking the
security settings) runs the init() method within the applet.
start():
• The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked.
• Every time the browser is loaded or refreshed, the start() method is invoked.
• It is also invoked whenever the applet is maximized, restored, or moving from one tab to
another in the browser.
• It is in an inactive state until the init() method is invoked.
stop():
• The stop() method stops the execution of the applet.
• The stop () method is invoked whenever the applet is stopped, minimized, or moving from
one tab to another in the browser, the stop() method is invoked. When we go back to that
page, the start() method is invoked again.
destroy():
• The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed.
• It removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
paint():
• The paint() method belongs to the Graphics class in Java. It is used to draw shapes like
circle, square, trapezium, etc., in the applet.
• It is executed after the start() method and when the browser or applet windows are resized.