Oopjava Unit 1
Oopjava Unit 1
Neelima
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
• Reusability
• Delegation
• Genericity
We shall discuss these concepts in some detail in this section.
Class
A class is a data-type that has its own members i.e. data members and member functions. It
is the blueprint for an object in object oriented programming language. It is the basic
building block of object oriented programming in C++. The members of a class are accessed
in programming language by creating an instance of the class.
Some important properties of class are −
• Class is a user-defined data-type.
• A class contains members like data members and member functions.
• Data members are variables of the class.
• Member functions are the methods that are used to manipulate data members.
• Data members define the properties of the class whereas the member functions
define the behavior of the class.
A class can have multiple objects which have properties and behavior that in common for
all of them.
Objects
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program
must handle.
The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real
word entity. For example: consider an example named Amit; Amit is 25 years old and his
salary is 2500. The Amit may be represented in a computer program as an object. The data
part of the object would be (name: Amit, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrieve of data,
change age, change of salary). In general even any user –defined type-such as employee may
be used. In the Amit object the name, age and salary are called attributes of the object
The figure shows two notations that are popularly used in object-oriented analysis and
design.
The wrapping up of data and functions into a single unit (called class) is known
as encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class
can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding
or information hiding.
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and functions to operate
on these attributes. They encapsulate all the essential properties of the objects that are to
be created. The attributes are sometimes called data members because they hold
information. The functions that operate on these data are sometimes called methods or
member functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types
(ADT).
Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. For example,
the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The
principle behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in Figure.
In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined features
of both the classes. The real appeal and power of the inheritance mechanism is that it allows
the programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduce any undesirable side-effects into the rest
of the classes
Note that each sub-class defines only those features that are unique to it. Without
the use of classification, each class would have to explicitly include all of its features.
Polymorphism
The name defines polymorphism is multiple forms, which means polymorphism is
the ability of object oriented programming to do some work using multiple forms. The
behavior of the method is dependent on the type or the situation in which the method is
[Link] process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Let’s take a real life example, a person can have more than one behavior depending
upon the situation like a woman a mother, manager and a daughter and this define her
behavior. This is from where the concept of polymorphism came from.
In C++ programming language, polymorphism is achieved using two ways. They are
operator overloading and function overloading.
Operator overloading In operator overloading and operator can have multiple behavior
in different instances of usage.
Function overloading Functions with the same name that can do multiple types based on
some condition.
Figure illustrates that a single function name can be used to handle different number
and different types of arguments. This is something similar to a particular word having
several different meanings depending on the context. Using a single function name to
perform different types of tasks is known as function overloading.
Figure: Polymorphism
Dynamic Binding
Consider the procedure “draw” in above figure. By inheritance, every object will
have this procedure. Its algorithm is, however, unique to each object and so the draw
procedure will be redefined in each class that defines the object. At run-time, the code
matching the object under current reference will be called.
Message Passing
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
A message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and the information to be sent. Example:
Objects have a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.
Reusability
Figure: Reusability
Delegation
In OOP, two classes can be joined in two ways: (a) Inheritance, (b) Delegation. Both
these ways provide reusability of the class.
In Inheritance one class can be derived from the other class. The relationship between these
two classes is called as kind of relationship. For example if class Y is derived from class X,
then class Y is known as kind of X. Figure 1.8 (a) explains this point.
Figure: 1.8 Relationships between two classes: (a) Kind of relationship (Inheritance) (b)
has a relationship (Delegation)
The second type of relationship is has a relationship. When object of one class is
used as data member in the other class, such composition of objects is known as delegation.
As shown in Figure 1.8(b) class C has two data members. These two data members are
objects of class A and B, such relationship between the classes in known as has a
relationship.
Genericity
The software components of a program have more than one version depending on
the data types of arguments. This feature allows declaration of variables without specifying
exact data type. The compiler identifies the data type at run time. The programmer can
create a function that can be used for any type of data. The template feature in C++ allows
generic programming.
Procedural Programming:
- Focuses on functions or procedures to operate on data.
- Functions are separate from data and are called to perform operations.
- Does not support encapsulation, inheritance, or polymorphism inherently.
Object-Oriented Programming:
- Focuses on objects that contain both data and methods to operate on that data.
- Promotes encapsulation, which bundles data and methods together.
- Supports inheritance and polymorphism, allowing for more flexible and reusable code.
Object-Oriented Programming Procedural Programming
Feature
(OOP) (POP)
Procedure or function
Basic Unit Object (combines data and methods)
(operates on data)
Data and
Encapsulated within objects Separate from functions
Functions
Focus On objects and interactions On procedures and algorithms
Advantages of OOP
Object oriented technology provides many advantages to the programmer and the user.
This technology solves many problems related to software development, provides
improved quality and low cost software.
1. Object oriented programs can be comfortably upgraded.
2. Using inheritance, we can eliminate redundant program code and continue the use of
previously defined classes.
3. The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.
4. The encapsulation feature provided by OOP languages allows programmer to define the
class with many functions and characteristics and only few functions are exposed to the
user.
5. All object oriented programming languages allows creating extended and reusable parts
of programs.
6. Object oriented programming changes the way of thinking of a programmer. This
results in rapid development of new software in a short time.
7. Objects communicate with each other and pass messages.
Applications of OOP
OOP is widely used in various fields of software development due to its flexibility and
modularity. Some common applications include:
1. Graphical User Interface (GUI) Applications: OOP languages like Java and C# are
commonly used to develop GUI applications.
2. Web Development: OOP principles are used in server-side languages like Java, C#, and
PHP to create dynamic web applications.
3. Mobile Development: OOP languages such as Swift for iOS development and
Java/Kotlin for Android development are widely used.
4. Game Development: OOP is fundamental in game development for managing game
entities, behaviors, and interactions.
5. Simulation and Modeling: OOP languages like Python and C++ are used to create
complex simulations and models.
6. Enterprise Applications: OOP languages are used to build large-scale enterprise
applications due to their modularity and reusability.
Introduction to JAVA
History of JAVA
Early Development
• 1991: Java's development began at Sun Microsystems, led by James Gosling and
team, under the project name "The Green Project."
• 1992: The language was initially called Oak, developed for a home-entertainment
controller device.
Transition to Java
• 1994: The team shifted focus to web technology, adapting Oak for web applets.
• 1995: Oak was renamed Java, and Java 1.0 was officially released.
• 1996: Java Development Kit (JDK) 1.0 was released, promoting the "Write Once, Run
Anywhere" (WORA) philosophy.
• 1998: Java 2 (J2SE 1.2) introduced significant improvements and split into Standard
(J2SE), Enterprise (J2EE), and Micro (J2ME) editions.
Later Developments
• 2004: Java 5.0 (J2SE 5.0) added generics, metadata, and enhanced loops.
• 2006: Sun Microsystems made Java open source.
• 2009: Oracle Corporation acquired Sun Microsystems and Java.
Modern Era
• 2014: Java 8 introduced lambda expressions, the Stream API, and the new Date and
Time API.
• 2017: Java 9 introduced the module system (Project Jigsaw).
• 2018: Oracle adopted a six-month release cadence, with Java 11 designated as a
Long-Term Support (LTS) version.
• 2021: Java 17 was released as the next LTS version.
Features of Java:
Java is a powerful and versatile programming language that provides numerous features to
developers. Here are some of the key features of Java:
Simple: Java has a clean and easy-to-understand syntax, which makes it easy to learn and
use. It eliminates many complex features found in other languages, such as explicit pointers
and operator overloading.
Platform-Independent: Java code is compiled into bytecode, which can be executed on any
system with a Java Virtual Machine (JVM). This "write once, run anywhere" capability
makes Java highly portable.
Secure: Java provides a secure environment by offering multiple security features such as
bytecode verification, sandboxing, and the security manager, which help in defending
against malicious code and vulnerabilities.
Robust: Java emphasizes reliability with features such as strong memory management,
exception handling, and garbage collection. It also has a strong type-checking mechanism
that helps in detecting errors at compile time.
Multithreaded: Java has built-in support for multithreading, allowing multiple threads to
run concurrently. This feature helps in developing high-performance, interactive, and
responsive applications.
Distributed: Java has a rich set of APIs and tools for developing distributed applications. It
supports Remote Method Invocation (RMI) and Enterprise JavaBeans (EJB) to create
distributed systems.
Dynamic: Java is capable of dynamically linking new class libraries, methods, and objects.
It supports dynamic loading of classes, which allows the code to be highly flexible and
extensible.
Interpreted: Java bytecode is interpreted by the JVM. This allows for platform
independence and enables the code to be executed on any system that has a JVM.
Portable: Java eliminates the platform-specific aspects of its language, making the
compiled code portable. It achieves this by using a standardized, machine-independent
bytecode and a runtime environment.
Structure of JAVA
1. Package Declaration: Defines the package name which groups related classes
together.
package [Link];
import [Link];
[Link]("Hello, World!");
package [Link];
import [Link];
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name + "!");
}}
Java Development Kit (JDK)
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment (JRE),
an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), and other tools needed for Java development. Here's an overview of
its main components and functionalities:
1. byte
o Size: 8-bit
o Range: -128 to 127
2. short
o Size: 16-bit
o Range: -32,768 to 32,767
3. int
o Size: 32-bit
o Range: -2^31 to 2^31-1
4. long
o Size: 64-bit
o Range: -2^63 to 2^63-1
5. float
Size: 32-bit floating point
o
Range: approximately ±3.40282347E+38F (6-7 significant decimal digits)
o
6. double
o Size: 64-bit floating point
o Range: approximately ±1.79769313486231570E+308 (15 significant
decimal digits)
7. char
o Size: 16-bit Unicode character
o Range: '\u0000' to '\uffff'
8. boolean
o Size: Not precisely defined
o Values: true or false
• Classes
• Interfaces
• Arrays
• Strings
JAVA Tokens
Java tokens are the smallest elements of a program that are meaningful to the compiler.
They include:
1. Keywords
o Reserved words that have a predefined meaning in the language. Example:
class, public, static, void, etc.
2. Identifiers
o Names given to classes, methods, variables, etc.
o Example: main, args, Scanner, etc.
3. Literals
o Constant values assigned to variables.
o Example: 123, 3.14, 'A', "Hello", true, false, etc.
4. Operators
o Symbols that perform operations on variables and values.
o Example: +, -, *, /, =, ==, etc.
5. Separators
o Symbols used to separate statements and blocks of code.
o Example: ;, ,, (), {}, [], etc.
Java Operators
Operators in Java are special symbols that perform specific operations on one, two, or three
operands and then return a result. Java operators can be classified into the following types:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Bitwise Operators
7. Ternary Operator
8. Instanceof Operator
1. Arithmetic Operators
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulus (%)
int a = 5;
a++; // Example: a is now 6
3. Assignment Operators
int a = 5;
a += 3; // Example: a is now 8
4. Relational Operators
• Equal to (==)
• Not Equal to (!=)
• Greater than (>)
• Less than (<)
• Greater than or Equal to (>=)
• Less than or Equal to (<=)
int result = 5 & 3; // Example: result is 1 (binary 0101 & 0011 = 0001)
7. Ternary Operator
• Conditional (? :)
• Instanceof (instanceof)
Control statements in Java control the flow of execution of the program. They can be
categorized into decision-making statements, looping statements, and jump statements.
1. Decision-Making Statements
if Statement
The if statement evaluates a condition. If the condition is true, the block of code inside the
if statement is executed.
Syntax:
if (condition) {
// code to be executed if condition is true
}
if-else Statement
The if-else statement evaluates a condition. If the condition is true, the block of code
inside the if statement is executed. Otherwise, the block of code inside the else statement
is executed.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
else-if Ladder
The else-if ladder allows you to check multiple conditions. If one condition is true, the
corresponding block of code is executed.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
switch Statement
The switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
default:
// code to be executed if expression doesn't match any case
}
2. Looping Statements
for Loop
The for loop is used to execute a block of code a specific number of times. It is typically
used when the number of iterations is known beforehand.
Syntax:
The while loop is used to execute a block of code as long as a specified condition is true.
The condition is checked before the loop body is executed.
Syntax:
while (condition) {
// code to be executed
}
do-while Loop
The do-while loop is similar to the while loop, but the condition is checked after the loop
body is executed. This ensures that the loop body is executed at least once.
Syntax:
do {
// code to be executed
} while (condition);
3. Jump Statements
break Statement
The break statement is used to exit from a loop or switch statement prematurely.
Syntax:
break;
• continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next
iteration.
Syntax:
continue;
• return Statement
The return statement is used to exit from a method and optionally return a value.
Syntax:
Example Program
Here’s an example Java program demonstrating the use of various control statements:
package [Link];
import [Link];
// if-else statement
[Link]("Enter a number: ");
int number = [Link]();
if (number > 0) {
[Link]("Number is positive.");
} else {
[Link]("Number is negative or zero.");
}
// for loop
[Link]("Counting to 5:");
for (int i = 1; i <= 5; i++) {
[Link](i);
}
// while loop
[Link]("Enter a positive number to countdown from:");
int countdown = [Link]();
while (countdown > 0) {
[Link](countdown);
countdown--;
}
// do-while loop
[Link]("This will run at least once:");
int doWhileCounter = -1;
do {
[Link]("do-while loop iteration");
} while (doWhileCounter > 0);
// switch statement
[Link]("Enter a grade (A-F): ");
char grade = [Link]().charAt(0);
switch (grade) {
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Good job!");
break;
case 'C':
[Link]("Well done!");
break;
case 'D':
[Link]("You passed.");
break;
case 'F':
[Link]("Better try again.");
break;
default:
[Link]("Invalid grade.");
}
// break statement
[Link]("Using break in a loop:");
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
[Link](i);
}
// continue statement
[Link]("Using continue in a loop:");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
[Link](i);
}
// return statement
[Link]("Method with return statement:");
printMessage();
}
Class:
• A class is a blueprint or template from which objects are created. It defines a type by
bundling data and methods that work on the data into one single unit.
• A class defines the properties (attributes) and behaviors (methods) that the objects
created from the class can have.
Example:
class Car {
// attributes
String color;
String model;
// behavior or method
void drive() {
[Link]("Car is driving");
}
}
Object:
Example:
Class Declaration
class Student {
// Attributes (Fields)
String name;
int age;
// Methods
void study() {
[Link](name + " is studying.");
}
}
Explanation:
a. Class Name
Definition: The class name is a unique identifier for the class. It should be descriptive
enough to convey the purpose of the class. For instance, a class that represents a bank
account might be named BankAccount, while a class representing an employee might be
named Employee.
Naming Convention:
• PascalCase is the convention used in Java for class names. This means each word in
the name begins with an uppercase letter, and there are no spaces or underscores
between words.
• Examples: Student, LibraryBook, CustomerOrder.
b. Attributes/Fields
Definition: Attributes, also known as fields or member variables, represent the state or
properties of an object. They are variables defined within a class, and each object of the
class has its own copy of these fields (unless they are static).
Types of Fields:
• Instance Variables: These are fields that belong to each instance of the class. For
example, each Student object might have its own name and age.
• Static Variables: These are shared across all instances of the class. If a variable is
declared as static, all instances of the class share the same value of that variable.
Example:
class Car {
String model; // Instance variable
String color;
static int numberOfWheels = 4; // Static variable
}
Explanation: Here, model and color are instance variables, while numberOfWheels is a
static variable shared by all Car objects.
c. Methods
Definition: Methods in a class define the behavior or actions that objects of the class can
perform. Methods are functions that are defined inside the class and can operate on the
class's fields.
Method Declaration:
• A method typically includes a return type, a method name, parentheses that may
enclose parameters, and a body enclosed in curly braces.
• The method name should follow the camelCase naming convention, where the first
word is lowercase, and subsequent words start with an uppercase letter.
Example:
class Student {
String name;
int age;
age = newAge;
}
}
Explanation: The Student class has two methods: displayDetails() to print the student's
details and setAge() to update the student's age.
Class Members
Fields (Attributes):
• Fields are variables defined within a class that hold the data for an object.
Example:
class Student {
String name;
int age;
}
Methods:
• Methods define the behavior of an object. They are functions that operate on the
fields of the class.
Example:
class Student {
String name;
int age;
void study() {
[Link](name + " is studying");
}
}
Constructors:
Example:
class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
}
In Java, objects are instances of classes. When you declare a class, you're essentially defining
a new data type. To use this class, you need to create objects from it. This process involves
using the new keyword and the class constructor.
1. Creating Objects
Syntax:
• The syntax for creating an object involves specifying the class name, followed by a
reference variable, and then using the new keyword to call the constructor of the
class.
Example:
Explanation:
Once an object is created, you can interact with its attributes (fields) and behaviors
(methods) using the dot . operator. The dot operator allows you to access the fields and
methods of the object.
Accessing Fields:
• Fields (attributes) of an object store data related to that particular instance. You can
read or modify these fields using the dot operator.
Example:
Explanation:
• [Link] = "Alice"; changes the name field of the student1 object to "Alice".
Accessing Methods:
• Methods define the behavior of an object. They can be invoked using the dot
operator.
Example:
Explanation:
• [Link](); calls the study() method of the student1 object. This method might
contain code to print a message like "Alice is studying."
Access Control for Class Members
Java provides four levels of access control for class members (fields and methods) using
access modifiers: private, default (no modifier), protected, and public. These modifiers
determine the visibility of class members from different parts of the program.
Visibility:
• The private modifier restricts access to the class members within the class itself.
This means that no other class, even within the same package, can directly access
private members.
• It's the most restrictive access level.
Usage:
• Private members are often used for encapsulation, hiding the internal details of a
class from other classes.
• To allow controlled access to these private members, you typically provide public
getter and setter methods.
Example:
class Student {
private String name; // Only accessible within the Student class
private int age;
// Constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
Explanation: In this example, name and age are private, so they cannot be accessed directly
from outside the Student class. However, the public methods getName() and setName()
provide controlled access to the name field.
Visibility:
• If no access modifier is specified, the member has default access (also known as
package-private).
• This means the member is accessible to any other class within the same package but
not to classes in other packages.
Usage:
• Use default access when you want to allow access to class members within the same
package but prevent access from outside the package.
Example:
class Student {
String name; // Accessible within the same package
int age;
}
Explanation: Here, name and age are accessible to all classes in the same package as
Student. However, if you try to access them from a class in a different package, it will result
in a compile-time error.
Visibility:
• The protected modifier allows access within the same package and to subclasses in
other packages.
• It provides a middle ground between default (package-private) and public access.
Usage:
• Protected members are often used in scenarios where you want to allow subclasses
to access certain members but still want to restrict access to the rest of the program.
Example:
class Student {
protected int rollNumber; // Accessible within the same package and by subclasses
void displayRollNumber() {
[Link]("Roll Number: " + rollNumber);
}
}
Visibility:
• The public modifier allows access from any other class in any package. Public
members are universally accessible throughout the entire program.
Usage:
• Use public access for methods or fields that you want to expose to all other parts of
the program.
• Common examples include public methods like main() and fields or methods
intended to be part of a class’s API.
Example:
class Student {
public String college; // Accessible from anywhere in the program
public Student(String college) {
[Link] = college;
}
public void displayCollege() {
[Link]("College: " + college);
}
}
The college field and the displayCollege() method are public, meaning any class from any
package can access them directly.
private ✔
Default ✔ ✔
protected ✔ ✔ ✔
public ✔ ✔ ✔ ✔
Static Variables
Static variables, also known as class variables, are variables that are shared among all
instances of a class. Unlike instance variables, which are unique to each object, static
variables have a single memory location, and all instances of the class refer to this same
memory location.
1. Shared Across Instances: All instances of the class share the same static variable.
Changing the value of a static variable in one instance affects all other instances.
2. Memory Allocation: Static variables are allocated memory only once, at the time of
class loading, not when objects are created. They remain in memory as long as the
class is loaded, which can be for the duration of the program.
3. Access: Static variables can be accessed directly using the class name, without
needing to create an instance of the class.
class Student {
static int totalStudents = 0; // Static variable
String name;
Explanation: In this example, totalStudents is a static variable that increments each time a
new Student object is created. Since it's static, it counts the total number of Student
instances, and all instances share this count.
Static Methods
Static methods are methods that belong to the class rather than to any specific instance of
the class. They can be called without creating an instance of the class.
1. No Instance Required: Static methods can be invoked directly using the class name,
without needing to instantiate the class.
2. Access to Static Members: Static methods can directly access other static variables
and static methods. However, they cannot directly access instance variables or
instance methods because static methods do not operate on instances.
3. Use Cases: Static methods are often used for operations that don't require any data
from an instance of the class. Common examples include utility or helper methods
like [Link]() or [Link]().
class Student {
static int totalStudents = 0;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John");
Student s2 = new Student("Jane");
Scanner Class
• The Scanner class is part of the [Link] package and is widely used for obtaining
input of primitive types like int, double, float, etc., as well as strings.
• It provides a convenient way to read user input during runtime from different input
sources, such as the keyboard, files, and streams.
• To use the Scanner class, you first need to import it from the [Link] package.
• Create an instance of the Scanner class, usually passing [Link] as an argument to
read input from the standard input stream (keyboard).
import [Link];
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the keyboard
Scanner scanner = new Scanner([Link]);
Explanation:
• new Scanner([Link]): Creates a Scanner object that reads from the keyboard.
• nextLine(): Reads the entire line of input, including spaces, until the user presses
Enter.
The Scanner class provides various methods to read different types of data:
import [Link];
// Reading an integer
[Link]("Enter your age: ");
int age = [Link]();
// Reading a double
[Link]("Enter your height in meters: ");
double height = [Link]();
// Reading a boolean
[Link]("Are you a student (true/false): ");
boolean isStudent = [Link]();
Command line arguments are values passed to a Java program at the time of execution.
These values are supplied after the program's name when running the program from the
command line.
o The main method in Java is defined as public static void main(String[] args). The args
parameter is an array of String objects that stores the command line arguments.
o If the user provides multiple arguments, they are stored as separate elements in the
args array, with args[0] representing the first argument, args[1] the second, and so
on.
Explanation:
o [Link]: This checks the length of the args array, which tells you how many
arguments were passed.
o args[0]: This accesses the first argument in the array. If at least one argument is
passed, it prints the first argument; otherwise, it prints a message saying no
arguments were provided.
3. How to Pass Command Line Arguments
To run a Java program with command line arguments, you use the following syntax in the
command line (or terminal):
Example:
In this example:
Expected Output:
If you run java Main without any arguments, the output would be:
No arguments provided.
Method Overloading
Definition:
• Method overloading allows a class to have multiple methods with the same name,
but with different parameter lists.
• The parameters can differ in the number of parameters, their types, or both.
• The correct method to be executed is determined by the method signature (the
method name and parameter list).
Example:
class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}
Benefits:
• Improves code readability and usability by allowing the same method name to be
used for similar operations.
• Reduces the need for method names with different names for different tasks, making
the API easier to understand and use.
CONSTRUCTORS
In Java, a constructor is a special method that is used to initialize objects. The constructor
is called when an object of a class is created. It has the same name as the class and does not
have a return type. Constructors can be broadly categorized into the following types:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
Let’s dive into each of these with detailed explanations and examples.
Default Constructor
• Has no parameters.
• Initializes object fields with their default values (e.g., 0 for numeric types, null for
objects, false for boolean).
• Allows the creation of objects even if no custom constructor is provided.
Example:
class Car {
String model;
int year;
// Default constructor
Car() {
model = "Unknown";
year = 0;
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
In this example, when car1 is created, the default constructor initializes the model to
"Unknown" and year to 0.
Parameterized Constructor
Example:
class Car {
String model;
int year;
// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
In this example, when car2 is created, the parameterized constructor initializes the model
to "Tesla" and year to 2024.
Copy Constructor
A copy constructor is a special type of constructor used to create a new object as a copy of
an existing object. Java doesn’t provide a built-in copy constructor, but you can define one
Example:
class Car {
String model;
int year;
// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
// Copy constructor
Car(Car car) {
[Link] = [Link];
[Link] = [Link];
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car3 = new Car("Audi", 2022); // Calls the parameterized constructor
Car car4 = new Car(car3); // Calls the copy constructor
[Link](); // Output: Model: Audi, Year: 2022
}
}
Here, car4 is created as a copy of car3 using the copy constructor, and they have the same
values for model and year.
Constructor Overloading
Constructor overloading in Java allows a class to have more than one constructor with
different parameter lists. This enables the creation of objects in different ways.
Example:
class Car {
String model;
int year;
// Default constructor
Car() {
model = "Unknown";
year = 0;
}
// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
// Another parameterized constructor with only one parameter
Car(String m) {
model = m;
year = 2021; // Default year if not specified
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
In this example, the Car class has three constructors: a default constructor, a two-parameter
constructor, and a one-parameter constructor, demonstrating constructor overloading.
this Keyword
The this keyword in Java is a reference to the current object. It is used to refer to instance
variables, invoke methods, or constructors of the current class.
Example:
class Car {
String model;
int year;
// Parameterized constructor
Car(String model, int year) {
// Using 'this' keyword to refer to instance variables
[Link] = model;
[Link] = year;
}
void display() {
[Link]("Model: " + [Link] + ", Year: " + [Link]);
}
}
public class Main {
public static void main(String[] args) {
Car car8 = new Car("Volvo", 2020); // Calls the parameterized constructor
[Link](); // Output: Model: Volvo, Year: 2020
Car car9 = new Car("Ford"); // Calls the constructor that uses 'this'
[Link](); // Output: Model: Ford, Year: 2021
}
}
In this example:
• The this keyword is used to differentiate between instance variables ([Link] and
[Link]) and constructor parameters (model and year).
• The second constructor demonstrates constructor chaining by invoking another
constructor using this().
***********