PROGRAMMING USING JAVA UNIT-II
OBJECT ORIENTATION : CASTING
Assigning one data type to another or one object to another is known as casting. Java supports
two types of casting – data type casting and object casting.
Conditions For Casting
1. Same class objects can be assigned one to another.
2. Subclass object can be assigned to a super class object and this casting is done implicitly. This is
known as Upcasting (upwards in the hierarchy from subclass to super class).
3. Java does not permit to assign a super class object to a subclass object (implicitly) and still to do
so, we need explicit casting. This is known as downcasting (super class to
subclass). Downcasting requires explicit conversion.
Example:
class Flower
{
public void smell()
{
System.out.println("All flowers give smell, if you can smell");
}
}
public class Rose extends Flower
{
public void smell()
{
System.out.println("Rose gives rosy smell");
}
public static void main(String args[])
{
Flower f = new Flower();
Rose r = new Rose();
f.smell();
r.smell();
f = r; // subclass to super class, it is valid
f.smell();
// r = f; // super class to subclass, not valid
r = (Rose) f; // explicit casting
f.smell();
}
}
Output:
All flowers give smell, if you can smell
Rose gives rosy smell
Rose gives rosy smell
Rose gives rosy smell
1 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
IMPLEMENTING AN INTERFACE
To declare a class that implements an interface, you include an implements clause in the class
declaration.
Your class can implement more than one interface, so the implements keyword is followed by a
comma-separated list of the interfaces implemented by the class.
By convention, the implements clause follows the extends clause, if there is one.
Declare An Interface?
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods declared in
the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
A Sample Interface, Relatable
Consider an interface that defines how to compare the size of objects.
public interface Relatable
{
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other
publicintisLargerThan(Relatable other);
}
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
2 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Interface: Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.
interface printable
{
void print();
}
class A6 implements printable
{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Legal Return Types: Return Type Declarations - Returning a Value
Legal Return Types
A return statement causes the program control to transfer back to the caller of a method.
Every method in Java is declared with a return type and it is mandatory for all java methods.
A return type may be a primitive type like int, float, double, a reference type or void type(returns
nothing).
There are a few important things to understand about returning the values
The type of data returned by a method must be compatible with the return type specified by
the method. For instance, if the return type of some method is boolean, we can not return an
integer.
The variable receiving the value returned by a method must also be compatible with the return
type specified for the method.
The parameters can be passed in a sequence and they must be accepted by the method in the
same sequence.
3 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Example:
public class ReturnTypeTest1
{
publicint add()
{ // without arguments
int x = 30;
int y = 70;
int z = x+y;
return z;
}
public static void main(String args[])
{
ReturnTypeTest1 test = new ReturnTypeTest1();
int add = test.add();
System.out.println("The sum of x and y is: " + add);
}
}
Output:
The sum of x and y is: 100
RETURN TYPE DECLARATIONS
A method is a function declared inside a class that contains a group of statements.
It is used to perform certain tasks or processing of data in the program to yield the expected
results.
A method can accept data from outside and can also return the results. To return the result, a
return statement is used inside a method to come out of it to the calling method.
Return type may be a primitive data type like int, float, double, a reference type, or void type
which represents “return nothing”. i.e, they don’t give anything back.
When a method is called, the method may return a value to the caller method.
Example :
Here, we will write a program to return the square of a number from a method. Look at the following
source code.
public class Test
{
int square(intnum){
returnnum * num; // return a square value.
}
public static void main(String[] args)
{
// Create an obejct of class Test.
Test t = new Test();
// Call the method using object reference variable. Since the return type of this
method is int, we will store it using a variable of type int.
intsquareOfNumber = t.square(20);
4 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
// Displaying the result.
System.out.println("Square of 20: " +squareOfNumber);
}
}
Output:
Square of 20: 400
RETURNING A VALUE
return is a reserved keyword in Java i.e, we can’t use it as an identifier. It is used to exit from a
method, with or without a value.
return can be used with methods in two ways:
1. Methods returning a value : For methods that define a return type, return statement must
be immediately followed by return value.
Example:
Java program to illustrate usage of return keyword
class A
{
// Since return type of RR method is double
// so this method should return double value
double RR(double a, double b)
{
double sum = 0;
sum = (a + b) / 2.0;
// return statement below:
return sum;
}
public static void main(String[] args)
{
System.out.println(new A().RR(5.5, 6.5));
}
}
Output:
6.0
CONSTRUCTORS AND INSTANTIATION
Instantiation is an immense word to define a universal and straightforward concept in Java
programming, creating new instances of objects.
In other words, creating an object of the class is called instantiation.
It occupies the initial memory for the object and returns a reference. An object instantiation in
Java provides the blueprint for the class.
Syntax for Instantiation
ClassName objName = new ClassName();
Creating Instances
5 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
There are two ways to create instances:
o Using the new Keyword
o Using Static Factory Method
OVERLOADED CONSTRUCTORS
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists.
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
//Java program to overload constructors
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
FDDFAryan 25
111 Karan 0
222 Aryan 25
Initialization Blocks
The initialization of the instance variable can be done directly but there can be performed
extra operations while initializing the instance variable in the instance initializer block.
Why use instance initializer block?
6 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Suppose I have to perform some operations while assigning value to instance data member e.g.
a for loop to fill a complex array or error handling etc.
Example:
class Bike7
{
int speed;
Bike7( )
{
System.out.println("speed is "+speed);
speed=100;
}
public static void main(String args[])
{
Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
OUTPUT:
SPEED IS100
SPEED IS 100
Statics: Static Variables and Methods
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:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
STATIC VARIABLE
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
7 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
EXAMPLE
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//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);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
OUTPUT:
111 KARAN ITS
222 ARYAN ITS
Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:
125
8 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Assignments: Stack and Heap
In Java, memory management is a vital process. It is managed by Java automatically. The
JVM divides the memory into two parts: stack memory and heap memory.
From the perspective of Java, both are important memory areas but both are used for different
purposes.
The major difference between Stack memory and heap memory is that the stack is used to store
the order of method execution and local variables while the heap memory stores the objects and it
uses dynamic memory allocation and deallocation.
Stack Memory
The stack memory is a physical space (in RAM) allocated to each thread at run time. It is
created when a thread creates. Memory management in the stack follows LIFO (Last-In-First-Out)
order because it is accessible globally. It stores the variables, references to objects, and partial results.
Memory allocated to stack lives until the function returns.
Heap Memory
It is created when the JVM starts up and used by the application as long as the application
runs. It stores objects and JRE classes. Whenever we create objects it occupies space in the heap
memory while the reference of that object creates in the stack.
It does not follow any order like the stack. It dynamically handles the memory blocks. It
means, we need not to handle the memory manually.
For managing the memory automatically, Java provides the garbage collector that deletes the
objects which are no longer being used.
Difference Between Stack and Heap Memory
Parameter Stack Memory Heap Space
Application It stores items that have a very short It stores objects and Java Runtime
life such as methods, Environment (JRE) classes.
variables, and reference variables of
the objects.
Ordering It follows the LIFO order. It does not follow any order because it is
a dynamic memory allocation and does
not have any fixed pattern for allocation
and deallocation of memory blocks.
Flexibility It is not flexible because we cannot It is flexible because we can alter the
alter the allocated memory. allocated memory.
Efficiency It has faster access, allocation, and It has slower access, allocation, and
deallocation. deallocation.
Memory It is smaller in size. It is larger in size.
Size 9 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
The following table summarizes all the major differences between stack memory and heap space.
Literals, Assignments, and Variables
There are 4 types of variables in Java programming language:
Instance Variables (Non-Static Fields)
Class Variables (Static Fields)
Local Variables
Parameters
Literals are data used for representing fixed values. They can be used directly in the code.
Types of Literals:
1. Boolean Literals. In Java, boolean literals are used to initialize boolean data types.
2. Integer Literals. An integer literal is a numeric value(associated with numbers) without any
fractional or exponential part. ...
3. Floating-point Literals.
4. Character Literals.
5. String literals.
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store two values: true and
false. For example
boolean flag1 = false;
boolean flag2 = true;
Here false and true are Boolean literals
2. Integer Literals
An integer literal is a numeric value(associated with numbers) without any fractional or exponential
part. There are 4 types of integer literals in Java:
1. binary (base 2)
2. decimal (base 10)
3. octal (base 8)
4. hexadecimal (base 16)
3. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponential form.
4. Character Literals
Character literals are unicode character enclosed inside single quotes.
5. String literals
A string literal is a sequence of characters enclosed inside double-quotes. For example,
String str1 = "Java Programming";
String str2 = "Programiz";
Here, Java Programming and Programiz are two string literals.
Literal Values for All Primitive Types
A literal is a specific value stored in the computer in a specific format. We can store numbers, text,
specific characters, a list of values like a shopping list, and many other things. Each one has its own
format and size. Depending on the literal there is a set of operations we can perform on it.
Primitive Values
Primitive types should be written in lowercase (Your first grammar rule). And they are, byte, char,
boolean, short, int, long, double, and float.
10 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Integer Primitive Types
The following types were designed to work with numbers. Though exist a little exception with char, it
stores numbers but those numbers are used to represent symbols, letters, and digits to be displayed as a
text on your screen.
byte:
It uses 8 bits (1 byte).
It is used to represent numbers in the range [-128, +127].
It is pretty fast to processed addition, subtraction, etc.
charIt uses 16 bits (12 bytes).
It is used to represent numbers in the range [0, 65535].
It is used to represent Unicode Characters
A Unicode character is a number that represents a symbol, letter or digit
It can be used as a number but was created to be a character and display the corresponding symbol
on the screen.
short:It uses 16 bits (2 bytes).
It is used to represent numbers in the range [-32 768, +32 767].
This is converted to a character easily whenever you want it.
It is pretty fast to processed addition, subtraction, etc.
intIt uses 32 bits (4 bytes).
It is used to represent numbers in the range [-2,147,483,648, +2,147,483,6487].
This is one of the common primitive types to represent numbers.
longIt uses 64 bits (8 bytes).
It is used to represent a huge range of numbers the range is
[-9,223,372,036,854,775,808, +9,223,372,036,854,775,807].
You should use this type carefully. It can slow down your computer.
Decimal Primitive Types:
Float and double were created to work with decimal numbers. In programming, they are known as
floating-point numbers.
double
It uses 32 bits (4 bytes)
It is used to represent decimal numbers and perform operations like division, the square root of a
number.
float
It uses 64 bits (8 bytes)
It is used to represent decimal numbers and perform operations like division, the square root of a
number.
Two special primitive type
boolean
It uses 8 bits (1 byte).
It was created to answer yes-no questions.
Though it has 8 bits, it only stores 2 values, true or false.
Internally 00000000 is the same as false.
Internally 11111111 is the same as true.
void
It is a type to express that there is no value to store at all.
We cannot use it in our variable definitions.
11 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Normally it is used when creating some functions.
Scope - Variable Initialization
Scope is that area of the program where the variable is visible to a program and can be used
(accessible). i.e. the scope of variable determines its accessibility for other parts of program.
Java allows declaring variables within any block. A block defines a scope that starts with an opening
curly brace and ends with a closing curly brace.
There are three types of variables in java, depending on their scope:
local variables
instance variables
class variables (static variables).
Scope of Local Variables in Java
1. When the local variable is created inside a method, constructor, or block, their scope only remains
within the method, block, or constructor.
Scope of Instance variables in Java
The scope of instance variables is inside the class. They are visible inside all the methods,
constructors, and from the beginning of its program block to the end of program block in the class.
Syntax
ObjectReference.VariableName;
Scope of Static variables
The scope of a static variable is within the class. All the methods, constructors, and blocks
inside the class can access static variables by using the class name. It has the following general form:
Syntax:
ClassName.VariableName;
Example program:
packagestaticVariable;
public class StaticTest
{
// Declaration of static variable.
staticint a = 20;
void m1()
{
int a = 30;
System.out.println("a: " +a);
System.out.println("a: " +StaticTest.a); // Accessing static variable using class name within instance
method.
}
public static void main(String[] args)
{
StaticTestst = new StaticTest();
st.m1();
}}
Output:
a:30
a:20
12 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Passing Variables into Methods: Passing Object Reference Variables - Passing
Primitive Variables.
Information can be passed to methods as parameter. Parameters act as variables inside the
method.
Parameters are specified after the method name, inside the parentheses.
You can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method to print
the full name:
EXAMPLE:
public class Main
{
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args)
{
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Passing Object Reference Variables
All object references in Java are passed by value. This means that a copy of the value will be
passed to a method.
But the trick is that passing a copy of the value also changes the real value of the object.
To understand why, start with this example:
publicclassObjectReferenceExample {
publicstaticvoid main(String... doYourBest) {
Simpsonsimpson = newSimpson();
transformIntoHomer(simpson);
System.out.println(simpson.name);
}
staticvoidtransformIntoHomer(Simpsonsimpson) {
simpson.name = "Homer";
}
}
classSimpson
{
String name;
}
13 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Passing Primitive Variables.
Like object types, primitive types are also passed by value.
Primitive variables are directly stored in stack memory.
Whenever any variable of primitive data type is passed as an argument, the actual parameters are
copied to formal arguments and these formal arguments accumulate their own space in stack memory.
publicclassPrimitiveByValueExample {
publicstaticvoid main(String... primitiveByValue) {
inthomerAge = 30;
changeHomerAge(homerAge);
System.out.println(homerAge);
}
staticvoidchangeHomerAge(inthomerAge) {
homerAge = 35;
}
}
Garbage collection:
Java garbage collection is the process by which Java programs perform automatic memory
management.
Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short.
When Java programs run on the JVM, objects are created on the heap, which is a portion of
memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these unused
objects and deletes them to free up memory.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
Example for Garbage Collection:
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in Object class as:
protected void finalize()
{
}
Gc( ) method:
The gc( ) method is used to invoke the garbage collector to perform cleanup processing.
The gc( ) is found in System and Runtime classes.
public static void gc(){}
14 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
Object is garbage collected
Object is garbage collected
Operators: Java Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Assignment Operators
The Assignment Operators
Following are the assignment operators supported by Java language −
Show Examples
Operator Description Example
Simple assignment operator. Assigns values from C = A + B will assign value
=
right side operands to left side operand. of A + B into C
Add AND assignment operator. It adds right
C += A is equivalent to C =
+= operand to the left operand and assign the result
C+A
to left operand.
Subtract AND assignment operator. It subtracts
C -= A is equivalent to C = C
-= right operand from the left operand and assign the
–A
result to left operand.
15 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Multiply AND assignment operator. It multiplies
C *= A is equivalent to C =
*= right operand with the left operand and assign the
C*A
result to left operand.
/= Divide AND assignment operator. It divides left
C /= A is equivalent to C = C
operand with the right operand and assign the
/A
result to left operand.
Relational Operators
The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example
Checks if the values of two operands are equal or
== (equal to) (A == B) is not true.
not, if yes then condition becomes true.
Checks if the values of two operands are equal or
!= (not equal to) not, if values are not equal then condition becomes (A != B) is true.
true.
Checks if the value of left operand is greater than
> (greater than) the value of right operand, if yes then condition (A > B) is not true.
becomes true.
Checks if the value of left operand is less than the
< (less than) value of right operand, if yes then condition (A < B) is true.
becomes true.
Arithmetic Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example
+ (Addition) Adds values on either side of the operator. A + B will give 30
16 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
Subtracts right-hand operand from left-hand
- (Subtraction) A - B will give -10
operand.
Multiplies values on either side of the
* (Multiplication) A * B will give 200
operator.
Divides left-hand operand by right-hand
/ (Division) B / A will give 2
operand.
Divides left-hand operand by right-hand
% (Modulus) B % A will give 0
operand and returns remainder.
Conditional Operators
The conditional operator is also known as a ternary operator. The conditional statements are
the decision-making statements which depends upon the output of the expression. It is represented by
two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also
a decision-making statement.
Syntax of a conditional operator
Expression1? expression2: expression3;
The pictorial representation of the above syntax is shown below,
17 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS
PROGRAMMING USING JAVA UNIT-II
EXAMPLE PROGRAM
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); //conditional operator
return 0;
}
Logical Operators.
The Logical Operators
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Operator Description Example
Called Logical AND operator. If both the operands are (A && B) is
&& (logical and)
non-zero, then the condition becomes true. false
Called Logical OR Operator. If any of the two operands
|| (logical or) (A || B) is true
are non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical
!(A && B) is
! (logical not) state of its operand. If a condition is true then Logical
true
NOT operator will make false.
18 Rajeswari College Of Arts & Science for Women-Ms.K.Rathi Devi-Dept. of CS