0% found this document useful (0 votes)
9 views24 pages

Core Java (Unit Ii)

This document provides an overview of Java programming concepts, including class creation, data members, methods, access specifiers, overloading, and types of classes. It explains how to declare classes, create objects, use data members, and invoke methods, as well as the rules for access modifiers and the importance of method and constructor overloading. Additionally, it covers decision-making constructs and loops in Java, such as if-else statements, switch statements, and while loops.
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)
9 views24 pages

Core Java (Unit Ii)

This document provides an overview of Java programming concepts, including class creation, data members, methods, access specifiers, overloading, and types of classes. It explains how to declare classes, create objects, use data members, and invoke methods, as well as the rules for access modifiers and the importance of method and constructor overloading. Additionally, it covers decision-making constructs and loops in Java, such as if-else statements, switch statements, and while loops.
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/ 24

UNIT - II

1. Creating a class & subclass

In Java, a class is a blueprint or a template for creating objects (instances) with specific attributes
and behaviors. Here are the steps to declare a class, name a class, define rules for assigning classes
and subclasses, create objects, and find the class of an object:

1.1 Declaring a Class:

To declare a class in Java, you use the `class` keyword followed by the class name. Here's a simple
example:

public class MyClass {


// Class members (fields and methods) go here
}

1.2 Naming a Class:

Class names in Java should follow these rules:

- Class names must start with a letter (A-Z or a-z) or an underscore (_).

- The rest of the class name can contain letters, digits (0-9), and underscores.

- Class names are case-sensitive, meaning "MyClass" and "myclass" are considered different class
names.

1.3. Rules for Assigning Classes and Subclasses:

In Java, you can create subclasses by extending an existing class. The subclass inherits the fields
and methods of the superclass and can add or modify them. Here's an example of creating a
subclass:

public class SubClass extends SuperClass {


// Additional subclass members
}

- `SubClass` is the subclass, and `SuperClass` is the superclass it extends.

- You can extend a class using the `extends` keyword.

- A class can only extend one superclass in Java (single inheritance).


1.4 Creating Objects:

To create an object of a class, you use the `new` keyword, followed by the class constructor. The
constructor initializes the object and returns a reference to it. Here's how you create an object:

MyClass myObject = new MyClass();

- `MyClass` is the class name.

- `myObject` is the name of the object reference.

- `new MyClass()` is the object creation expression.

1.5 Finding the Class of an Object:

To determine the class of an object in Java, you can use the `getClass()` method provided by the
`Object` class, which is the root class for all Java classes. Here's an example:

MyClass myObject = new MyClass();


Class<?> objectClass = myObject.getClass();
System.out.println("Class of myObject: " + objectClass.getName());

The `getClass()` method returns a `Class` object representing the class of the object. You can use
the `getName()` method of the `Class` object to get the class name as a string.

2. Data members

In Java programming, when you're working with classes and objects, you'll be declaring data
members (also known as fields or attributes), naming variables, and using class members (methods
and variables). Here's a basic rundown:

2.1. Declaring Data Members (Fields):

Data members are variables that hold data associated with a class. They define the state of an
object. Here's an example of how you declare data members in a class:

public class MyClass {


// Data members (fields)
int myInt; // An integer variable
String myString; // A string variable
double myDouble; // A double variable

// Constructor (to initialize these fields)


public MyClass(int myInt, String myString, double myDouble) {
this.myInt = myInt;
this.myString = myString;
this.myDouble = myDouble;
}
}

2.2 Naming Variables:

When naming variables in Java, follow these conventions:

- Use meaningful names that reflect the purpose of the variable.

- Variable names are case-sensitive.

- Start variable names with a lowercase letter (camelCase).

- For constants, use ALL_CAPS_WITH_UNDERSCORES.

- Avoid using reserved words (like `int`, `String`, etc.) as variable names.

Example of good variable names:

int studentAge;
String userName;
final int MAX_VALUE = 100;

2.3. Using Class Members:

2.3.1. Using Data Members:

You can access data members using the dot (`.`) operator.

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass(10, "Hello", 3.14);

// Accessing data members


int num = obj.myInt;
String str = obj.myString;
double d = obj.myDouble;

System.out.println(num + " " + str + " " + d);


}
}

2.3.2. Using Methods:

Methods are functions defined within a class. You can call methods using the dot (`.`) operator.

