0% found this document useful (0 votes)
46 views56 pages

Java Unit - 1 Notes

The document outlines a syllabus for an Object-Oriented Programming course using Java, covering fundamental concepts such as data types, classes, and methods. It provides an overview of Java's history, features, and applications, emphasizing its object-oriented nature and platform independence. Additionally, it details Java programming basics, including variable types, data types, and the structure of a Java program.

Uploaded by

Mgm Mallikarjun
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)
46 views56 pages

Java Unit - 1 Notes

The document outlines a syllabus for an Object-Oriented Programming course using Java, covering fundamental concepts such as data types, classes, and methods. It provides an overview of Java's history, features, and applications, emphasizing its object-oriented nature and platform independence. Additionally, it details Java programming basics, including variable types, data types, and the structure of a Java program.

Uploaded by

Mgm Mallikarjun
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

Object Oriented with java programming

Syllabus
Unit – I

Unit No. Course Content Hours


Introduction to Java: OOPs concepts, Basics of Java
programming, Data types, Variables, Operators, Control
structures including selection ,Looping, Arrays in java.

UNIT - 1 13
Objects and Classes: Basics of objects and classes in java, Methods
and objects, Instance of operator, Visibility modifiers, Method
Overloading, Constructors, Static Members

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 1
Object Oriented with java programming

Introduction to Java:
What is java?
 Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle Corporation).It was first released in 1995 and
has since become one of the most popular programming languages in the world,
known for its platform independence, versatility, and wide range of applications.

 Java was developed by a team of engineers led by James Gosling at Sun Microsystems
in the early 1990s. The project was initially called "Oak" but was later renamed "Java"
to avoid trademark issues. The official release of Java 1.0 occurred in 1995. Over the
years, Java has evolved with contributions from various individuals and
organizations, and it is now maintained by Oracle Corporation, which acquired Sun
Microsystems in 2010. James Gosling is often credited as the "father of Java" for his
key role in its creation.

 3 billion mobile phones, 125 million TV sets, and 1 billion computers run Java
programming language.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 2
Object Oriented with java programming

Applications of JAVA (Java is used in many areas)

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Key Features of java:

1. "Write once, run anywhere" philosophy, meaning that Java programs can be
compiled into byte code, which can then be executed on any platform that has a
Java Virtual Machine (JVM) installed.

2. Easy to Learn: Java is designed to be simple and easy to understand, making it


accessible for beginners to learn and use.

3. Object-Oriented: Java organizes code into objects, which are like building blocks
that represent real-world things. This makes it easier to manage and reuse code, like
Lego pieces fitting together.

4. Platform independent: Developer/users can run java code in any platform.

5. Safe and Secure: Java has built-in features to protect your code and data from
security threats, like viruses or hackers. It's like having a security guard watching over
your program.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 3
Object Oriented with java programming

6. Robust and Reliable: Java is designed to be strong and dependable, with features
that help prevent crashes and errors. It's like having a sturdy shield that protects your
program from breaking.

7. Lots of Tools and Libraries: Java comes with a lot of helpful tools and pre-made
code (libraries) that you can use to build your programs faster. It's like having a
toolbox full of handy gadgets for your project.

8. Fast Performance: While Java may not be the fastest language, it's still pretty speedy,
especially with modern improvements. It's like a car that may not be a race car, but
it still gets you where you need to go efficiently.

9. Works with Multiple Tasks: Java can handle doing multiple things at once
(multithreading), which is useful for tasks like downloading files while playing music.
It's like being able to cook dinner while chatting with a friend on the phone.

10. Interpreted:

Java uses a combination of compilation and interpretation.

1. Compilation: When you write Java code, you first compile it using the Java compiler
(javac). The compiler translates your human-readable Java code into an intermediate
form called bytecode. Bytecode is not machine code but rather a set of instructions that
can be executed by the Java Virtual Machine (JVM).

2. Interpretation: The JVM then interprets the bytecode and executes it on the target
platform. The JVM is responsible for translating bytecode instructions into machine
code that the underlying hardware can understand. This process happens dynamically at
runtime.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 4
Object Oriented with java programming

Object Oriented Programming (OOPs) Concept in Java


Object-Oriented:
Java organizes code into objects, which are like building blocks that represent real-world
things. This makes it easier to manage and reuse code.

1. Object :
It is a basic unit of Object Oriented Programming and represents the real life entities.

An object consists of :

1. State : It is represented by attributes of an object. It also reflects the properties of


an object.
2. Behavior : It is represented by methods of an object. It also reflects the response
of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact
with other objects.
Example of an object : dog,car,person.

2. Class:
 A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
 Class is “blueprint”

3. Inheritance
 Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviours of a parent object. It is an important part of OOPs (Object
Oriented programming system).
 The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes.

4. Polymorphism (Many Forms)


 Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

5. Abstraction
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details.
Ex: A car is viewed as a car rather than its individual components.

6. Encapsulations
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 5
Object Oriented with java programming

Basics of java programming:


Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a
wide variety of applications. So, before diving in depth, it is necessary to understand
the basic structure of Java program in detail.

