0% found this document useful (0 votes)
11 views16 pages

Unit 1

The document provides an overview of type conversion and casting in Java, explaining implicit and explicit conversions, along with methods, static members, and string manipulation. It covers inheritance types, including single, multilevel, hierarchical, and multiple inheritance through interfaces. Key concepts such as method syntax, method overloading, and the differences between String and StringBuffer classes are also discussed.

Uploaded by

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

Unit 1

The document provides an overview of type conversion and casting in Java, explaining implicit and explicit conversions, along with methods, static members, and string manipulation. It covers inheritance types, including single, multilevel, hierarchical, and multiple inheritance through interfaces. Key concepts such as method syntax, method overloading, and the differences between String and StringBuffer classes are also discussed.

Uploaded by

mahiphilip88
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Type Conversion and Casting

1. What is Type Conversion?


Type conversion in Java is the process of converting a value from one data type to another.
Java supports two types of conversion:
1. Implicit Type Conversion (Widening)
2. Explicit Type Casting (Narrowing)
2. Implicit Type Conversion (Widening)
Definition:
Implicit type conversion is an automatic conversion done by the Java compiler when:
 The destination type is larger
 No data loss occurs
Characteristics:
 No cast operator needed
 Safe conversion
 Happens automatically
Widening Order in Java:
byte → short → int → long → float → double
char → int → long → float → double
Example:
int a = 10;
double b = a; // implicit conversion
[Link](b);
✔ Output:
10.0
Why Java Allows Widening:
 Smaller data fits inside larger data type
 No precision loss
3. Explicit Type Casting (Narrowing)
Definition:
Explicit type casting is a manual conversion where:
 The destination type is smaller
 There is a risk of data loss
Characteristics:
 Cast operator required
 Programmer responsibility
 Data may be truncated
Syntax:
destinationType variable = (destinationType) value;
Example:
double x = 10.75;
int y = (int) x; // explicit casting
[Link](y);
✔ Output:
10
👉 Decimal part is lost.
4. Type Conversion with byte, short, and char
Important Rule:
Arithmetic operations convert byte, short, and char to int automatically.

Example:
byte a = 10;
byte b = 20;
byte c = (byte)(a + b); // casting required
✔ Without casting → compilation error

5. Type Casting with char


char to int:
char ch = 'A';
int x = ch;
[Link](x);
✔ Output:
65

int to char:
int y = 66;
char c = (char) y;
[Link](c);
✔ Output:
B

6. Type Conversion with float and double


Example:
float f = 10.5f;
double d = f; // widening

Narrowing:
double d = 12.34;
float f = (float) d;

7. Type Casting in Expressions


Example:
int a = 5;
int b = 2;

double result = a / b;
[Link](result);
✔ Output:
2.0
👉 Why?
Because a / b is integer division before assignment.

Correct Way:
double result = (double) a / b;
[Link](result);
✔ Output:
2.5

8. Type Casting with Objects (Reference Casting)


Java also allows casting of objects in inheritance.
Upcasting (Implicit):
class Animal {}
class Dog extends Animal {}

Animal a = new Dog(); // upcasting


✔ Safe and automatic

Downcasting (Explicit):
Dog d = (Dog) a; // downcasting
⚠ May cause ClassCastException if object is not actually a Dog.

Using instanceof:
if (a instanceof Dog) {
Dog d = (Dog) a;
}

Methods
1️. What is a Method?
A method is a block of code that:
 performs a specific task
 runs only when it is called
 helps avoid repetition and keeps code organized
👉 Think of it like a machine:
input → processing → output

2️.Why Use Methods?


 Code reusability ♻️
 Better readability 👀
 Easier debugging 🛠️
 Modular programming

3️. Method Syntax (General Form)


accessModifier returnType methodName(parameters) {
// method body
}
🔍 Example:
public static void greet() {
[Link]("Hello!");
}

4️.Parts of a Method
Let’s break that down 👇
Part Meaning
public Who can access the method
static Belongs to class (not object)
void Returns nothing
greet Method name
() Parameters
{} Method body

5️.Types of Methods
🔹 1. Predefined Methods
Already built into Java
Examples:
 [Link]()
 [Link]()
 [Link]()

🔹 2. User-Defined Methods
Created by the programmer
Example:
public static void sayHi() {
[Link]("Hi!");
}

6️.Method Calling
A method runs only when called
sayHi();
📍 Must be called inside main() or another method.

7️. Methods with Parameters


Parameters = input values
public static void greet(String name) {
[Link]("Hello " + name);
}
Call:
greet("Alex");

8️.Methods with Return Value


Return = output value
public static int add(int a, int b) {
return a + b;
}
Call:
int sum = add(3, 4);
⚠️Rule:
 If return type is not void, return is mandatory

9️.void vs return
void return
No value returned Sends value back
Just performs task Used in calculations

🔁 10️.Method Overloading
Same method name, different parameters
add(int a, int b)
add(double a, double b)
✔ Different:
 number of parameters OR
 data type of parameters

11. main() Method


public static void main(String[] args)
 Program execution starts here
 JVM looks for this method first

Static Block, Static Data, and Static Methods


1. Introduction
In Java, the static keyword is used for memory management primarily. It belongs to the class rather than
instances (objects) of the class. Static members (variables, methods, blocks) are shared among all objects of the
class.
2. Static Variables (Static Data)
Definition:
A static variable is shared by all objects of a class. It is initialized only once at the start of the program.
Syntax:
class Example {
static int count = 0; // static variable
}
Key Points:
 Stored in class memory, not in object memory.
 Can be accessed using [Link] or object reference (not recommended).
Example:
class Student {
static int collegeCode = 101; // shared by all students
String name;

Student(String n) {
name = n;
}

void display() {
[Link]("Name: " + name + ", College Code: " +
collegeCode);
}
}

public class TestStaticVariable {


public static void main(String[] args) {
Student s1 = new Student("Ravi");
Student s2 = new Student("Priya");

[Link]();
[Link]();

[Link]("Access directly: " + [Link]);


}
}
Output:
Name: Ravi, College Code: 101
Name: Priya, College Code: 101
Access directly: 101

3. Static Methods
Definition:
A static method belongs to the class, not to any object. It can be called without creating an object of the class.
Syntax:
class Example {
static void showMessage() {
[Link]("Hello from static method!");
}
}
Key Points:
 Can access static variables directly.
 Cannot access non-static (instance) variables directly.
 Can be called using [Link]().
Example:
class Calculator {
static int add(int a, int b) {
return a + b;
}
}

public class TestStaticMethod {


public static void main(String[] args) {
int sum = [Link](10, 20); // no object required
[Link]("Sum: " + sum);
}
}
Output:
Sum: 30

4. Static Block
Definition:
A static block is used to initialize static variables. It runs once when the class is loaded, before the main
method.
Syntax:
class Example {
static int num;
static {
num = 100;
[Link]("Static block executed");
}
}
Key Points:
 Executed automatically when class is loaded.
 Used for initialization of static variables.
 Can have multiple static blocks (executed in order).
Example:
class TestStaticBlock {
static int x;
static {
x = 50;
[Link]("Static block executed");
}

public static void main(String[] args) {


[Link]("Value of x: " + x);
}
}
Output:
Static block executed
Value of x: 50

5. Summary Table
Feature Memory Area Access When Executed/Initialized
Static Variable Class area [Link] Once when class loaded
Static Method Class area [Link]() Anytime
Static Block Class area Automatic When class loaded

6. Combined Example
class Student {
static int collegeCode;
String name;

// Static block
static {
collegeCode = 101;
[Link]("Static block: College Code initialized");
}
Student(String n) {
name = n;
}

// Static method
static void displayCollegeCode() {
[Link]("College Code: " + collegeCode);
}

void display() {
[Link]("Student: " + name + ", College Code: " +
collegeCode);
}
}

public class TestAllStatic {


public static void main(String[] args) {
Student s1 = new Student("Ravi");
Student s2 = new Student("Priya");

[Link]();
[Link]();

[Link](); // calling static method


}
}
Output:
Static block: College Code initialized
Student: Ravi, College Code: 101
Student: Priya, College Code: 101
College Code: 101

STRING AND STRINGBUFFER CLASSES


1. Introduction
In Java, String and StringBuffer classes are used to store and manipulate text (sequence of characters).
Both classes belong to the package:
[Link]

2. String Class
Definition
The String class is used to create and manipulate immutable strings.
👉 Immutable means once a String object is created, its value cannot be changed.

Creating a String
1. Using String literal
String s1 = "Java";
2. Using new keyword
String s2 = new String("Java");

Immutability of String (Important)


String s = "Hello";
s = [Link](" World");
[Link](s);
📌 Output:
Hello World
✔ Here, a new String object is created.
❌ The original "Hello" is not modified.
Common String Methods
Method Description
length() Returns length of the string
charAt(index) Returns character at given index
concat() Joins two strings
equals() Compares content
equalsIgnoreCase() Compares without case
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
substring() Extracts part of string
indexOf() Finds position of character
replace() Replaces characters

Example Program – String Operations


class StringExample {
public static void main(String args[]) {
String s = "Java";

[Link]("Length: " + [Link]());


[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Character at index 1: " + [Link](1));
}
}
📌 Output:
Length: 4
Uppercase: JAVA
Lowercase: java
Character at index 1: a

3. StringBuffer Class
Definition
The StringBuffer class is used to create mutable strings.
👉 Mutable means the content can be changed without creating a new object.

Creating StringBuffer Object


StringBuffer sb = new StringBuffer("Java");

Why StringBuffer?
 Faster for frequent modifications
 Saves memory
 Thread-safe (synchronized)

Common StringBuffer Methods


Method Description
append() Adds text at the end
insert() Inserts text at given position
delete() Deletes characters
reverse() Reverses the string
replace() Replaces characters
capacity() Returns buffer capacity
length() Returns length

Example Program – StringBuffer Operations


class StringBufferExample {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");
[Link](sb);

[Link]();
[Link](sb);
}
}
📌 Output:
Java Programming
gnimmargorP avaJ

4. Difference Between String and StringBuffer