public class MyClass {


int myInt;
String myString;

public void printValues() {


System.out.println("Integer: " + myInt);
System.out.println("String: " + myString);
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myInt = 10;
obj.myString = "Hello";

// Calling a method
obj.printValues();
}
}

Remember, for a method to be callable, it should be either `static` or you need an instance of the
class to call it.

3. Methods
In Java, using data members, invoking methods, passing arguments to a method, and calling
methods are essential aspects of object-oriented programming. Here's a detailed explanation:

3.1. Using Data Members:

Data members (also known as fields or attributes) are variables declared within a class. They define
the state of an object. To use data members, you first need to create an instance of the class.

public class MyClass {


int myInt; // Data member (field)
String myString; // Another data member

public void printValues() {


System.out.println("Integer: " + myInt);
System.out.println("String: " + myString);
}
}

3.2. Invoking Methods:

Methods are functions defined within a class. They can perform specific actions and may or may not
return a value.

public class MyClass {


int myInt;

public void printValue() {


System.out.println("Integer: " + myInt);
}
}

3.3. Passing Arguments to a Method:

Methods can accept parameters (also known as arguments) which allow you to pass data to the
method for processing.

public class MyClass {


public void printValue(int value) {
System.out.println("Value: " + value);
}
}
3.4. Calling a Method:

To call a method, you need an instance of the class (if the method is not `static`). Then, you use the
dot (`.`) operator followed by the method name and any necessary arguments.

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myInt = 10; // Setting data member value

// Invoking a method
obj.printValue(20); // Passing an argument to the method
}
}

3.5. Example Putting it All Together:

Here's an example that demonstrates using data members, invoking a method, passing an argument
to a method, and calling the method:

public class MyClass {


int myInt;
String myString;

public void printValues() {


System.out.println("Integer: " + myInt);
System.out.println("String: " + myString);
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myInt = 10;
obj.myString = "Hello";

// Invoking a method
obj.printValues(); // This will print both values
}
}

This example creates an instance of `MyClass`, sets values for its data members, and then calls the
`printValues` method which prints the values of `myInt` and `myString`.

4. Access Specifier & Modifiers

In Java, there are access modifiers and keywords that control the visibility and behavior of classes,
methods, and variables. Here's an explanation of the common access modifiers (`default`, `public`,
`private`, `protected`) and the keywords `static` and `final`:

4.1. Default (Package-Private)

- When no access modifier is specified, it's considered "default" or "package-private."

- It allows access to members (classes, methods, and variables) from within the same package but
not from outside the package.

- It's the narrowest scope in terms of visibility.

class MyClass { // Default access modifier


int myVar; // Default access modifier
}

4.2. public

- The `public` access modifier allows access from anywhere, including outside the package.

- It provides the widest scope and is used for classes, methods, and variables that are meant to be
accessible from anywhere in the program.

public class MyClass {


private int myVar;
private void myMethod() {
// Code here
}
}
4.3. private

- The `private` access modifier restricts access to members within the same class.

- It is often used to encapsulate and hide the implementation details.

public class MyClass {


private int myVar;
private void myMethod() {
// Code here
}
}

4.4. protected:

- The `protected` access modifier allows access within the same package and by subclasses (even
if they are in different packages).

- It's often used when you want to provide access to subclasses while limiting access to other
classes outside the package.

public class MyClass {


protected int myVar;
protected void myMethod() {
// Code here
}
}

4.5. static:

- The `static` keyword is used to create class-level members (methods and variables) that belong
to the class itself, not to instances of the class.

- You can access static members using the class name without creating an object.

public class MyClass {


public static int myStaticVar;
public static void myStaticMethod() {
// Code here
}
}

4.6. final:
- The `final` keyword is used to make a class, method, or variable unchangeable or unextendable.

- When applied to a class, it means the class cannot be subclassed.

- When applied to a method, it means the method cannot be overridden in subclasses.

- When applied to a variable, it means the variable's value cannot be changed once it's initialized.

public final class MyFinalClass {


public final int myFinalVar = 42;
public final void myFinalMethod() {
// Code here
}
}

5. Overloading

Method overloading and constructor overloading are two important concepts in Java that allow you
to define multiple methods or constructors with the same name in the same class but with different
parameters. The key to method or constructor overloading is that the method or constructor names
are the same, but they differ in the number or types of their parameters.

