0% found this document useful (0 votes)
1 views

Java_Ignou

Uploaded by

test1.mehere
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Java_Ignou

Uploaded by

test1.mehere
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

MCS024 - OOP with

Java
Literals in Java
In Java, literals are fixed values that appear directly in the code. They
represent the actual values that are assigned to variables.

1.Integer literals: Represent whole numbers, like 10, 0, -5. They can be
expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base
2).
•Example: int x = 42;
2.Floating-point literals: Represent numbers with decimal points. They
default to double unless specified as float by adding an "f" or "F" at the end.
•Example: double pi = 3.14159;, float rate = 2.5f;

3.Character literals: Represent single characters enclosed in single quotes.


•Example: char grade = 'A';
Literals in Java
4.String literals: Represent sequences of characters enclosed in double
quotes.
•Example: String greeting = "Hello, world!";

5.Boolean literals: Can only be true or false.


•Example: boolean isActive = true;

6.Null literal: Represents a null reference.


•Example: String name = null;
Datatypes in Java
Primitive Data Types - These are the basic data types built into the language:
•byte: Size: 1 byte (8 bits)

•short: Size: 2 bytes (16 bits)

•int: Size: 4 bytes (32 bits)

•long: Size: 8 bytes (64 bits)

•float: Size: 4 bytes (32 bits)

•double: Size: 8 bytes (64 bits)

•char: Size: 2 bytes (16 bits)

•boolean: Size: (usually 1 bit)


Datatypes in Java
• Reference Data Types - These refer to objects and arrays and are more
complex types:
• Class types: Represent objects defined by a class.
Example: String name = "John";
• Array types: A collection of variables of the same type.
Example: int[] numbers = {1, 2, 3};
• Interface types: Used to define a contract for classes.
Example: List<Integer> list = new ArrayList<>();
Variables in Java
• In Java, variables are containers for storing data values. Every variable
in Java must have a type, which determines what kind of data it can
hold. Variables allow you to manipulate data throughout a program.
• Types of Variables in Java - Local Variables:
1. Declared inside methods, constructors, or blocks.
2. They are only accessible within the block or method where they are declared.
3. Must be initialized before use, as Java does not provide default values.
Example:
public void show() {
int num = 10; // Local variable
System.out.println(num);
}
Variables in Java
• Instance Variables (Non-static Fields):Declared in a class but outside
methods, constructors, or blocks.
• Each object of the class has its own copy of the instance variable.
• Default values are assigned (e.g., 0 for numbers, null for objects).

Example:
class Car {
String model; // Instance variable
int year;
}
Variables in Java
• Static Variables (Class Variables):Declared with the static keyword
inside a class but outside methods.
• Shared by all instances of the class, meaning they belong to the class
rather than individual objects.
• Initialized only once at the start of the program execution.
Example:
class Car {
static int numberOfCars; // Static variable
}
Operators in Java
• In Java, operators are symbols used to perform operations on
variables and values. They are essential for manipulating data and
performing calculations in a program.
• Arithmetic operators
Operators in Java
• Unary Operators - Unary operators operate on a single operand.
Operators in Java
• Assignment Operators - Assignment operators assign values to
variables.
Operators in Java
• Relational (Comparison) Operators - These operators compare two
values and return a boolean result (true or false).
Operators in Java
• Ternary Operator ?:
• The ternary operator is a concise way to evaluate a condition and
return one of two values.
Method overloading
• Method Overloading allows multiple methods to have the same name
but differ in the number or type of parameters.
• It’s a form of polymorphism (specifically, compile-time or static
polymorphism), where the compiler determines which method to invoke
based on the arguments passed.
• Example:
• // Calculator class with overloaded add() methods
class Calculator
{
// Method to add two numbers
public int add(int a, int b) {
return a + b;
}
Method overloading
// Method to add three numbers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add four numbers
public int add(int a, int b, int c, int d) {
return a + b + c + d;
}
}
Method Overloading
public class Main {
public static void main(String[] args) {
// Create an object of Calculator class
Calculator calc = new Calculator();
// Calling the overloaded add() methods
System.out.println("Sum of 2 numbers: " + calc.add(10,
20)); // Adds 2 numbers
System.out.println("Sum of 3 numbers: " + calc.add(10, 20, 30));
// Adds 3 numbers
System.out.println("Sum of 4 numbers: " + calc.add(10, 20, 30, 40));
// Adds 4 numbers
}
}
Method overriding
• Method overriding in Java is a feature that allows a subclass (child
class) to provide a specific implementation for a method that is
already defined in its superclass (parent class).
• When a method in a subclass has the same name, return type, and
parameters as a method in its superclass, the subclass's version of the
method "overrides" the superclass's version.
• Key Points of Method Overriding - Same Method Signature: The
method in the subclass must have the same name, return type, and
parameters as the method in the superclass.
• Example - Consider a scenario with a superclass Animal and a subclass
Dog, where both have a sound() method, but Dog overrides it to
provide a more specific sound.
Method overriding
// Superclass
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
Method overriding
public class Main {
public static void main(String[] args) {
// Creating an object of the superclass
Animal a = new Animal();
a.sound(); // Calls Animal's sound method

Dog d = new Dog();


dog.sound(); // Calls Dog's overridden sound method

Animal myDog = new Dog();


myDog.sound(); // Calls Dog's sound method due to polymorphism
}
}
Inheritance
• Inheritance in Java is a mechanism where a new class (subclass or child class)
acquires the properties and behaviors (fields and methods) of an existing
class (superclass or parent class).
• Key Points of Inheritance - Code Reusability: Inheritance promotes code
reuse. A subclass inherits fields and methods from its superclass, so you
don’t have to rewrite the same code.
• Example: The extends keyword is used for inheritance.
class Superclass {
// Superclass members
}