String StringBuffer
Immutable Mutable
Slower for modification Faster
Creates new object Modifies same object
Not synchronized Synchronized
Less memory efficient More memory efficient

Inheritance in Java
Inheritance in Java is a core OOP concept that allows a class to acquire properties and behaviors from
another class. It helps in creating a new class from an existing class, promoting code reusability and better
organization.
 A subclass can reuse the fields and methods of the parent class without rewriting the code
 A subclass can add its own fields and methods or modify existing ones to extend functionality.
Example: In the following example, Animal is the base class and Dog, Cat, and Cow are derived classes that
extend the Animal class.
//Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

// Child class
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}

// Child class
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}

// Child class
class Cow extends Animal {
void sound() {
[Link]("Cow moos");
}
}

// Main class
public class Geeks {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();

a = new Cat();
[Link]();

a = new Cow();
[Link]();
}
}

Output
Dog barks
Cat meows
Cow moos
Explanation:
 Animal is the base class.
 Dog, Cat and Cow are derived classes that extend Animal class and provide specific implementations of
the sound() method.
 The Geeks class is the driver class that creates objects and demonstrates runtime polymorphism using
method overriding.
Inheritance in Java

Syntax
class Parent {
// fields and methods
}
class Child extends Parent {
// additional fields and methods
}
Note: In Java, inheritance is implemented using the extends keyword.
Key Terminologies in Java Inheritance

Term Description

Class Blueprint from which objects are created


Term Description

Superclass Class whose properties are inherited

Subclass Class that inherits another class

extends Keyword used to inherit a class

Types of Inheritance in Java

Types of Inheritance in Java


Below are the different types of inheritance which are supported by Java.

1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior
of a single-parent class. Sometimes, it is also known as simple inheritance.
Single Inheritance

//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}

// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}

public class Test {


public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
Car obj = new Car();
}
}

Output
This is a Vehicle
This Vehicle is Car

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also
acts as the base class for other classes.
Multilevel Inheritance

class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
[Link]("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
[Link]("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
Car obj = new Car(); // Triggers all constructors in order
}
}

Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car

3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e. more than one
derived class is created from a single base class. For example, cars and buses both are vehicle
Hierarchical Inheritance

class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}

class Car extends Vehicle {


Car() {
[Link]("This Vehicle is Car");
}
}

class Bus extends Vehicle {


Bus() {
[Link]("This Vehicle is Bus");
}
}

public class Test {


public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances , one class can have more than one superclass and inherit features from all parent
classes.
Note: that Java does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces.

Multiple Inheritance
interface LandVehicle {
default void landInfo() {
[Link]("This is a LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
[Link]("This is a WaterVehicle");
}
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
[Link]("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
[Link]();
[Link]();
}
}

Output
This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid inheritance only
through Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
Hybrid Inheritance
Explanation:
 class Car extends Vehicle->Single Inheritance
 class Bus extends Vehicle and class Bus implements Interface Fare->Hybrid Inheritance (since Bus
inherits from two sources, forming a combination of single + multiple inheritance).
// First interface
interface A {
void showA();
}

// Second interface
interface B {
void showB();
}

// Class C implements both interfaces (Multiple inheritance)


class C implements A, B {
public void showA() {
[Link]("Interface A method");
}

public void showB() {


[Link]("Interface B method");
}
}

// Class D extends class C (Single inheritance)


class D extends C {
void showD() {
[Link]("Class D method");
}
}

// Main class
public class HybridInheritanceDemo {
public static void main(String[] args) {
D obj = new D();
[Link]();
[Link]();
[Link]();
}
}

📌 Creating Own Exception Classes


🔹 Definition
A custom (user-defined) exception is an exception created by the programmer to represent specific error
conditions in an application.

🔹 Steps to Create a Custom Exception


1. Create a class that extends Exception or RuntimeException
2. Define a constructor
3. Use throw to raise the exception
4. Handle using try-catch

🔹 Syntax
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}

🔹 Example: Checked Custom Exception


class MarksException extends Exception {
MarksException(String msg) {
super(msg);
}
}

class Student {
static void checkMarks(int marks) throws MarksException {
if (marks < 0 || marks > 100) {
throw new MarksException("Invalid marks");
}
[Link]("Valid marks");
}

public static void main(String[] args) {


try {
checkMarks(120);
} catch (MarksException e) {
[Link](e);
}
}
}

🔹 Example: Unchecked Custom Exception


class PasswordException extends RuntimeException {
PasswordException(String msg) {
super(msg);
}
}

class Login {
public static void main(String[] args) {
String password = "123";

if ([Link]() < 6) {
throw new PasswordException("Password too short");
}
[Link]("Login successful");
}
}

🔹 Points to Remember ⭐
 Custom exceptions improve clarity and control
 Checked exceptions must be declared or handled
 Unchecked exceptions are not forced by compiler
 Exception class name should end with Exception

🔹 Advantages
✔️Application-specific error handling
✔️Clean and readable code
✔️Meaningful error messages

🔹 Common Use Cases


 Age validation
 Banking transactions
 Login authentication
 Input validation
/

You might also like