Documentation Section:
This typically refers to the comments and documentation within a Java file that
describe the purpose, usage, and behavior of the code. It includes Javadoc comments
which are used to generate documentation. comments are: single line comment (//)
multiline comments(/* */)

Package Declaration:
Every Java class belongs to a package, which is declared at the beginning of the file.
Packages help organize classes into meaningful groups and prevent naming conflicts.

Import Statements:
Java allows classes to import other classes or entire packages to use their
functionalities without fully qualifying their names. Import statements are used to
include these external classes or packages.

Interface Section:
In Java, an interface is a reference type that defines a set of abstract methods. It
specifies a contract that implementing classes must adhere to, without providing any
implementation details.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 6
Object Oriented with java programming

Class Definition:
In Java, a class is a blueprint for creating objects. It encapsulates data (in the form of
fields or variables) and behavior (in the form of methods or functions) into a single
unit.

Class Variables and Variables:


Variables in Java can be declared at various levels: as class variables (static variables),
which belong to the class itself, or as instance variables, which belong to individual
objects. Variables can also be declared within methods, known as local variables.

Main Method Class:


In Java applications, the main method serves as the entry point for execution. It is a
special method that is called when the program starts and is typically declared within
a class.

Methods and Behaviours:


Methods in Java are blocks of code that perform specific tasks. They encapsulate
behaviours and functionalities that can be invoked by other parts of the program.
Methods can have parameters and may return values. Behaviours refer to the actions
or tasks performed by these methods.

JDK, JRE, JVM:


1. Java JDK (Java Development Kit):
 The Java Development Kit is a software development kit used by Java developers to
develop Java applications. It contains tools such as the Java compiler (javac), the Java
interpreter (java), and other development tools like debugger and documentation
generator.

2. Java JRE (Java Runtime Environment):


 The Java Runtime Environment is a software package that provides the necessary
runtime environment for executing Java applications. It includes the Java Virtual
Machine (JVM), class libraries, and other supporting files. JRE is required to run Java
applications on a computer.

3. JVM (Java Virtual Machine):


 The Java Virtual Machine is computing machine that enables Java bytecode to be
executed on different platforms. It interprets the compiled Java bytecode into
machine code that can be understood and executed by the underlying operating
system

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 7
Object Oriented with java programming

Data Types in Java

 Data types specify the different sizes and values that can be stored in the variable.
 Every variable declared before using it in program.
 Java programming language has a rich set of data types.

There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays and etc.

Class

Java Primitive Data Types


 In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
 They hold a single, direct value in memory.

There are 8 types of primitive data types:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 8
Object Oriented with java programming

There are 8 types of primitive data types:

1. Boolean Data Type


Boolean is used to store only two values: true or false.
It is mainly used in conditions, loops, and decision making like if statements.
Example: boolean isLoggedIn = true;

2. Byte Data Type


Byte is an 8-bit integer data type. It uses very little memory.
It is useful when working with large arrays where memory saving matters.
Range: -128 to 127
Example: byte age = 25;

3. Short Data Type


Short is a 16-bit integer data type.
It is used when values are small but larger than byte range.
Range: -32,768 to 32,767
Example: short marks = 1200;

4. Int Data Type


Int is a 32-bit integer and the most commonly used data type for whole numbers.
It is fast and suitable for general calculations.
Range: -2³¹ to 2³¹ - 1
Example: int population = 100000;

5. Long Data Type


Long is a 64-bit integer used for very large whole numbers.
You must add L at the end of the value.
Range: -2⁶³ to 2⁶³ - 1
Example: long distance = 9876543210L;

6. Float Data Type


Float stores decimal values using 32 bits.
It is used when memory saving is important but high precision is not required.
Always add f at the end.
Example: float temperature = 36.5f;

7. Double Data Type


Double stores decimal values using 64 bits and gives better accuracy than float.
It is the default choice for decimal numbers in Java.
Not suitable for exact values like money.
Example: double price = 199.99;

8. Char Data Type


Char stores a single character using Unicode format.
It can store letters, numbers, or symbols.
Example: char grade = 'A';

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 9
Object Oriented with java programming

Example on data types:

public class PrimitiveTypesExample


{
public static void main(String[] args)
{
byte b = 10;
short s = 100;
int i = 1000;
long l = 10000L;

float f = 10.5f;
double d = 20.55;

char c = 'A';
boolean flag = true;

[Link](b);
[Link](s);
[Link](i);
[Link](l);
[Link](f);
[Link](d);
[Link](c);
[Link](flag);
}
}

OUTPUT:

10
100
1000
10000
10.5
20.55
A
true

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 10
Object Oriented with java programming

Java Variables
 In Java, a variable is a name given to a memory location where data is stored.
 The value of a variable can change while the program runs.
 Think of a variable as a labeled box in memory that holds some value.

Why variables are needed


 To store data
 To reuse values
 To perform calculations
 To make programs flexible and readable
Syntax

dataType variableName = value;

Example:
int age = 20;
Here:
int is the data type
age is the variable name
20 is the value stored in memory

Types of Variables in Java

Java mainly has three types of variables based on where they are declared and how memory
is allocated.

1. Local Variable.

2. Instance Variable.

3. Static Variable.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 11
Object Oriented with java programming

1. Local Variable
What it is local variable?
A local variable is declared inside a method, constructor, or block.
It exists only while that method is running.

How it works
When a method is called:
 Java creates a stack frame for that method.
 It creates Temporary memory.
 Local variables are stored inside this stack frame.
 Automatically destroyed after method execution

Scope of Local Variable:


 Scope of local variable is limited to method.
Such a variable is accessible only within the
method or block in which it is declared.

 A local variable cannot be defined with "static" keyword.

Key points

 Scope: only inside the method


 No default value, must be initialized
 Fast access because stack memory is fast
 Cannot be accessed outside the method
Program:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 12
Object Oriented with java programming

2) Instance Variable

What it is Instance variable?


 An instance variable is declared inside a class but outside methods.
Each object gets its own copy.
 It is not declared as static.
How it works
When you create an object:
 Memory is allocated in the Heap
 Instance variables are stored with that object
 They live as long as the object lives
Key points
 Scope: whole object
 Default values are assigned (0, null, false)
 Different objects have different copies
Think of instance variables like personal bags. Each student carries their own bag.

Example:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 13
Object Oriented with java programming

3) Static variable
What it is Static variable?

 A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.

How it works

When the class is loaded:

 Static variables are created once.


 Stored in Method Area (Static Memory)
 Shared across all instances.

Key points

 One copy only


 Can be accessed using class name
 Memory efficient for common data

Think of static variables like a notice board. Everyone reads the same information.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 14
Object Oriented with java programming

Lab Program 6: Program with class variable that is available for all instances of a class.
Use static variable declaration. Observe the changes that occurring the object’s
member variable values.

OUTPUT:

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 15
Object Oriented with java programming

Java Type casting


 Converting one data type to another data type is called type casting.
Java Variable Example: Widening
public class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
[Link](a);
[Link](f);
}
}
Output:

10
10.0
Java Variable Example: Narrowing (Typecasting)
public class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}
}
Output:

10.5
10

Java Variable Example: Overflow


class Simple
{
public static void main(String[] args)
{
//Overflow
int a=130;
byte b=(byte)a;
[Link](a);
[Link](b);
}
}
Output:130
-126

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 16
Object Oriented with java programming

Java Operators:
 Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while * is also an operator used for
multiplication.
 Operators in Java can be classified into:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators

1. Java Arithmetic Operators

 Arithmetic operators are used to perform arithmetic operations on variables and data.
For example, a + b;
 Here, the + operator is used to add two variables a and b. Similarly, there are various
other arithmetic operators in Java.

Let's see some more Arithmetic operators available in Java.

Operator Meaning Example


+ Addition a+b;
- Subtraction a-b;
* Multiplication A*b;
/ Division a/b;
% Module a%b;

2. Java Assignment Operators


Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on
its left. That is, 5 is assigned to the variable age.
Let's see some more assignment operators available in Java.

Operator Example Equivalent to


= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 17
Object Oriented with java programming

3. Java Relational Operators

 Relational operators are used to check the relationship between two operands.
 For example : a < b; // check if a is less than b
 Here, < operator is the relational operator. It checks if a is less than b or not. It
returns either true or false.

Operator Description Example


== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
>= Greater Than or Equal To 3 >= 5 returns false
<= Less Than or Equal To 3 <= 5 returns true

4. Java Logical Operators


Logical operators are used to check whether an expression is true or false. They are
used in decision making.

Logical operators are


Operator Example Meaning
&& (Logical AND) expression1 && expression2 true only if both expression1 and
expression2 are true
|| (Logical OR) expression1 || expression2 true if either expression1 or
expression2 is true
! (Logical NOT) !expression true if expression is false and vice versa

5. Java Unary Operators


Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.

Different types of unary operators are:


Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without
using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
! Logical complement operator: inverts the value of a boolean

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 18
Object Oriented with java programming

Increment and Decrement Operators


 Java also provides increment and decrement operators: ++ and --
respectively. ++ increases the value of the operand by 1, while -- decrease it by 1. For
example,
int num = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.

6. Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits. For
example,
Bitwise complement Operation of 35

35 = 00100011 (In Binary)


~ 00100011
________
11011100 = 220 (In decimal)

Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).
The various bitwise operators present in Java are:

Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR

7. Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-
else statement. For example,
variable = Expression? expression1: expression2
Example:
public class TernaryOperatorExample Output
{
public static void main(String[] args)
{ The number
int number = 10; 10 is even.
String result;

result = (number % 2 == 0) ? "even" : "odd";


[Link]("The number " + number + " is " +
result + ".");
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 19
Object Oriented with java programming
PROGRAM ON OPERATORS
class OperatorsDemo
{
public static void main(String[] args)
{
// --------- Arithmetic Operators ---------
int a = 12, b = 5;
[Link]("Arithmetic Operators:");
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));

// --------- Assignment Operators ---------


int num = 20;
[Link]("\nAssignment Operators:");
[Link]("num = " + num);

num += 5;
[Link]("num += 5 : " + num);

num -= 3;
[Link]("num -= 3 : " + num);

num *= 2;
[Link]("num *= 2 : " + num);

num /= 4;
[Link]("num /= 4 : " + num);

num %= 3;
[Link]("num %= 3 : " + num);

// --------- Relational Operators ---------


int x = 7, y = 11;
[Link]("\nRelational Operators:");
[Link]("x == y : " + (x == y));
[Link]("x != y : " + (x != y));
[Link]("x > y : " + (x > y));
[Link]("x < y : " + (x < y));
[Link]("x >= y : " + (x >= y));
[Link]("x <= y : " + (x <= y));

// --------- Logical Operators ---------


[Link]("\nLogical Operators:");
[Link]("(5 > 3) && (8 > 5) : " + ((5 > 3) && (8 > 5)));
[Link]("(5 > 3) && (8 < 5) : " + ((5 > 3) && (8 < 5)));
[Link]("(5 < 3) || (8 > 5) : " + ((5 < 3) || (8 > 5)));
[Link]("!(5 == 3) : " + (!(5 == 3)));

// --------- Unary Operators ---------


int p = 12, q = 12;
[Link]("\nUnary Operators:");
[Link]("Value of p: " + p);
[Link]("++p = " + (++p));

[Link]("Value of q: " + q);


[Link]("--q = " + (--q));
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 20
Object Oriented with java programming

Control Statements in java:

What is a control structure in Java?

 A control structure decides how the program runs, meaning which statements run,
how many times they run, and in what order.
 By default, Java runs code line by line from top to bottom.
 Control structures change this normal flow.

Selection control structure (Decision making)

A selection control structure allows a program to make decisions.


It chooses which block of code to execute based on a condition.

Selection statements in Java

 if

 if-else

 if-else-if

 nested if

 switch

 ternary operator (?:)

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 21
Object Oriented with java programming

1. Java if (simple if) Statement


The Java if statement tests the condition. It executes the if block if condition is true.
Runs code only when the condition is true.

The syntax of if-then statement in Java is:


 Here expression is a boolean

expression (returns
either true or false).
 If the expression is evaluated to true,

statement(s) inside the body


of if (statements inside parenthesis)
are executed.
 If the expression is evaluated to false,

statement(s) inside the body of if are


skipped from execution.

Example 1: Java if Statement

class CheckNumber OUTPUT


{ Number is positive.
public static void main(String[] args)
{
int number = 10;

if (number > 0)
{
[Link]("Number is positive.");
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 22
Object Oriented with java programming

2. Java if...else (if-then-else) Statement


The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
The syntax of if-then-else statement is:

How it works

1. The condition is
evaluated.
2. If the condition is true
→ code inside the if
block runs.
3. If the condition is false
→ code inside the else
block runs.
4. Only one block executes
at a time.

Example:
OUTPUT
class CheckNumber
{ Number is positive.
public static void main(String[] args) This statement is
{ always executed.
int number = 10;

if (number > 0)
{
[Link]("Number is positive.");
}
else
{
[Link]("Number is not positive.");
}
[Link]("This statement is always executed.");
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 23
Object Oriented with java programming

3. Java if..else..if Statement (if ..else.. ladder)


In Java, it's possible to execute one block of code among many. For that, you can use
if..else...if ladder.
Syntax of if..else..if
How it works
1. condition1 is
checked first
2. If false, condition2
is checked
3. This continues until
one condition is true
4. If all conditions are
false, the else block
runs.
5. Only one block
executes.

5.

Example:
class IfElseLadderExample OUTPUT

{ Grade B
public static void main(String[] args)
{
int marks = 78;

if (marks >= 90)


{
[Link]("Grade A");
}
else if (marks >= 75)
{
[Link]("Grade B");
}
else if (marks >= 35)
{
[Link]("Grade C");
}
else
{
[Link]("Fail");
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 24
Object Oriented with java programming

4. Java Nested if..else Statement


The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
 It's possible to have if..else statements inside a if..else statement in Java. It's called
nested if...else statement.
Here's a program to find largest of 3 numbers:
Syntax:
How it works
condition1 is checked first.

If false → program skips the


entire block

condition2 is checked only if


condition1 is true

Inner code runs only when


both conditions are true
Example 4: Nested if...else Statement
class LargestNumber OUTPUT
{
public static void main(String[] args) Largest number is 4.5
{
double n1 = -1.0, n2 = 4.5, n3 = -5.3;
double largestNumber;
if (n1 >= n2)
{
if (n1 >= n3)
{
largestNumber = n1;
}
else
{
largestNumber = n3;
}
}
else
{
if (n2 >= n3)
{
largestNumber = n2;
}
else
{
largestNumber = n3;
}
}
[Link]("Largest number is " + largestNumber);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 25
Object Oriented with java programming

5. Java Switch Statement:


The switch statement allows us to execute a block of code among many alternatives.
Syntax:

How does the switch-case statement work?


The expression is evaluated once and compared with the values of each case.
 If expression matches with value1, the code of case value1 are executed. Similarly, the
code of case value2 is executed if expression matches with value2
 If there is no match, the code of the default case is executed

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 26
Object Oriented with java programming

// Java Program to check the size using the switch...case statement

class SwitchExample
{
public static void main(String[] args)
{
int day = 3;

switch (day)
{
case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

case 3:
[Link]("Wednesday");
break;

case 4:
[Link]("Thursday");
break;

case 5:
[Link]("Friday");
break;

default:
[Link]("Invalid day");
}
}
}
Output:

Wednesday

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 27
Object Oriented with java programming

Java Looping:
In computer programming, loops are used to repeat a block of code.

For example, if you want to show a message 100 times, then rather than typing the same
code 100 times, you can use a loop.

In Java, there are three types of loops.

1. for loop
2. while loop
3. do...while loop

[Link] loop:
Java for loop is used to run a block of code for a certain number of times. The syntax
of for loop is:

for (initialization; condition; Increment/Decrement)


{
// body of the loop
}

Here,

1. The initialization initializes and/or declares variables and executes only once.
2. The condition is evaluated. If the condition is true, the body of the for loop is
executed.
3. The Increment/Decrement updates the value of initialization.
4. The condition is evaluated again. The process continues until the condition is false.

Example 1: Display a Text Five Times


// Program to print a text 5 times
class Main OUTPUT:
{
public static void main(String[] args) Java is fun
{ Java is fun
int n = 5; Java is fun
// for loop Java is fun
for (int i = 1; i <= n; i++) Java is fun
{
[Link]("Java is fun");
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 28
Object Oriented with java programming

Example 3: Display Sum of n Natural Numbers


// Program to find the sum of natural numbers from 1 to 10.

class SumOfNaturalNumber OUTPUT:


{
public static void main(String[] args) Sum = 50
{
int sum = 0;
int n = 10;

// for loop
for (int i = 1; i <= n; i++)
{
sum = sum + i
}
[Link]("Sum = " + sum);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 29
Object Oriented with java programming

1. Java while loop


 Java while loop is used to run a specific code until a certain condition is true.

The syntax of the while loop is:

//Intialization
while (Condition)
{
// body of loop
//Increment /Decrement
}

Here,
1. A while loop evaluates the Condition inside the parenthesis ().
2. If the Condition evaluates to true, the code inside the while loop is executed.
3. The Condition is evaluated again.
4. This process continues until the Condition is false.
5. When the Condition evaluates to false, the loop stops.

Example 1: Display Numbers from 1 to 5


import [Link]; OUTPUT:

class PasswordCheck Enter password: abc


{
public static void main(String[] args) Enter password: 12345
{
Enter password: java123
Scanner sc = new Scanner([Link]);
String password = ""; Access granted

while (![Link]("java123"))
{
[Link]("Enter password: ");
password = [Link]();
}

[Link]("Access granted");
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 30
Object Oriented with java programming

2. Java do...while loop


 The do...while loop is similar to while loop. However, the body of do...while loop is
executed once before the test expression is checked. For example,

do
{
// body of loop
//Increment/Decrement
} while(Condition);

Here,
1. The body of the loop is executed at first. Then the Condition is evaluated.
2. If the Condition evaluates to true, the body of the loop inside the do statement is
executed again.
3. The Condition is evaluated once again.
4. If the Condition evaluates to true, the body of the loop inside the do statement is
executed again.
5. This process continues until the Condition evaluates to false. Then the loop stops.

Example: Display Numbers from 1 to 5


import [Link]; OUTPUT:

class AgeCheck Enter your age: -5


{
public static void main(String[] args) Enter your age: 0
{
Scanner sc = new Scanner([Link]); Enter your age: 18
int age;
Valid age entered
do
{
[Link]("Enter your age: ");
age = [Link]();
} while (age <= 0);

[Link]("Valid age entered");


}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 31
Object Oriented with java programming

Nested Loop in Java


 If a loop exists inside the body of another loop, it's called a nested loop. Here's an
example of the nested for loop.

// outer loop
for (int i = 1; i <= 5; ++i)
{
// codes
// inner loop
for(int j = 1; j <=2; ++j)
{
// codes
}
..
}

Here, we are using a for loop inside another for loop.

Here is a program to create a half pyramid pattern using nested loops.

class Main OUTPUT:


{ 1
public static void main(String[] args) 12
{ 123
1234
int rows = 5;
12345
// outer loop
for (int i = 1; i <= rows; i++)
{

// inner loop to print the numbers


for (int j = 1; j <= i; j++)
{
[Link](j + " ");
}
[Link]("");
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 32
Object Oriented with java programming

Java for-each Loop


 The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.

 It works on the basis of elements and not the index. It returns element one by one in
the defined variable.

Syntax:

for(data_type variable : array_name)


{
//code to be executed
}

Here,

 Array_name - an array or a collection


 variable - each item of array/collection is assigned to this variable
 data_type - the data type of the array/collection

Example 1: Print Array Elements


class PrintArray OUTPUT:
{ 3
public static void main(String[] args) 9
{ 5
// create an array -5
int[ ] numbers = {3, 9, 5, -5};

// for each loop


for (int number: numbers)
{
[Link](number);
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 33
Object Oriented with java programming

Java Jumping Statements:


 Jumping statements are control statements that transfer execution control from one
point to another point in the program. There are three Jump statements that are
provided in the Java programming language:
1. Break statement.
2. Continue statement.
3. Return Statement

1. Break statement
1. Using Break Statement to exit a loop:

In java, the break statement is used to terminate the execution of the nearest looping
statement or switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.

Syntax:

break;

When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:

// Java program to illustrate the OUTPUT:


// break keyword in Java 1
import [Link].*; 2
3
class BreakExample 4
{ 5
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
[Link](i);
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 34
Object Oriented with java programming

2. Java continue:
 While working with loops, sometimes you might want to skip some statements or
terminate the loop. In such cases, break and continue statements are used.

The continue statement skips the current iteration of a loop (for, while, do...while, etc).

After the continue statement, the program moves to the end of the loop. And, test
expression is evaluated (update statement is evaluated in case of the for loop).

Here's the syntax of the continue statement.

continue;

Example: // Java program to illustrate the continue keyword in Java

OUTPUT:
import [Link].*; 0
class ContinueExample 1
{ 2
public static void main(String[] args) 3
{ 4
for (int i = 0; i < 10; i++) 5
{
if (i == 6) 7
{ 8
[Link](); 9
continue;
}
[Link](i);
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 35
Object Oriented with java programming

3. Return Statement
 The “return” keyword can help you transfer control from one method to the method
that called it. Since the control jumps from one part of the program to another, the
return is also a jump statement.

“return” is a reserved keyword means we can’t use it as an identifier.

Syntax:

return value;

class ReturnExample OUTPUT:


{ Result: 15

public static int calculateSum(int num1, int num2)


{

[Link]("Calculating the sum of " + num1 + " and " + num2);


int sum = num1 + num2;
[Link]("The sum is: " + sum);

return sum;
}

public static void main(String[] args)


{

int result = calculateSum(5, 10);

[Link]("Result: " + result);


}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 36
Object Oriented with java programming

Java Array:
What is an Array in Java?

 An array refers to a data structure that contains homogeneous elements. This means
that all the elements in the array are of the same data type. Let's take an example:

This is an array of seven elements. All the elements are integers and homogeneous. The box
below the array is called the index, which always starts from zero and goes up to n-1
elements.

In this case, as there are seven elements, the index is from 0 to 1.

Elements stored under a single name: All the elements are stored under one name. This name
is used any time we use an array.

Advantages:

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.
 Java arrays enable you to access any element randomly with the help of indexes
 It is easy to store and manipulate large data sets

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
 Java cannot store heterogeneous data. It can only store a single type of primitives

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 37
Object Oriented with java programming

Step-by-step explanation for declaring an array.

Step 1: Declare an Array


First, tell Java what type of data the array will store.
Syntax:
data_type[] arrayName;
// or
data_type arrayName[];
Example:
int[] marks;

Step 2: Create an Array


Next, create the array by giving its size.
marks = new int[5]; // array can store 5 integers

Step 3: Declare and Create Together


You can do both steps in one line.
int[] marks = new int[5];

Step 4: Initialize an Array


You can give values at the time of declaration.
int[] marks = {7, 10, 23, 17, 5};

Examples with Different Data Types


Integer Array
int[] numbers = new int[10];
String Array
String[] names = new String[3];
Double Array
double[] prices = new double[4];
Character Array
char[] letters = {'a', 'b', 'c', 'd'};

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 38
Object Oriented with java programming

Types of Array in java


There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array

1. Single Dimensional Array - (One- Dimensional Array)

 A one-dimensional array in Java is a collection of elements, all of the same type,


stored in a single row. Each element in the array can be accessed by its index, which
starts from 0. Let's break down the concept with an example.

Steps to Create and Use a One-Dimensional Array in Java:

1. Declare the Array: Specify the type of elements it will store and the name of the array.

2. Instantiate the Array: Use the `new` keyword to allocate memory for the array.

3. Initialize the Array: Assign values to the elements in the array.

Example:
Let's create an array of integers to store 5 numbers.
# Step 1: Declare the Array
Ex: int[ ] numbers;
This line declares an array named `numbers` that will hold integers.
# Step 2: Instantiate the Array
Ex: numbers = new int[5];
This line allocates memory for 5 integers. Now `numbers` can hold 5 elements.
# Step 3: Initialize the Array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 39
Object Oriented with java programming

Here, we assign values to each element in the array using their indices.

# Full Example #1:

public class ArrayExample


{ OUTPUT:
public static void main(String[] args)
{ Element at index 0: 10
// Step 1: Declare the array Element at index 1: 20
int[] numbers; Element at index 2: 30
Element at index 3: 40
// Step 2: Instantiate the array Element at index 4: 50
numbers = new int[5];

// Step 3: Initialize the array


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Print the elements of the array


for (int i = 0; i < [Link]; i++)
{
[Link]("Element at index " + i +
": " + numbers[i]);
}
}
}

Example #2: (Displays the elements using for each loop)


public class ArrayExample
{ OUTPUT:
public static void main(String[] args) Element at index 0:
{ 10
// Step 1: Declare the array and intialize Element at index 1:
int[ ] numbers = {10,20,30,40,50}; 20
Element at index 2:
30
// Print the elements of the array
Element at index 3:
int i=0;
40
for (int number:numbers)
Element at index 4:
{
50
[Link]("Element at index " + i + ": " + number);
i++;
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 40
Object Oriented with java programming

2. Two Dimensional Array


 A two dimensional array stores data in rows and columns, like a table or matrix.

Declaration Syntax
 You can declare a 2D array in these ways:

dataType[][] arrayName;
dataType arrayName[][];
Example:

int[][] arr;

Create (Instantiate) a 2D Array


 Specify the number of rows and columns.

int[][] arr = new int[3][3]; // 3 rows and 3 columns

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

//Java Program to illustrate the use of multidimensional array


class Test_Array
{ OUTPUT:
public static void main(String args[ ]) 1 2 3
{ 2 4 5
//declaring and initializing 2D array 4 4 5
int arr[ ][ ]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 41
Object Oriented with java programming

Class and Object in Java


Class: Class is a blue print which is containing only list of variables and method .A class is a
group of objects that has common properties.
OR
Class: Class can be defined as a template / blueprint that describe the state and behavior of
the objects.

A class contains:
1. Field/Data Member: Data items are called fields or data members (Instance of class)
2. Method : Functions are called methods.
3. Constructor
4. Block

In java variables are known as instances of classes, which are actual objects.

Create a Class in Java (Syntax for creating a class)

 A class in Java is created using the class keyword.

Syntax:
class ClassName
{
// fields
// methods
}

In a class:

 Fields (variables) store data. They represent the state of an object.


 Methods define actions or operations. They represent the behavior of an object.

Example:

class Student
{
int id; // field
String name; // field

void display() // method


{
[Link](id + " " + name);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 42
Object Oriented with java programming

Field Declaration:
Data is encapsulated in a class by placing data fields inside the body of a class definition.
These variables are called instance variables because of they are created whenever an object
of the class they are instantiated.

Example for Field Declaration:


class Rectangle
{
int length, width;
}

Here, in above example for class field declaration Rectangle is the class name and in this class
we declared the two variable like length and width.

Note: If we are created a class like above example, no storage space or memory allocation
has been created for these variables, also called as member variables.

Method Declaration:
A method is a collection of statements that perform some specific task and return the result to
the caller. A method can perform some specific task without returning anything.
Syntax
modifier data_type method_name (Parameter List)
{
// method body
}

Example1:
class Rectangle
{
int length;
int width;

void getdata(int x, int y)


{
length=x;
width=y;
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 43
Object Oriented with java programming

Java Object :

Object: Object is an instance of class, object has state and behaviors.


An Object in java has three characteristics:
1. State
2. Behavior
3. Identity

State: Represents data (value) of an object.


Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.
Ex: Chair, Bike, Pen, Table, Animal

Object Definitions:

 Object is a real world entity.


 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of class

Creation of Object:
An object in java is essentially a block of memory that contains space to store all the
instance variables. Creating an object is also referred to as instantiating an object.

 Objects in java created using new operator. The new operator dynamically allocates
memory for an object.

Example for creating an object:

A simple class example


 Suppose, Student is a class and student's name, roll number, age will be its property.
Let’s see this in Java syntax
class Student
{
String name;
Int rollno;
int age;
}

Creating Object for the class Student is given below.

Student std; //Declare the object for class student


Std=new Student(); //creating the object.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 44
Object Oriented with java programming

 Both statements can be combined into one as shown below:

Student std=new Student( );

 After the above statement std is instance/object of Student class. Here


the new keyword creates an actual physical copy of the object and assign it to
the std variable. It will have physical existence and get memory in heap
area. The new operator dynamically allocates memory for an object

The method Student( ) is the default constructor of the class student. We can create any
number of objects of Student.

Example:

Student std1=new Student( );


Student std2=new Student( );
Student std3=new Student( );

Java Program: Values Assigned in Class, Accessed in Main


class Student
OUTPUT
{
int rollNo = 1; Roll No: 1

String name = "Raju"; Name : Raju

void display()
{
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}

public static void main(String[] args)


{
Student s = new Student();
[Link]();
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 45
Object Oriented with java programming

Java Program: Area of Circle (Class and Object)


class Circle OUTPUT
{
double radius = 7; Area of Circle: 153.86
double pi = 3.14;

void area()
{
double result = pi * radius * radius;
[Link]("Area of Circle: " + result);
}

public static void main(String[] args)


{
Circle c = new Circle();
[Link]();
}
}

Java Program: Read Name Using Class and Object


import [Link];
class Student
OUTPUT
{
String name; Enter name: Raju

Name: Raju
void readName()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
}

void displayName()
{
[Link]("Name: " + name);
}

public static void main(String[] args)


{
Student s = new Student();
[Link]();
[Link]();
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 46
Object Oriented with java programming

Accessing class members/Accessing instance variables and methods:

 We can’t use instance variables outside the class and also methods. To do this we must
concerned object and the dot(.) operator as shown below.

Syntax:

Object_name.variable_name=value;
Object_name.method_name(parameter list);

Where,
Object_name Name of the object
variable_nameName of the variable.
Method_nameMethod
Parameter_listActual values to the parameter.

Example 1: java program to access the class variable by reference variable.

class Student OUTPUT


{
int rollno; Roll No = 1114520
String name;
Name = Shridhar
int age;
} Age = 24
public class StudentDemo
{
public static void main(String args[])
{
Student std=new Student();

[Link]=1114520;
[Link]="Shridhar";
[Link]=24;

[Link]("Roll No = "+[Link]);
[Link]("Name = "+[Link]);
[Link]("Age = "+[Link]);
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 47
Object Oriented with java programming

Instance Operator:
 In Java, the instance operator is represented by the keyword “instanceof ”. It is used to
check whether an object is an instance of a particular class or implements a particular
interface.

Here's the basic syntax:

object instanceof ClassName; Example: s1 instanceof Student

This operator returns `true` if the object is an instance of the specified class or implements
the specified interface, otherwise it returns `false`.

For example:
OUTPUT
class Dog Dog is barking
{ True : The animal is a Dog.
void bark()
{
[Link](“Dog is barking”);
}
}
public class Animal extends Dog
{
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();

if(d instanceof Dog)


{
[Link]("True : The animal is a Dog.");
}
else
{
[Link]("False : The animal is not a Dog.");
}
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 48
Object Oriented with java programming

Visibility Modifier/Access Modifier:


What are Access Modifiers?

 The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
 We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Example(Click Here)

2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Example(Click Here)

3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Example(Click Here)

4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Example(Click Here)

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 49
Object Oriented with java programming

Java Method Overloading:

 In Java, if a class having two or more methods with having the same name but with
differ in parameters lists. These methods are called overloaded methods and this is
called method overloading.

For example:
class MethodOverload
{
void func( ) { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
}
Here, the func( ) method is overloaded. These methods have the same name but accept
different arguments.

There are two ways to overload the method in java


1. By changing number of arguments
2. By changing the data type

1) Method Overloading: changing no. of arguments


 In this example, we have created two methods, first add( ) method performs addition
of two numbers and second add( ) method performs addition of three numbers.
 In this example, we are creating static methods so that we don't need to create instance
for calling methods.

class Adder
{
static int add(int a,int b) OUTPUT
{ 30
return a+b;
}
60
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](10,20));
[Link]([Link](10,20,30));
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 50
Object Oriented with java programming

2) Method Overloading: changing data type of arguments

 In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

class Addition

{ OUTPUT
int addInt() Default integer sum: 30
{ Integer sum: 15
return 10 + 20; Default Float sum: 5.0
Float sum: 6.0
}

int addInt(int a, int b)


{
return a + b;
}

float addFloat()
{
return 2.5f+2.5f;
}
float addFloat(float a, float b)
{
return a + b;
}
}
public class OverloadingExample
{
public static void main(String[] args)
{
Addition obj = new Addition();
[Link]("Default integer sum: " + [Link]());
[Link]("Integer sum: " + [Link](5, 10));
[Link]("Default Float sum: " + [Link]());
[Link]("Float sum: " + [Link](2.5f, 3.5f));
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 51
Object Oriented with java programming

Constructor:
 A constructor in Java is a special method that is used to initialize objects. The constructor
is called when an object of a class is created.
 At the time of calling constructor, memory for the object is allocated in the memory.
 It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.

Rules for creating Java constructor


There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor.
1. Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:

<class_name> ( )
{
}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the tim
object creation.
//Java Program to create, initialize and call a default constructor

public class MyClass


{
OUTPUT:
int number;
String name; Number: 0
public MyClass() Name: Default
{
number = 0; // default value
name = "Default"; // default value
}

public void display()


{
[Link]("Number: " + number);
[Link]("Name: " + name);
}

public static void main(String[] args)


{
MyClass obj = new MyClass();
[Link]();
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 52
Object Oriented with java programming

2. Parameterized Constructor:
A parameterized constructor in Java is a constructor that accepts parameters, allowing you to
initialize an object with specific values at the time of its creation.
Syntax:
public class ClassName
{
// Instance variables
datatype variableName1;
datatype variableName2;

// Parameterized constructor
public ClassName(data_type1 parameterName1, data_type2 parameterName2, ...)
{
// Initialization of instance variables with parameter values
// Parameterized constructor body.
}
}

Here is an example:

public class Student OUTPUT:


{
int id;
String name; ID:1
Name:Arun
// Parameterized constructor
public Student(int id1, String name1)
{ ID:2
id = id1; Name:Vikram
name = name1;
}

public void display()


{
[Link]("ID: " + id);
[Link]("Name: " + name);
}

public static void main(String[] args)


{

Student student1 = new Student(1, "Arun");


Student student2 = new Student(2, "Vikram");

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

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 53
Object Oriented with java programming

Constructor Overloading:

 Constructor overloading in Java refers to the concept of having multiple constructors


in a class with different parameter lists.
 This allows objects of the class to be initialized in various ways, providing flexibility in
object creation. Each constructor can have a unique signature based on the number or
types of parameters it accepts.

Here's an example to illustrate constructor overloading:

public class Rectangle OUTPUT:


{
int length;
Area of
int width;
square: 25
Area of
// Default constructor rectangle: 24
public Rectangle()
{
length = 0;
width = 0;
}

// Parameterized constructor with one parameter


public Rectangle(int side)
{
length = side;
width = side;
}

// Parameterized constructor with two parameters


public Rectangle(int l, int w)
{
length = l;
width = w;
}

// Method to calculate area


public int calculateArea()
{
return length * width;
}

public static void main(String[] args)


{
Rectangle square = new Rectangle(5);
Rectangle rectangle = new Rectangle(4, 6);
// Displaying areas
[Link]("Area of square: " +
[Link]());
[Link]("Area of rectangle: " +
[Link]());
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 54
Object Oriented with java programming

Static Members:

 The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, block.
 The static keyword belongs to the class than an instance of the class.

The static can be:


1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block

1. Static Variable:
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
 The static variable gets memory only once in the class area at the time of class
loading.

Example: Java Program to demonstrate the use of static variable

OUTPUT:
class Student
{
int rollno;
111 Karan ITS
String name; 222 Aryan ITS
static String college ="Tungal jamakhandi";

Student(int r, String n)
{
rollno = r;
name = n;
}

void display( )
{
[Link](rollno+" "+name+" "+college);
}
}

// Test class to show the values of objects


public class TestStaticVariable
{
public static void main(String args[ ])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
[Link]();
[Link]();
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 55
Object Oriented with java programming

2. Static Method:

If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

class Student OUTPUT:


{
static String name="Santosh";
static void Display() Name=Santosh
{
[Link]("Name="+name); After change the name:
[Link]("After change the name:"); Name= Rahul
name = "Rahul"; // change static variable
[Link]("Name="+name);
}
public static void main(String args[])
{
Display();
}
}

3. Static block:

o It Is used to initialize the static data member.


o It is executed before the main method at the time of class loading.

Here is an Example:
class StaticBlock
OUTPUT:
{
static Static block is invoked
{
[Link]("static block is invoked"); Hello JAVA
}
public static void main(String args[ ])
{
[Link]("Hello JAVA");
}
}

Prof. Raju Vathari Tungal BCA and BSc Degree College-Jamkhandi Page 56

You might also like