5.1. Method Overloading:

Method overloading allows you to define multiple methods in the same class with the same name
but different parameter lists. The methods can have different numbers or types of parameters.

Example of method overloading:

public class MathUtils {


// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}

// Method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}
}

In the example above, the `add` method is overloaded with different parameter lists based on the
number and types of parameters. The appropriate method is called based on the arguments
provided.

5.2. Constructor Overloading:

Constructor overloading is the same concept as method overloading, but it applies to class
constructors. You can have multiple constructors in the same class with the same name but
different parameter lists.

Example of constructor overloading:

public class Person {


private String name;
private int age;

// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}

// Constructor with name


public Person(String name) {
this.name = name;
this.age = 0;
}

// Constructor with name and age


public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

In the `Person` class, there are three constructors with different parameter lists. Depending on how
you create an instance of the `Person` class, the appropriate constructor is called to initialize the
object.
6. Java class library

In Java, there are several types of classes that serve different purposes and have specific
characteristics. Some of the common types of classes include:

6.1. Regular Class:

- A regular class is the most common type of class in Java.

- It can have fields, methods, and constructors.

- Regular classes are used to encapsulate data and behavior, and they can be instantiated to create
objects.

public class MyClass {


private int myField;
public MyClass(int value) {
myField = value;
}

public void doSomething() {


// Code here
}
}

6.2. Abstract Class:

- An abstract class is a class that cannot be instantiated on its own.

- It often contains abstract methods (methods without implementations) that must be


implemented by its subclasses.

- Abstract classes are used to define a common interface or behavior for a group of related classes.

public abstract class Shape {


abstract double area();
}

6.3. Interface:
- An interface is similar to an abstract class but can only define method signatures (no method
implementations) and constants (implicitly `public`, `static`, and `final`).

- Classes can implement multiple interfaces, enabling multiple inheritance of types.

- Interfaces are used to define contracts for classes that implement them.

public interface Drawable {


void draw();
}

6.4. Enum:

- An enum (short for "enumeration") is a special class used to represent a fixed set of constants.

- It's often used to define a list of named values, which are typically treated as symbolic names for
integer values.

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

6.5. Inner Class (Nested Class):

- An inner class is a class defined within another class.

- It can access the members of the outer class, and the outer class can access the members of the
inner class.

- Inner classes are used for encapsulation, organizing code, and creating relationships between
classes.

public class Outer {


private int outerField;

public class Inner {


public void doSomething() {
outerField = 42; // Accessing outer class's field
}
}
}
6.6. Static Nested Class:

- A static nested class is similar to an inner class, but it doesn't have a reference to an instance of
the outer class.

- It's often used when you want to group related classes together without a tight relationship to
the outer class.

public class Outer {


private static int outerField;

public static class StaticNested {


public void doSomething() {
outerField = 42; // Accessing outer class's static field
}
}
}

7. Decision making & loops

7.1. If-Then-Else:

- The `if-then-else` statement is used for conditional execution. It allows you to execute a block of
code if a certain condition is true, and another block of code if the condition is false.

int number = 10;


if (number > 5) {
System.out.println("Number is greater than 5.");
} else {
System.out.println("Number is not greater than 5.");
}

7.2. Switch Statement:

- The `switch` statement is used for multi-branching based on the value of an expression. It
provides a way to compare a single value with multiple possible values and execute different code
blocks accordingly.

int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
// ...
default:
System.out.println("Invalid day");
}

7.3. Ternary Operator (? :):

- The ternary conditional operator (`? :`) is a shorthand way to express an `if-then-else` statement
in a single line. It returns one of two values based on a given condition.

int number = 10;


String result = (number > 5) ? "Greater than 5" : "Not greater than 5";

7.4. While Loop:

- The `while` loop is used for executing a block of code repeatedly as long as a specified condition
is true.

int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}

7.5. Do-While Loop:

- The `do-while` loop is similar to the `while` loop but guarantees that the loop body is executed at
least once before checking the condition.

int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);

7.6. For Loop:


- The `for` loop is used for iterating over a range of values. It provides initialization, condition, and
iteration statements within the loop header.

for (int i = 0; i < 5; i++) {


System.out.println("Iteration: " + i);
}

7.7. For-Each Loop (Enhanced For Loop):

- The for-each loop is used to iterate through collections like arrays and lists without the need for
explicit indexing.

int[] numbers = {1, 2, 3, 4, 5};


for (int number : numbers) {
System.out.println("Number: " + number);
}

8. Array

In Java, you can create arrays to store collections of elements. There are one-dimensional arrays
(like lists) and two-dimensional arrays (like tables). Here's how you create them:

8.1 One-Dimensional Array:

A one-dimensional array is a list of elements of the same type.

8.1.1 Declaration and Initialization:

// Declaration and initialization in one step


int[] numbers = {1, 2, 3, 4, 5};
// Declaration and then initialization
int[] numbers = new int[5]; // Creates an array of size 5
numbers[0] = 1;
numbers[1] = 2;

8.2. Two-Dimensional Array:

A two-dimensional array is like a table with rows and columns.

8.2.1 Declaration and Initialization:


// Declaration and initialization in one step

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Declaration and then initialization


int[][] matrix = new int[3][3]; // Creates a 3x3 array
matrix[0][0] = 1;
matrix[0][1] = 2;

8.4. Creating an Array:

8.4.1 Declaration and Initialization:

// Declaration and initialization in one step


int[] numbers = {1, 2, 3, 4, 5};
// Declaration and then initialization
int[] numbers = new int[5]; // Creates an array of size 5
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

8.5. Creating a Two-Dimensional Array:

8.5.1 Declaration and Initialization:

// Declaration and initialization in one step


int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Declaration and then initialization


int[][] matrix = new int[3][3]; // Creates a 3x3 array
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;

8.6. Initializing an Array After Declaration:

You can also initialize an array after declaration, using a loop or by reading values from user input,
for example.

int[] numbers = new int[5];


for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}

int[][] matrix = new int[3][3];


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = i * 3 + j + 1;
}
}

Remember, arrays in Java are zero-indexed, which means the first element is at index 0. The length
of an array is accessed with the `length` property (e.g., `numbers.length`).

9. String

In Java, a string is an object that represents a sequence of characters. It's widely used for storing
and manipulating textual information. Here's how you can work with string arrays and some
common string methods:

9.1. String Array:

A string array is an array that holds references to string objects.

Declaration and Initialization:


// Declaration and initialization in one step
String[] names = {"Alice", "Bob", "Charlie"};

// Declaration and then initialization


String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";

9.2. Common String Methods:

1. length():

- Returns the length (number of characters) of the string.

String str = "Hello";


int length = str.length(); // length will be 5

2. charAt(int index):

- Returns the character at the specified index.

String str = "Hello";


char ch = str.charAt(0); // ch will be 'H'

3. substring(int beginIndex) and substring(int beginIndex, int endIndex):

- Returns a substring of the original string.

- The first version returns from `beginIndex` to the end of the string.

- The second version returns from `beginIndex` to `endIndex - 1`.

String str = "Hello World";


String sub1 = str.substring(6); // sub1 will be "World"
String sub2 = str.substring(0, 5); // sub2 will be "Hello"
4. indexOf(String str) and lastIndexOf(String str):

- Returns the index of the first (or last) occurrence of the specified substring.

- Returns -1 if the substring is not found.

String str = "Hello World";


int index1 = str.indexOf("o"); // index1 will be 4
int index2 = str.lastIndexOf("o"); // index2 will be 7

5. toUpperCase() and toLowerCase():

- Returns a new string with all characters converted to upper or lower case.

String str = "Hello";


String upperCase = str.toUpperCase(); // upperCase will be "HELLO"
String lowerCase = str.toLowerCase(); // lowerCase will be "hello"

6. equals(String another) and equalsIgnoreCase(String another):

- Compares two strings for equality.

- `equals` compares case-sensitive, while `equalsIgnoreCase` ignores case.

String str1 = "Hello";


String str2 = "hello";
boolean isEqual = str1.equals(str2); // isEqual will be false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); //
isEqualIgnoreCase will be true

7. startsWith(String prefix) and endsWith(String suffix):

- Checks if the string starts with or ends with the specified prefix or suffix.

String str = "Hello World";


boolean startsWith = str.startsWith("Hello"); // startsWith will be true
boolean endsWith = str.endsWith("World"); // endsWith will be true

8. split(String regex):

- Splits the string into an array of substrings based on the given regular expression.

