0% found this document useful (0 votes)
14 views13 pages

Java Unit - II

Uploaded by

anil kasula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

Java Unit - II

Uploaded by

anil kasula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-II

Arrays, Command Line Arguments, Strings-String Class Methods


Classes & Objects: Creating Classes, declaring objects, Methods, parameter passing, static fieldsand
methods, Constructors, and ‘this’ keyword, overloading methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member access rules, ‘super’ keyword,
preventing inheritance: final classes and methods, the object class and its methods; Polymorphism:
Dynamic binding, method overriding, abstract classes and methods;

1. Arrays in Java
Definition:
An array is a collection of elements of the same data type stored in contiguous memory locations. It
allows storing multiple values under a single variable name.
Array Declaration:
An array can be declared in two parts:
1. Declaration: Specifies the type of elements the array will hold.
2. Initialization: Specifies the size or values of the array.
Array Syntax:
• Declaration: type[] arrayName; or type arrayName[];
• Initialization: arrayName = new type[size];
Example:
int[] arr = new int[5]; // Array of integers with 5 elements
arr[0] = 10; // Initializing the first element

// Or, using initialization shorthand


int[] arr2 = {1, 2, 3, 4, 5};
Accessing Array Elements:
Array elements can be accessed using an index, starting from 0.
System.out.println(arr[0]); // Accessing first element: Output: 10
Multi-Dimensional Arrays:
Arrays can have more than one dimension (2D, 3D, etc.).
• 2D Array Example:
int[][] matrix = new int[3][3]; // A 3x3 matrix
matrix[0][0] = 1;
matrix[2][2] = 5;
Common Array Operations:
• Length of an array: arr.length
• Iterating over arrays using loops:
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
2. Command Line Arguments
Definition:
Command line arguments allow users to pass input values to a program when running it from the
command line. These arguments are passed as an array of strings (String[] args) to the main() method.
Syntax:
When running the Java program, command-line arguments are provided as space-separated values.
java ProgramName arg1 arg2 arg3
Accessing Command Line Arguments:
• The arguments are passed as a String[] array.
• The args array holds the input values provided by the user.
Example:
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (String arg : args) {
System.out.println(arg);
} }}
Run the program with arguments:
$ java CommandLineExample Hello World 123
Output:
Number of arguments: 3
Hello
World
123

3. Strings and String Class Methods


Definition:
In Java, a String is an object that represents a sequence of characters. The String class is part of
java.lang package, and its objects are immutable (i.e., their values cannot be changed after creation).
String Declaration:
• String initialization:
String str = "Hello, Java!";
• String objects are created using the new keyword as well:
String str2 = new String("Hello, Java!");
Common String Methods:
1. length():
• Returns the length of the string.
String str = "Java";
System.out.println(str.length()); // Output: 4
2. charAt(int index):
• Returns the character at the specified index.
String str = "Java";
System.out.println(str.charAt(0)); // Output: J
3. substring(int startIndex) and substring(int startIndex, int endIndex):
• Extracts a part of the string from a given index or between two indices.
String str = "Programming";
System.out.println(str.substring(3)); // Output: "gramming"
System.out.println(str.substring(0, 4)); // Output: "Prog"
4. toLowerCase() and toUpperCase():
• Converts the string to lowercase or uppercase.
String str = "Java";
System.out.println(str.toLowerCase()); // Output: java
System.out.println(str.toUpperCase()); // Output: JAVA
5. equals(String anotherString):
• Compares two strings for equality.
String str1 = "Java";
String str2 = "java";
System.out.println(str1.equals(str2)); // Output: false
6. equalsIgnoreCase(String anotherString):
• Compares two strings for equality, ignoring case differences.
String str1 = "Java";
String str2 = "java";
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true
7. trim():
• Removes leading and trailing whitespace from the string.
String str = " Java ";
System.out.println(str.trim()); // Output: "Java"
8. replace(char oldChar, char newChar):
• Replaces all occurrences of a character in the string.
String str = "Java";
System.out.println(str.replace('a', 'o')); // Output: Jovo
9. indexOf(String str):
• Finds the first occurrence of a substring in the string.
String str = "Hello, Java!";
System.out.println(str.indexOf("Java")); // Output: 7
10. split(String regex):
• Splits the string into an array of substrings based on a delimiter or regular expression.
String str = "apple,banana,cherry";
String[] fruits = str.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Output:
// apple
// banana
// cherry
String Concatenation:
Strings can be concatenated using the + operator or the concat() method.
String str1 = "Hello";
String str2 = "World";
System.out.println(str1 + " " + str2); // Output: Hello World
System.out.println(str1.concat(" ").concat(str2)); // Output: Hello World

