Java - Unit2 2023-24 (CS Major)
Java - Unit2 2023-24 (CS Major)
Arrays
What is an array and Explain types of arrays with examples?
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the 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.
// Length of strings
System.out.println("Length of String 1: " + str1.length());
System.out.println("Length of String 2: " + str2.length());
// Substring
String subStr = str1.substring(0, 5);
System.out.println("Substring of String 1 (0-5): " + subStr);
// Concatenation
String concatenated = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenated);
// Trimming
String trimmed = " Hello ".trim();
System.out.println("Trimmed String: '" + trimmed + "'");
// Replacing characters
String replaced = str1.replace("World", "Java");
UNIT-2
// Character access
char ch = str1.charAt(1);
System.out.println("Character at index 1 of String 1: " + ch);
// Comparing strings
boolean isEqual = str1.equals(str2);
System.out.println("Are String 1 and String 2 equal? " + isEqual);
// String formatting
String formatted = String.format("Formatted Output: Name: %s, Age: %d", "Alice", 30);
System.out.println(formatted);
}
}
When we define a class we can easily create a number of instances of that class
Creating class in java:
In java, a class can be defined through the use of class keyword. The general definition of a
class is given below:
class classname
{
type instance_variable1;
type instance_variable1;
………
returntype methodname(parameter list)
{
// body of method
}
……………………..
}
Here,
● class is a keyword used to define class
UNIT-2
● class name is the identifier that specifies the name of the class
● type specifies the datatype of the variable
● instance_variable1, . . . are the variable defined in the class
● method name is the method defined in the class that can operate on the variables in
the class
Example:
class Sample
{ int x, y;
setXY()
{
x=10; y=20;
}
}
The variables defined in the class are called member variables/data members
The functions defined in the class are called member functions/member methods.
Both data members and member methods together called members of class.
Concept of Objects
Objects are instances of a class. Objects are created and this process is called
“Instantiation”. In java objects are created through the use of new operator. The new operator
creates an object and allocates memory to that object. Since objects are created at runtime,
they are called runtime entities.
In java object creation is a two step process.
Step1: create a reference variable of the class. When this declaration is made a
reference variable is created in memory and initialized with null.
Example: Sample s;
Step2: create the object using the new operator and assign the address of the
object to the reference variable created in step1.
Example: Sample s=new Sample();
The step2 creates the object physically and stores the address of the object in the
reference variable.
Accessing members of an object:
Once an object of a class is created we can access the members of the class through the use of
object name and „.„ (dot) operator.
Syntax: objectname. member;
Example:
class sample
{ int x, y;
setXY()
{
x=10; y=20;
}
UNIT-2
printXY()
{ System.out.print(“=”+x);
System.out.print(“=”+y);
}
}
class Demo
{ public static void main(String ar[])
{ sample s;
s=new sample();
s.setXY();
s.printXY();
}
}
Constructors
A constructor is a special kind of method that has the same name as that of class in
which it is defined. It is used to automatically initialize an object when the object is created.
Constructor gets executed automatically at the time of creating the object. A constructor
doesn‟t have any return type.
Example: // program to demonstrate constructor
class Student
{
int number;
String name;
Student() // default constructor
{
number=569;
name=”satyam”;
}
Student(int no, String s) // parameterized constructor
{
number=no;
name=s;
}
void showStudent()
{
System.out.println(“number =”+number);
System.out.println(“name =”+name);
}
}
class Demo
{
public static void main(String ar[])
{
Student s1=new Student();
UNIT-2
„this‟ keyword
„this‟ keyword : „this‟ keyword refers to the current object. Sometimes a member method
of a class needs to refer to the object in which it was invoked. In order to serve this purpose
java introduces “this keyword”. By using „this‟ keyword we can remove name space conflict.
Name Space Conflict: When the parameters of a member method have the same name as
that of instance variables of the class, local variables take the priority over the instance
variable. This leads to conflict called „name space conflict‟. It can be resolved with “this” .
Example:
class Student
{
int number;
String name;
void setStudent(int number, String name)
{
this.number=number;
this.name=name;
}
void showStudent()
{ System.out.println(“number=”+number);
System.out.println(“name=”+name);
}
}
class Display
{
public static void main(String ar[])
{
Student s=new Student(); // object creation for class Student
s.setStudent(1,”Rama”);
s.showStudent();
}
}
UNIT-2
Overloading Constructors
Just like member methods constructors can also be overloaded. The following example
emonstrates this,
class Student
{ int no;
String name;
Student()
{ no=70;
name=”ram”;
}
Student(int n, String s)
{ no=n; name=s;
}
void show()
{ System.out.println(“Number=”+no);
System.out.println(“Name=”+name);
}
}
class Display
{ public static void main(String ar[])
{
Student s1= new Student();
Student s2= new Student(69,”satya”);
s1.show();
s2.show();
}
}
Output: number=70
name=ram
number=69
name=satya
When a modification is performed on a static variable the change will be reflected in all
objects of the class for which the static variable is a member.
Static Methods:
● A static method can call other static methods only
● A static method can access static variables only
● Static methods can‟t have access to this/ super keyword.
Static Blocks:
Just like static variables and static methods we can also create a static block . this static block
is used to initialize the static variables.
Example program:
class UseStatic
{ static int a=3;
static int b;
static void meth(int x)
{
System.out.println(“x=” + x);
System.out.println(“a=” + a);
System.out.println(“b=” + b);
}
static
{
System.out.println(“static block initialized”);
}
public static void main(String args[])
{
meth(69);
}
}
INHERITANCE
What is inheritance?
Inheritance in Java is a mechanism in which one object acquires(inherits/derives) all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and variables of the parent class.
Moreover, you can add new methods and variables in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
UNIT-2
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
UNIT-2
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one
of its parent class, it is known as method overriding.
UNIT-2
s.setStudent(69,81,”ramu”);
s.showStudent();
}
}
Output: number=1
marks=89
name=rama
number=69
marks=81
name=ramu
Super Keyword
In Java, the super keyword is used to refer to the superclass (the parent class) of the current object. It is often
used in the context of inheritance and can serve several purposes:
1. Accessing Superclass Methods
You can use super to call a method defined in the superclass that has been overridden in the subclass.
class Parent {
void display() {
System.out.println("Display from Parent");
}
}
class Child extends Parent {
void display() {
System.out.println("Display from Child");
}
void show() {
super.display(); // Calls the Parent's display method
}
}
public class SuperExample {
public static void main(String[] args) {
Child child = new Child();
child.show(); // Output: Display from Parent
}
}
// Output:
// Parent Constructor
// Child Constructor
}
}
void displayNames() {
System.out.println("Child name: " + name); // Child's name
System.out.println("Parent name: " + super.name); // Parent's name
}
}
public class SuperExample {
public static void main(String[] args) {
Child child = new Child();
child.displayNames();
// Output:
// Child name: Child
// Parent name: Parent
}
}