String str = "Hello,World";


String[] parts = str.split(","); // parts will be {"Hello", "World"}

10. Inheritance:

In Java, inheritance is a fundamental concept of object-oriented programming that allows a class to


inherit properties and behaviors from another class. There are several types of inheritance in Java,
which include:

1. Single Inheritance:

- Single inheritance occurs when a class inherits from only one superclass.

- In Java, single inheritance is the default and the only type of class inheritance, as a class can
extend at most one other class.

Example:

class Parent {
// Parent class members
}

class Child extends Parent {


// Child class inherits from Parent
}

2. Multiple Inheritance through Interfaces:

- Although Java does not support multiple inheritance for classes (a class cannot extend more than
one class), it allows multiple inheritance of behavior through interfaces.

- A class can implement multiple interfaces, inheriting method signatures from each of them.
Example:

interface A {
void methodA();
}

interface B {
void methodB();
}

class MyClass implements A, B {


public void methodA() {
// Implementation for methodA
}

public void methodB() {


// Implementation for methodB
}
}

It's important to note that Java does not support multiple inheritance of state (fields). If a class
implements multiple interfaces, it only inherits the method signatures from those interfaces, not
the fields or state. This prevents the "diamond problem" and the complexities associated with
multiple inheritance of state that are seen in some other programming languages.

3. Hierarchical Inheritance:

- Hierarchical inheritance occurs when multiple classes inherit from a single superclass.

Example:

class Parent {
// Parent class members
}

class Child1 extends Parent {


// Child1 class inherits from Parent
}

class Child2 extends Parent {


// Child2 class inherits from Parent
}

4. Multilevel Inheritance:

- Multilevel inheritance occurs when a class inherits from another class, which in turn inherits
from another class, creating a chain or hierarchy of inheritance.

Example:

class Grandparent {
// Grandparent class members
}

class Parent extends Grandparent {


// Parent class inherits from Grandparent
}

class Child extends Parent {


// Child class inherits from Parent
}

5. Hybrid Inheritance (Not Supported by Java):

- Hybrid inheritance combines two or more types of inheritance. For example, it can include
multiple inheritance of classes and interfaces.

- Java doesn't support hybrid inheritance due to potential complexities and conflicts it may
introduce, such as the "diamond problem."

11. Interfaces

In Java, an interface is a reference type similar to a class, but it only contains method signatures
without implementations. It provides a contract that classes implementing the interface must
adhere to. Here's how you define, extend, and implement interfaces:

11.1 Defining an Interface:


To define an interface, you use the `interface` keyword followed by the interface name. Inside the
interface, you declare method signatures (without implementations).

interface MyInterface {
void method1();
int method2(String input);
}

In this example, `MyInterface` declares two method signatures: `method1()` and `method2()`.
Classes implementing this interface must provide implementations for these methods.

11.2 Extending Interfaces:

An interface can extend one or more other interfaces. This is similar to classes extending other
classes, but you use the `extends` keyword.

interface MyExtendedInterface extends MyInterface {


void method3();
}

In this example, `MyExtendedInterface` extends `MyInterface`, meaning it inherits the method


signatures from `MyInterface` (`method1()` and `method2()`), but it also declares its own method
`method3()`.

11.4 Implementing Interfaces:

To implement an interface in a class, you use the `implements` keyword.

class MyClass implements MyInterface {


public void method1() {
System.out.println("Method 1 implemented.");
}

public int method2(String input) {


System.out.println("Method 2 implemented with input: " + input);
return input.length();
}
}

In this example, `MyClass` implements `MyInterface`. It must provide implementations for both
`method1()` and `method2()`.
Example:

interface MyInterface {
void method1();
int method2(String input);
}

class MyClass implements MyInterface {


public void method1() {
System.out.println("Method 1 implemented.");
}

public int method2(String input) {


System.out.println("Method 2 implemented with input: " + input);
return input.length();
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.method1();
int result = obj.method2("Hello");
System.out.println("Result: " + result);
}
}

In this example, `MyClass` implements `MyInterface`. It provides implementations for both


`method1()` and `method2()`. When an object of `MyClass` is created, it can call these methods as
defined in the interface.

Interfaces provide a way to achieve abstraction and define contracts for classes to follow. They are
widely used in Java for achieving polymorphism and decoupling code.

You might also like