Key Points:
• Arrays: Useful for storing multiple values in a single variable; index-based access.
• Command Line Arguments: Allow passing arguments to the main method; useful for dynamic
input.
• Strings: Immutable objects; many built-in methods like substring(), toUpperCase(), equals(),
etc., make string manipulation easy.

Notes on Classes & Objects in Java

1. Classes and Objects in Java


Class in Java
A class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors
(methods) that the objects created from the class will have.
• Syntax to declare a class:
class ClassName {
// Fields (attributes)
dataType fieldName;

// Methods (behaviors)
returnType methodName(parameters) {
// Method body
}
}
Object in Java
An object is an instance of a class. It is created using the new keyword and is used to access the fields
and methods of the class.
• Syntax to declare and initialize an object:
ClassName objectName = new ClassName();
Example:
class Car {
String make;
String model;
int year;

// Method
void startEngine() {
System.out.println("The engine of " + make + " " + model + " is now started.");
}
}
public class Main {
public static void main(String[] args) {
// Create object
Car car1 = new Car();
car1.make = "Toyota";
car1.model = "Corolla";
car1.year = 2021;

car1.startEngine(); // Calling method on the object


}
}
Output:
The engine of Toyota Corolla is now started.

2. Methods in Java
Methods define the behavior of the class and represent actions or functionality that the object can
perform.
Method Declaration:
• Syntax:
returnType methodName(parameters) {
// method body
}
Method Types:
1. Instance Methods: These methods belong to an object. They require an object to be called.
2. Static Methods: These methods belong to the class and can be called without an instance of the
class.
Example:
class Person {
String name;
int age;
// Instance method
void greet() {
System.out.println("Hello, " + name + "!");
}
// Static method
static void displayInfo() {
System.out.println("This is a static method in the Person class.");
}}
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "John";
person1.greet(); // Calling instance method
Person.displayInfo(); // Calling static method without object
}}

3. Parameter Passing in Methods


Pass-by-Value:
In Java, primitive data types are passed by value, meaning a copy of the original value is passed to the
method.
class Calculator {
void add(int a, int b) {
int result = a + b;
System.out.println("Sum: " + result);
}}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int x = 10, y = 5;
calc.add(x, y); // Arguments passed by value
}}
Pass-by-Reference (for Objects):
For objects, a reference (memory address) is passed to the method, meaning changes to the object's
fields within the method will affect the original object.
class Person {
String name;
void changeName(String newName) {
name = newName; // Modifying the original object
}}
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "John";
System.out.println("Before: " + person1.name); // Output: John
person1.changeName("Mike");
System.out.println("After: " + person1.name); // Output: Mike
}}

4. Static Fields and Methods


Static Fields:
• Static fields are shared among all objects of a class.
• These fields belong to the class, not instances, and are accessed using the class name.
Example:
class Car {
static int carCount = 0; // Static field to count cars

Car() {
carCount++; // Increment car count each time a car object is created
}

static void displayCarCount() {


System.out.println("Number of cars: " + carCount);
}}
public class Main {
public static void main(String[] args) {
new Car(); // Creates a new car object
new Car(); // Creates another car object
Car.displayCarCount(); // Access static method
}}
Output:
Number of cars: 2
Static Methods:
• Static methods belong to the class and can be called without an instance of the class.
• They cannot access instance variables or instance methods directly.
class Utility {
static void printMessage() {
System.out.println("This is a static method.");
}}
public class Main {
public static void main(String[] args) {
Utility.printMessage(); // Call static method without creating an object
}}

5. Constructors in Java
Definition:
A constructor is a special method used to initialize objects. It has the same name as the class and does
not have a return type.
Types of Constructors:
1. Default Constructor: Automatically provided by Java if no constructor is defined.
2. Parameterized Constructor: Allows you to initialize object fields with specific values when the
object is created.
Constructor Syntax:
class ClassName {
// Constructor
ClassName(parameters) {
// Initialization code
}}
Example:
class Car {
String make;
String model;
int year;
// Parameterized constructor
Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
void displayDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Tesla", "Model S", 2022); // Using parameterized constructor
car1.displayDetails();
}}

6. The this Keyword in Java


The this keyword is used to refer to the current object. It is mainly used to:
1. Differentiate between instance variables and parameters.
2. Invoke current class methods.
3. Call other constructors in the same class.
Example:
class Person {
String name;
int age;
// Constructor with parameters
Person(String name, int age) {
this.name = name; // 'this' distinguishes instance variable from parameter
this.age = age;
}
void greet() {
System.out.println("Hello, " + this.name);
}}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, Alice
}}
• Calling another constructor:
class Car {
String make;
String model;
// Default constructor
Car() {
this("Unknown", "Unknown"); // Calls another constructor within the class
}
// Parameterized constructor
Car(String make, String model) {
this.make = make;
this.model = model;
}
void display() {
System.out.println("Make: " + make + ", Model: " + model);
}}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.display(); // Output: Make: Unknown, Model: Unknown
}}

7. Method Overloading in Java


Definition:
Method Overloading occurs when two or more methods in the same class have the same name but
different parameters (either in number, type, or both).
Overloading Example:
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles
double add(double a, double b) {
return a + b;
}}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // Calls the method with two integers
System.out.println(calc.add(1, 2, 3)); // Calls the method with three integers
System.out.println(calc.add(1.5, 2.5)); // Calls the method with two doubles
}}
Output:
5
6
4.0
Access Modifiers:
Access modifiers control the visibility of methods and fields:
1. public: Accessible from any other class.
2. private: Accessible

Notes on Inheritance and Polymorphism in Java

1. Inheritance in Java
Definition:
Inheritance is a mechanism in Java where one class acquires the properties and behaviors (methods) of
another class. This helps in reusability of code and is a fundamental feature of Object-Oriented
Programming (OOP).
• Super Class (Parent Class): The class whose properties and methods are inherited.
• Sub Class (Child Class): The class that inherits the properties and methods from the parent
class.
Syntax:
class SubClass extends SuperClass {
// Subclass-specific code
}
Inheritance Hierarchy:
An inheritance hierarchy is a system where multiple classes are related in a parent-child structure.
• Single Inheritance: One class inherits from another class.
• Multilevel Inheritance: A class inherits from a class, which is also a subclass of another class.
• Hierarchical Inheritance: Multiple classes inherit from a single parent class.
• Multiple Inheritance: Java does not support multiple inheritance directly (i.e., a class cannot
inherit from more than one class). However, this can be achieved through interfaces.
Example of Single Inheritance:
class Animal {
void eat() {
System.out.println("Animal eats food.");
}}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}
Output:
Animal eats food.
Dog barks.
2. super Keyword
The super keyword is used to refer to the parent class (superclass) of the current object. It is commonly
used in two scenarios:
1. Access Parent Class Constructor: To invoke the parent class constructor.
2. Access Parent Class Methods/Fields: When the subclass has overridden a method from the
superclass.
Example of Using super:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
super.makeSound(); // Calls the parent class method
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
}
Output:
Animal makes a sound
Dog barks
Example of super with Constructor:
class Animal {
Animal(String name) {
System.out.println("Animal name: " + name);
}
}

class Dog extends Animal {


Dog(String name) {
super(name); // Calls the parent constructor
System.out.println("Dog name: " + name);
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Bulldog");
}
}
Output:
Animal name: Bulldog
Dog name: Bulldog
3. Member Access Rules in Inheritance
In Java, members (fields and methods) of a class can have different access levels, and their accessibility
in the subclass depends on the access modifiers used:
• private: Members cannot be inherited or accessed by subclass.
• default (no modifier): Accessible within the same package.
• protected: Accessible in the subclass (even if it's in a different package).
• public: Accessible everywhere.
Example:
class Parent {
private String privateField = "Private";
public String publicField = "Public";
protected String protectedField = "Protected";
String defaultField = "Default";
}

class Child extends Parent {


void printFields() {
// System.out.println(privateField); // Not accessible, private member
System.out.println(publicField); // Accessible
System.out.println(protectedField); // Accessible
System.out.println(defaultField); // Accessible (within the same package)
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.printFields();
}
}
Output:
Public
Protected
Default
4. Preventing Inheritance
Java provides the final keyword to prevent inheritance or method overriding.
• final Class: A final class cannot be subclassed.
• final Method: A final method cannot be overridden in a subclass.
Example:
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}

class SubClass extends FinalClass { // Compile-time error: cannot inherit from final class
// Additional code
}
final Method Example:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}

class Child extends Parent {


void display() { // Compile-time error: cannot override a final method
System.out.println("This will not compile.");
}
}

5. The Object Class in Java


Every class in Java implicitly extends the Object class. The Object class is the root class of all Java
classes. It provides some essential methods that are inherited by all Java classes.
Common Methods in the Object Class:
1. toString(): Returns a string representation of the object.
2. equals(): Compares two objects for equality.
3. hashCode(): Returns a unique integer hash code for the object.
4. clone(): Creates and returns a copy of the object.
5. getClass(): Returns the runtime class of the object.
Example:
class Person {
String name;

Person(String name) {
this.name = name;
}

@Override
public String toString() {
return "Person{name='" + name + "'}";
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person("Alice");
System.out.println(person.toString()); // Calls the overridden toString() method
}
}
Output:
Person{name='Alice'}

6. Polymorphism in Java
Definition:
Polymorphism is the ability of an object to take on many forms. It allows one interface to be used for
different underlying forms (objects). There are two types of polymorphism:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)
Runtime Polymorphism (Method Overriding)
Method overriding occurs when a subclass provides a specific implementation of a method that is
already defined in its superclass. It is determined at runtime.
• Syntax for Method Overriding:
@Override
void methodName() {
// Subclass-specific implementation
}
Example of Method Overriding:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();

myAnimal.sound(); // Animal's sound


myDog.sound(); // Dog's sound (overridden method)
}
}
Output:
Animal makes a sound
Dog barks
Abstract Classes and Methods
Abstract classes are classes that cannot be instantiated on their own. They are meant to be inherited
by other classes. An abstract method is a method declared in an abstract class that does not have a
body. Subclasses must provide their own implementation of the abstract methods.
Abstract Class Syntax:
abstract class Animal {
abstract void sound(); // Abstract method

void sleep() {
System.out.println("Animal sleeps");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}
Example:
abstract class Shape {
abstract void draw(); // Abstract method

void displayInfo() {
System.out.println("This is a shape.");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}

public class Main {


public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
shape.displayInfo();
}
}
Output:
Drawing a circle
This is a shape.
Key Points:
• Inheritance allows code reusability and establishes a parent-child relationship.
• Polymorphism lets us use the same method name for different objects (method overriding and
overloading).
• The super keyword helps access parent class members and constructors.
• Abstract classes cannot be instantiated and must be extended by subclasses that implement
the abstract methods.

You might also like