class Subclass extends Superclass {


// Subclass members
}
Inheritance
• Example:
// Superclass
class Animal {
String name;

// Constructor
public Animal(String name) {
this.name = name;
}

// Method
public void eat() {
System.out.println(name + " is eating.");
}
}
Inheritance
// Subclass

class Dog extends Animal {

// Constructor
public Dog(String name) {
super(name); // Calls the superclass (Animal) constructor
}

// Additional behavior
public void bark() {
System.out.println(name + " is barking.");
}
}
Inheritance
public class Main {

public static void main(String[] args) {


// Creating a Dog object
Dog myDog = new Dog("Buddy");

// Accessing inherited method


myDog.eat(); // Calls the eat() method from Animal

// Accessing subclass-specific method


myDog.bark(); // Calls the bark() method from Dog
}
}
Types of Inheritance in Java
• Single Inheritance:
One class inherits from another single class.
class A { }
class B extends A { }
• Multilevel Inheritance:
A class is derived from another class, which in turn is derived from
another class, forming a chain.
class A { }
class B extends A { }
class C extends B { }
• Hierarchical Inheritance:
Multiple classes inherit from a single superclass.
Types of Inheritance in Java
class A { }
class B extends A { }
class C extends A { }
• Multiple Inheritance (Through Interfaces):
A class implements multiple interfaces, combining behavior from
different sources.
interface X { }
interface Y { }
class Z implements X, Y { }
Abstract classes in Java
• Abstract classes in Java are special classes that cannot be instantiated
and are meant to serve as a base for other classes.
• They are designed to be extended by subclasses, providing a blueprint
for methods that must be implemented in the derived classes.
• Key Features of Abstract Classes
1.Cannot Be Instantiated:
1.Abstract classes cannot be used to create objects directly. They
are only used as a base class for other classes.
2.Can Contain Abstract Methods:
An abstract method is a method declared without a body ({}),
and its implementation is left to the subclasses. Subclasses must
override abstract methods unless they themselves are declared
abstract.
Abstract classes in Java
• Can Contain Concrete Methods: Abstract classes can also have
methods with implementations, which are inherited by subclasses.
• Can Contain Fields: Abstract classes can have fields (variables) just
like regular classes, and these can be accessed or inherited by
subclasses.
• Supports Inheritance: Abstract classes are meant to be extended by
other classes using the extends keyword.
• Constructor in Abstract Classes: Abstract classes can have
constructors, and these constructors are called when a subclass
object is created.
Abstract classes in Java
• Syntax of Abstract Classes
class ClassName
{ // Abstract method (no implementation)
abstract void methodName();
// Concrete method (with implementation)
void methodWithBody()
{
System.out.println("This is a concrete method.");
}
}
Abstract classes in Java
Example:
// Abstract class
abstract class Shape {
String color;
// Constructor
Shape(String color)
{
this.color = color;
}
// Abstract method
abstract double calculateArea();
// Concrete method
void displayColor()
{
System.out.println("Color: " + color);
}}
Abstract classes in Java
// Subclass
class Circle extends Shape
{
double radius;
Circle(String color, double radius)
{
super(color); // Call to the abstract class constructor
this.radius = radius;
}
@Override
double calculateArea()
{
return Math.PI * radius * radius;
}
}
Abstract classes in Java
// Subclass
class Rectangle extends Shape
{
double length, width;
Rectangle(String color, double length, double width)
{
super(color);
this.length = length;
this.width = width;
}
@Override
double calculateArea()
{
return length * width;
}}
Abstract classes in Java
public class Main
{
public static void main(String[] args)
{
Circle c = new Circle("Red", 5);
c.displayColor();
System.out.println("Area of Circle: " + c.calculateArea());
Rectangle r = new Rectangle("Blue", 4, 6);
r.displayColor();
System.out.println("Area of Rectangle: " + r.calculateArea());
}}
Exception Handling in Java
• Exception handling in Java is a mechanism that handles runtime
errors, ensuring the normal flow of the program.
• When an exception occurs, Java creates an exception object that
contains information about the error, and this object is thrown to a
part of the program that can handle it.
• Key Concepts of Exception Handling Exception:
• An exception is an event that disrupts the normal flow of a program.
Examples: Division by zero, accessing an invalid array index, file not
found, etc.
• Error: Errors are serious issues that applications should not try to
handle (e.g., OutOfMemoryError).
Exception Handling in Java
• Types of Exceptions:
• Checked Exceptions: Must be handled during compile-time (e.g., IOException,
SQLException).
• Unchecked Exceptions: Occur at runtime and are not checked during compile-
time (e.g., NullPointerException, ArithmeticException).
• Syntax:
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}
finally { // Code that will always execute }
Exception Handling in Java
public class Exception Example
{
public static void main(String[] args)
{
try
{
int a = 10, b = 0; int result = a / b; // Division by zero
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: Division by zero is not allowed.");
}
finally { System.out.println("Finally block executed.");
}}}
Exception Handling in Java
• Multiple Catch Blocks
public class MultiCatchExample
{ public static void main(String[] args)
{
try
{
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException }
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds.");
}
catch (Exception e)
{
System.out.println("An error occurred: " + e);
}}}
Exception Handling in Java
• Throwing Exceptions - Throw an exception using the throw keyword.
• Throws Keyword - The throws keyword declares exceptions that a
method may throw.
• Finally Block - The finally block executes whether or not an exception
occurs.
String Functions
Method Description Return
Type
charAt() Returns the character at the specified index (position) char
compareTo() Compares two strings lexicographically int
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of boolean
characters
endsWith() Checks whether a string ends with the specified boolean
character(s)
startsWith() Checks whether a string starts with specified characters boolean

substring() Returns a new string which is the substring of a String


specified string
toLowerCase() Converts a string to lower case letters
String Functions
Method Description Return Type

equals() Compares two strings. Returns true if the strings are boolean
equal, and false if not

getChars() Copies characters from a string to an array of chars void

join() Joins one or more strings with a specified separator String

length() Returns the length of a specified string int

replace() Searches a string for a specified value, and returns a new String
string where the specified values are replaced

replaceAll() Replaces each substring of this string that matches the String
given regular expression with the given replacement

split() Splits a string into an array of substrings String[]


File Operations in Java
• In Java, a File is an abstract data type.

• A named location used to store related information is known as


a File.

• There are several File Operations like creating a new File,


getting information about File, writing into a File, reading
from a File and deleting a File.

• Stream - A series of data is referred to as a stream.

• In Java, Stream is classified into two types,


• Byte Stream
• Character Stream.
File Operations in Java
Byte Stream is mainly involved with byte
data. A file handling process with a byte stream
is a process in which an input is provided and
executed with the byte data.

Character Stream is mainly involved with


character data. A file handling process with a
character stream is a process in which an input is
provided and executed with the character data.
File Class
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath( String Returns the absolute pathname of the file
)
length() Long Returns the size of the file in bytes
Applet Life Cycle in Java
• In Java, an applet is a special type of
program embedded in the web page to
generate dynamic content. Applet is a class
in Java.
• The applet life cycle can be defined as the
process of how the object is created, started,
stopped, and destroyed during the entire
execution of its application.
• It basically has five core methods namely
init(), start(), stop(), paint() and destroy().
Methods of Applet Life Cycle
Methods of Applet Life Cycle
init():
• The init() method is the first method to run that initializes the applet. It can
be invoked only once at the time of initialization.
• The web browser creates the initialized objects, i.e., the web browser (after
checking the security settings) runs the init() method within the applet.
start():
• The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every
time the browser is loaded or refreshed, the start() method is invoked.
• It is also invoked whenever the applet is maximized, restored, or moving
from one tab to another in the browser. It is in an inactive state until the
init() method is invoked.
stop():
• The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one
tab to another in the browser, the stop() method is invoked.
• When we go back to that page, the start() method is invoked again.
Methods of Applet Life Cycle
destroy():
• The destroy() method destroys the applet after its work
is done. It is invoked when the applet window is closed
or when the tab containing the webpage is closed.
• It removes the applet object from memory and is
executed only once. We cannot start the applet once it
is destroyed.
paint():
• The paint() method belongs to the Graphics class in
Java. It is used to draw shapes like circle, square,
trapezium, etc., in the applet.
• It is executed after the start() method and when the
browser or applet windows are resized.
Applet Life Cycle Working
• The Java plug-in software is responsible for managing the
life cycle of an applet.
• An applet is a Java application executed in any web
browser and works on the client-side. It doesn't have the
main() method because it runs in the browser. It is thus
created to be placed on an HTML page.
• The init(), start(), stop() and destroy() methods belongs to
the applet.Applet class.
• The paint() method belongs to the awt.Component class.
• In Java, if we want to make a class an Applet class, we
need to extend the Applet
• Whenever we create an applet, we are creating the
instance of the existing Applet class. And thus, we can use
all the methods of that class.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy