CHAPTER 1: Basics of java and overloading
1.0. Introduction
1.1. Object-Oriented Programming (OOP)
1.2. Compare procedure-oriented programming and object-oriented programming
1.3. Features of Java
1.4. Bytecode, JVM, JRM, and JDK
1.5. How to write and executing a Java program
1.6. The building blocks of a Java program
1.7. Variables in Java
1.8. Conversion and Casting features
1.9. Conditional statements
1.9.2 Looping Statements
1.9.1 Decision-Making Statements
1.10. Array’s
1.11. Strings
1.12. Objects and Classes
1.13. Method in java
1.13.1 Method Overloading
1.14. Constructor
1.14.1 Constructor Overloading
1.15. this Keyword
1.16. static keyword
1.17. Command-Line Arguments
CHAPTER 1: Basics of java and overloading
1.0. INTRODUCTION
Java is an important object-oriented programming language that is used in the software
industry today. Object-Oriented Programming is also known as OOP. Objects are the basic
elements of object-oriented programming. OOPS (Object Oriented Programming System) is
used to describe a computer application that comprises multiple objects connected. It is a type
of programming language in which the programmers not only define the data type of a data
structure (files, arrays, and so on) but also define the behaviour of the data structure.
Therefore, the data structure becomes an object, which includes both data and functions.
1.1. Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm centred around the concept
of “objects,” which are instances of classes. OOP emphasizes organizing code based on real-
world entities, making it easier to structure and manage complex applications. Here are the
primary features of OOP:
1. Classes and Objects: In OOP, class can be defined as a template/blueprint that
describes the behavior/state that the object of its type support.
An object is an instance of a class, representing a real-time entity with its
own attribute values. Classes and objects make OOP modular and provide a clear
structure.
2. Encapsulation: Encapsulation is the bundling of data (attributes) and methods
(functions) that operate on that data within a single unit (class). This helps in access
control, protecting the data and providing a controlled way of interacting with it.
3. Abstraction: Abstraction is the concept of hiding the complex details and exposing
only the necessary details. It allows programmers to focus on interactions at a higher
level without needing to understand all the details of implementation.
4. Inheritance: It is the technique of creating new classes by making use of the behavior
of the existing classes. This is done by extending the behavior of the existing classes
just by adding additional features as required, thus bringing in the reusability of
existing code.
5. Polymorphism: Polymorphism, which means one name multiple forms. It allows to
change behavior according to the instance of the object that it holds. This can be
achieved through method overloading (where multiple methods have the same name
but different parameters) and method overriding (where a child class provides a
specific implementation of a method already defined in its parent class).
1.2. Compare procedure-oriented programming and object-oriented programming
OOP: OOP, refers to Object Oriented Programming and its deals with objects and their
properties. Major concepts of OOPs are Class/objects, Abstraction, Encapsulation,
Polymorphism, Inheritance
POP: POP, refers to Procedural Oriented Programming and its deals with programs and
functions. Programs are divided into functions and data is global.
Following are the important differences between OOP and POP.
S.No. Key OOP POP
1 Core Concept Focus on objects and classes. Focus on functions and procedures.
2 Approach OOP follows bottom-up approach. POP follows top-down approach.
A program is divided to objects and their
3 Division A program is divided into functions.
interactions.
Importance is given to the data rather
4 Importance Importance is not given to data
than procedures or functions
Access control is supported via access
5 Access control No access modifiers are supported.
modifiers.
Objects can move and communicate with Data can move freely from function to
6 Data Moving
each other through member functions. function in the system.
No data hiding present. Data is globally
7 Data Hiding Encapsulation is used to hide data.
accessible.
8 Inheritance Inheritance is supported. Inheritance is not supported.
Overloading is possible in the form of
9 Overloading Function Overloading and Operator In POP, Overloading is not possible.
Overloading.
10 Example C++, Java C, Pascal
What is JAVA?
Java is a programming language and a platform. It is a high-level, robust, object-oriented, and
secure programming language. It was developed by Sun Microsystems in the year 1995.
James. Gosling is known as the father of Java. Before Java, its name was Oak. Just like any
other programming language, Java programs consist of some basic elements such as
keywords, constants, variables, data types, operators, and expressions that help a programmer
to create logical programs, and some important features such as platform independence which
enables it to run on any computer platform.
Editions of Java
Each edition of Java has different capabilities.There are three editions of Java:
1. Java Standard Editions (JSE): It is used to create programs for a desktop computer.
2. Java Enterprise Edition (JEE): It is used to create large programs that run on the server and
manages heavy traffic and complex transactions.
3. Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.
1.3. Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language.
The features of Java are also known as java buzzwords. A list of most important features of
Java language is given below.
1. Simple
2. Object-Oriented
3. Platform independent
4. Robust and Secure
5. Multithreading
6. Distributed
7. Dynamic and Extensible
8. Automatic Memory Management
9. Rich API
10. Support for GUI and Enterprise Applications
1. Simple: Java is very easy to learn, especially for developers familiar with languages
like C++. Its syntax is straightforward and removes many complexities, such as
pointers and multiple inheritance, simplifying coding.
2. Object-Oriented: Java follows the object-oriented programming (OOP) paradigm,
meaning it organizes software design around objects rather than functions and logic.
Key principles of OOP (like encapsulation, inheritance, and polymorphism) make Java
code modular, flexible, and easier to understand.
3. Platform Independence: Java is platform-independent because of the Java Virtual
Machine (JVM). Once written and compiled into bytecode, Java bytecode can run on
any platform that supports JVM, making it "write once, run anywhere."
4. Robust and Secure: Java emphasizes reliability with strong memory management,
exception handling, and garbage collection to avoid memory leaks and crashes. It also
has inbuilt security features, including a secure runtime environment and the ability to
restrict application access to system resources.
5. Multithreading: Java allows multiple threads to run concurrently, which improves the
performance of applications that require multitasking, such as real-time applications or
interactive applications like games and GUI programs.
6. Distributed: Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any machine
on the internet.
7. Dynamic and Extensible: Java can dynamically load classes at runtime, which makes
it adaptable to evolving environments. New classes and methods can be added to
libraries without changing existing code.
8. Automatic Memory Management (Garbage Collection): Java has an automatic
garbage collector that manages memory, which reduces the risk of memory leaks by
automatically clearing unused objects from memory.
9. Rich API: Java provides a comprehensive Application Programming Interface (API)
with libraries for tasks like database connections, I/O operations, networking, utilities,
XML parsing, and more. This reduces development time by providing ready-to-use
functionalities.
10. Support for GUI and Enterprise Applications: Java provides frameworks for
building desktop GUIs (Swing, AWT, JavaFX) and enterprise-level applications (Java
EE, Spring, Hibernate), enabling developers to create a variety of applications from
simple to complex enterprise-grade systems.
1.4. Bytecode, JVM, JRM, and JDK
Byte Code
In Java, bytecode is the intermediate code generated by the Java compiler after compiling
Java source code. This bytecode is stored in .class files and can be executed by the Java
Virtual Machine (JVM). This bytecode is a platform-independent code because it can be run
on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java
program. When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code. JVM is platform
dependent
Java Runtime Environment (JRE)
JRE (Java Runtime Environment) is a software package that provides Java class libraries,
Java Virtual Machine (JVM), and other components that are required to run Java
applications. JRE contains all the inbuilt packages and library files (lang, io, util, etc. all
packages are present in JRE)
Java Development Kit (JDK)
The Java Development Kit (JDK) is a software development environment which is used to
develop java applications and applets. It physically exists. It contains JRE + development
tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) etc. to complete the development of a Java Application.
1.5. How to write and executing a Java program
To write and execute a Java program, you need to follow these steps. You’ll require the Java
Development Kit (JDK) installed on your machine, as it includes both the compiler and the
Java Virtual Machine (JVM) required for running Java programs.
Steps to Write and Execute a Java Program
Step 1: Install the JDK
1. Download the latest JDK from the Oracle website or use OpenJDK.
2. Follow the installation instructions for your operating system.
3. Ensure that the java and javac commands are available in your system's PATH to run
Java commands in the terminal or command prompt.
Step 2: Write the Java Program
1. Open a text editor (like Notepad, VS Code, or any IDE like Eclipse, IntelliJ IDEA, or
NetBeans).
2. Write a simple Java program. Here’s an example of a basic Java program to print
"Hello, World!" to the console:
// HelloWorld.java
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
3. Save the file with a .java extension, such as HelloWorld.java. The file name should
match the public class name (HelloWorld in this case).
Step 3: Compile the Java Program
1. Open a terminal (or command prompt) and navigate to the directory where you saved
the .java file.
2. Compile the Java program by using the javac command:
Example D:\Education\programs > javac HelloWorld.java
3. If there are no errors, this command will generate a file named HelloWorld.class in
the same directory. This file contains the bytecode that can be executed by the JVM.
Step 4: Run the Java Program
1. Run the compiled program using the java command followed by the class name
(without the .class extension).
Example D:\Education\programs > java HelloWorld
2. You should see the output in the terminal:
Hello, World!
1.6. The Building blocks of a Java program
1. Lexical Tokens
a. Identifiers
b. Keywords
2. Literals
a. Integer Literals
b.Floating-Point Literals
c.Boolean Literals
d.Character Literals
e.String Literals
3. White Spaces
4. Comments
1. Lexical tokens
• A lexical token may consist of one or more characters, and every single
character is in exactly one token.
• The tokens can be keywords, comments, numbers, white space, or strings. All lines
should be terminated by a semi-colon (;).
a. Identifiers
✓ Identifier is a name chosen by the programmer to identify something defined inside a
program. There are some rules in Java that must be follow to form the identifier name.
✓ An identifier must begin with a letter (A-Z or a-z), an underscore (_), or a dollar sign
($). It cannot start with a digit.
✓ After the first character, identifiers can include letters, digits, underscores, and dollar
signs.
✓ Java identifiers are case-sensitive. This means that 'var' and 'Var' would be considered
different identifiers.
✓ Identifiers cannot be any of Java's reserved keywords (like int, class, public, etc.).
b. Keywords
✓ Keywords have special meaning in a programming language.
✓ It is also known as Reserved Words
✓ You cannot use a keyword as identifier (keywords are reserved for a specific
purpose!)
abstract continue for new switch case try
extends default goto* package synchronized enum**** catch
boolean do if private this instanceof char
Break double implements protected throw return final
Byte else import public throws transient interface
Class finally long strictfp** volatile int static
const* float native super while short void
2. Literals
• A literal is a source code representation of a fixed value.
• They are represented directly in the code without any computation.
• Literals can be assigned to any primitive type variable.
a. Integral Literals in Java
We can specify the integer literals in 4 different ways –
a. Decimal (Base 10)
Digits from 0-9 are allowed in this form. int x = 101;
b. Octal (Base 8)
Digits from 0 – 7 are allowed. It should always have a prefix 0.
int x = 0146;
c. Hexa-Decimal (Base 16)
Digits 0-9 are allowed and also characters from a-f are allowed in this form.
Furthermore, both uppercase and lowercase characters can be used.
int x = 0X123Face;
b. Boolean Literals in Java
They allow only two values i.e. true and false.
boolean b = true;
c. Floating-Point Literals in Java
Here, datatypes can only be specified in decimal forms and not in octal/hexadecimal.
Every floating type is a double type and this the reason why we cannot assign it
directly to float variable, to escape this we use f or F as suffix, and for double we use
d or D.
d. Char Literals in Java
There are the four types of char literals in Java
i. Single quote
- Java Literal can be specified to a char data type as a single character within
a single quote.
char ch = 'a';
ii. Char literal
- A char literal in Java can specify as integral literal which also represents
the Unicode value of a character.
- Furthermore, an integer can specify in decimal, octal and even
hexadecimal type, but the range is 0-65535.
char ch = 062;
iii. Escape sequences
- A character preceded by a backslash (\) is an escape sequence and has a
special meaning to the compiler.
- The following table shows the Java escape sequences.
Escape
Description
Sequence
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
Inserts a single quote character in the text at this
\'
point.
Inserts a double quote character in the text at this
\"
point.
\\ Inserts a backslash character in the text at this point.
iv. Unicode representation
- Char literals can specify in Unicode representation ‘\uxxxx’. Here
XXXX represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
v. String literals in Java
Java String literals are any sequence of characters with a double quote.
String s = "Hello";
They may not contain unescaped newline or linefeed characters.
3. White Spaces
• White space can contain the characters for tabs, blanks, newlines, and form feeds.
• These characters are ignored except when they serve to separate other tokens.
• However, blanks and tabs are significant in strings.
4. Comments
• A text inside a Java program that is ignored by the Java compiler.
• Comments are used to annotate the program to help humans understand the
operation of the Java program.
Single line comment syntax:
// ... single line comment
The text on the line following the symbol // will be ignored
Multiple lines comment syntax:
/* comment line 1
comment line 2
...
*/
All text between the comment brackets /* . */ will be ignored
Data Types in Java
• Data types specify the different sizes and values that can be stored in the variable.
• 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.
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.
✓ Java is a statically-typed programming language. It means, all variables must
be declared before its use. That is why we need to declare variable's type and name.
✓ There are 8 types of primitive data types:
1. boolean data type
• The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.
2. byte data type
▪ It is an 8-bit signed two's complement integer. Its value-range lies between -
128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127.
▪ Its default value is 0. It saves space because a byte is 4 times smaller
than an integer.
3. char data type
▪ It is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
4. short data type
▪ It is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767.
▪ Its default value is 0. A short data type is 2 times smaller than an integer.
5. int data type
▪ It is a 32-bit signed two's complement integer.
▪ Its value-range lies between - 2,147,483,648 to 2,147,483,647. Its minimum
value is - 2,147,483,648 and maximum value is 2,147,483,647. Its default
value is 0.
6. long data type
▪ It is a 64-bit two's complement integer.
▪ Its value-range lies between minimum value is 9,223,372,036,854,775,808
and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
▪ The long data type is used when you need a range of values more than
those provided by int.
7. float data type
▪ It is a single-precision 32-bit IEEE 754 floating point. Its value range
is unlimited.
▪ Its default value is 0.0F.
8. double data type
▪ It is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. Its default value is 0.0d.
Data Type Default Value Default size Example
Boolean False 1 bit Boolean one = false
char '\u0000' 2 byte char letterA = 'A'
byte 0 1 byte byte a = 10, byte b = -20
short 0 2 byte short s = 10000, short r = -5000
int 0 4 byte int a = 100000, int b = -200000
long 0L 8 byte long a = 100000L, long b = -
200000L
float 0.0f 4 byte float f1 = 234.5f
double 0.0d 8 byte double d1 = 12.3
1.7. Variables in Java
Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
Types of Variables:
There are three types of variables:
1. Local Variables
2. Instance Variables
3. Static or Class variables
1. Local Variables
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
2. Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created.
3. Static or Class variables
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory.
1.8. Conversion and Casting features
Casting is a mechanism of converting the value of an object or primitive type into another
type. There are three forms of casts and conversions in java:
1. Casting Primitive Types
2. Casting Objects: an instance of a class to an instance of another class
3. Converting primitive types to objects and vice versa.
1. Casting Primitive Types
In Java, casting primitive types allows you to convert values from one primitive type to
another. This process can be categorized into two main types: widening
casting and narrowing casting.
Implicit casting, also known as widening conversion, occurs automatically when
you assign a smaller data type to a larger. This type of casting is safe and does not result in
data loss.
• byte → short → int → long → float → double
• char → int → long → float → double
Example: int a = 50;
double p = a; // int to double (widening)
Explicit casting, also known as narrowing conversion, requires manual conversion
because it may result in a loss of data. This type of casting occurs when converting from a
larger type to a smaller type, and it requires using parentheses with the target type.
Example: double val = 50.7;
int res = (int) val; // Explicit casting from double to int
2. Casting Objects
In Java, casting objects is a fundamental concept that allows developers to convert an
object from one class type to another, possible only when there is a valid inheritance
relationship between the classes involved. This process can be categorized into two main
types: upcasting and downcasting.
Upcasting (Implicit Casting) is casting a subclass object to a superclass reference.
This happens automatically because it moves from a more specific type to a more general
type, making it a safe conversion.
Downcasting (Explicit Casting) is the process of casting a superclass reference back
to a subclass type. This requires an explicit cast and can lead to a ClassCastException if the
object being cast is not an instance of the target subclass. Therefore, it’s essential to check the
object's type using the instanceof operator before performing downcasting.
To cast an object explicitly as: (classname) object;
Here’s a example of a cast of an instance of the class GreenApple to an instance of the class
Apple (where GreenApple is theoretically a subclass of Apple):
GreenApple ga;
Apple ap;
ga = new GreenApple(); //Implicit casting
ap = (Apple) ga; // Explicit casting
3.Converting primitive types to objects and vice versa.
In Java, converting primitive types to objects and vice versa is known as boxing and
unboxing. Java provides wrapper classes for each primitive type to support this, allowing
primitives to be used in contexts that require objects, like in collections (ArrayList, HashMap,
etc.).
Boxing is the process of converting a primitive type into its corresponding wrapper
class object. Java supports autoboxing, which means that the conversion from primitive to
wrapper class happens automatically.
Example:
int num = 5;
Integer numObject = num; // Autoboxing from int to Integer
System.out.println(numObject); // Output: 5
Unboxing is the reverse of boxing; it converts a wrapper class object back to its
corresponding primitive type. Java supports auto-unboxing, meaning the conversion from
wrapper object to primitive is automatic.
Example:
Integer numObject = 10;
int num = numObject; // Auto-unboxing from Integer to int
System.out.println(num); // Output: 10
1.9. Conditional statements
Control statements in Java are essential constructs that manage the flow of program execution
based on specific conditions. They allow developers to implement decision-making, looping,
and control transfer mechanisms within their code.
Java's control statements can be categorized into three main types:
1. Decision-Making Statements
2. Looping Statements
3. Jump Statements
1.9.1 Decision-Making Statements
These statements allow a program to choose different paths of execution based on conditions.
The primary decision-making statements in Java include:
• if Statement: The Java if statement tests the condition. It executes the if block if
condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Example: //Java Program to demonstate the use of if statement.
public class IfExample
{
public static void main(String[] args){
int age=20;
if(age>18) //checking the age {
System.out.print("Age is greater than 18");
}
}
}
• if-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.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example: //A Java Program to demonstrate the use of if-else statement.
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0) //Check if the number is divisible by 2 or not
System.out.println("even number");
else
System.out.println("odd number");
}
}
• if-else-if ladder: The if statements are executed in a sequential manner, as soon as
one of the conditions of if is true, the statements associated with that if is executed
and rest of ladder is bypassed. If none of the condition is true, then final else
statement will be executed.
Syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if none of the above conditions are true
}
Example: //A Java Program to demonstrate the use of if-else ladder.
public class GradeCalculator {
public static void main(String[] args) {
int marks = 75;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else if (marks >= 50) {
System.out.println("Grade D");
} else {
System.out.println("Fail");
}
}
}
• Switch Statement: Java has a built-in multiway decision statement known as switch.
The switch statement tests the value of a given variable (or expression) against a list
of case values and when a match is found, a block of statements associated with that
case is executed.
Syntax:
switch (variable) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
.
.
default:
// default code
}
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20; //Declaring a variable for switch expression
switch(number)
{
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
1.9.2 Looping Statements
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true.
There are three types of loops in Java.
1. while loop
2. do…while loop
3. for loop
• while loop: The while loop repeats a statement or block till its controlling expression
is true. The body of the loop will be executed as long as the conditional expression is
true.
Syntax:
while(condition)
{
//code to be executed
}
Example
public class WhileExample
{
public static void main(String[] args) {
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
• do...while loop: Each iteration of the do-while loop first executes the body of the loop
and then evaluates the conditional expression. If this expression is true, the loop will
repeat otherwise, the loop terminates. The do-while loop always executes its body at
least once, because its conditional expression is at the bottom of the loop.
Syntax:
do
{
//code to be executed
}while(condition);
Example:
public class DoWhileExample
{
public static void main(String[] args) {
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
• for loop: The Java for loop is used to iterate a part of the program several times. If the
number of iterations is fixed, it is recommended to use for loop.
It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts.
2. Condition: It is the second condition which is executed each time to test the
condition of the loop. It continues execution until the condition is false.
3. Statement: The statement of the loop is executed each time until the condition is
false.
4. Increment/Decrement: It increments or decrements the variable value.
Syntax:
for(initialization; condition; incr/decr)
{
//statement or code to be executed
}
Example:
public class ForExample
{
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
• for each loop: The for-each loop, also known as the enhanced for loop, is a
convenient way to iterate over elements in arrays and collections in Java.
Syntax:
for (dataType item : collection) {
// Code to be executed for each item
}
Example : //Iterating Over an Array
public class ForeachDemo {
public static void main(String[] args) {
int[] numbers = {3, 9, 5, -5};
// Using for-each loop to print array elements
for (int number : numbers) {
System.out.println(number);
}
}
}
1.9.3 Jump Statements
Jump statements alter the flow of control within loops or methods. They include:
• break Statement: The break statement breaks or terminates the loop and transfers the
control outside the loop.
• continue Statement: The continue statement skips the current iteration of a loop and
proceeds to the next iteration.
• return Statement: Exits from the current method and optionally returns a value.
1.10. Arrrays
Arrays are used to store multiple values in a single variable. In java, Array is an object which
contains elements of a similar data type. The elements of an array are stored in a contiguous
memory location. Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on the 1st index, and so on.
Java supports different types of arrays such as one-dimensional arrays and two-
dimensional arrays
1.10.1 One-dimensional (1D) Arrays
A list of similar items represented by a single variable_name using only one subscript
is called 1D array.
To create an array in Java, you use three steps:
1. Declaring an Array
2. Create a new array object.
3. Initializing an Array
1. Declaring an Array
To declare an array, define the variable type with square brackets [] after the type, followed
by the name of the identifier. (or) define the variable type and the name of the array, followed
by empty brackets ([])
Syntax: dataType[] arr; (or) dataType arr[];
Example: int [] marks; (or) int marks[];
2. Create a new array object.
The second step is to create an array object and assign it to that variable. The new keyword is
used for creating an array, which is followed by the number of elements to be contained in
that array (in square brackets).
Syntax: arrayRefVar = new datatype[size];
Example: marks = new int[5];
Here, the name of the array is marks, which is of size (index value) 5.
Note: you can combine declaration and instantiation as: int marks[]=new int[5];
3. Initializing an Array
When you create an array object using new, all its elements are initialized to default values.
(0 for numeric arrays, false for boolean, ‘\0’ for character arrays, and null for everything
else). You can also create and initialize an array at the same time.
Example: int[] marks={85,76,88,91};
Each of the elements inside the braces must be the same type as the variable that holds
that array. An array of size as the number of elements you’ve included is created.
Example: //Java Program to illustrate how to declare, instantiate, initialize and traverse the
Java array.
class Testarray {
public static void main(String args[]) {
int a[]=new int[5]; //declaration and instantiation
a[0]=10; a[1]=20; a[2]=70; a[3]=40; a[4]=50; //initialization
for(int i=0; i<a.length; i++) //length is the property of array
System.out.println(a[i]);
}
}
Two-dimensional (2D) Arrays
In this case, data is stored in row and column-based index (also known as matrix form).
Syntax: dataType[][] arrayRefVar; (or) dataType arrayRefVar[][];
Example: int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java: arr[0][0]=1; arr[0][1]=2;
Example ://Java Program to illustrate the use of multidimensional array
class Testarray3
{
public static void main(String args[]) {
//declaring and initializing 2D array
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++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
1.11. Strings
• A string is a sequence of characters but it’s not a primitive type. When we create a
string in java, it creates an object of type String.
• A string is an immutable object which means that it cannot be changed once it is
created. Whenever a change to a String is made, an entirely new String is created.
• A Stringvariable contains a collection of characters surrounded by double-quotes.
The following are the ways to create a string object:
1.Using string literal.
2.Using a new keyword.
Using string literal
This is the most common way of creating a string. In this case, a string literal is enclosed with
double-quotes.
Syntax: String var_name=“value”
Example: String str = "abc";
Using new keyword
We can create String object using new operator, just like any normal java class. There are
several constructors available in String class to get String from char array, byte array,
StringBuffer and StringBuilder.
Example:
String str = new String("abc");
char[ ] chArr = {'a', 'b', 'c'};
String str2 = new String(chArr);
String Methods
A String in Java is an object, which contains methods that can perform certain operations on
strings. which are as follows:
s.no Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
static String format(String format, Object...
3 returns a formatted string.
args)
static String format(Locale l, String format,
4 returns formatted string with given locale.
Object... args)
5 String substring(int beginIndex) returns substring for given begin index.
String substring(int beginIndex, int returns substring for given begin index and end
6
endIndex) index.
returns true or false after matching the sequence of
7 boolean contains(CharSequence s)
char value.
8 boolean equals(Object another) checks the equality of string with the given object.
9 boolean isEmpty() checks if string is empty.
10 String concat(String str) concatenates the specified string.
11 int indexOf(int ch) returns the specified char value index.
returns the specified char value index starting with
12 int indexOf(int ch, int fromIndex)
given index.
13 int indexOf(String substring) returns the specified substring index.
returns the specified substring index starting with
14 int indexOf(String substring, int fromIndex)
given index.
15 String toLowerCase() returns a string in lowercase.
16 String toLowerCase(Locale l) returns a string in lowercase using specified locale.
17 String toUpperCase() returns a string in uppercase.
18 String toUpperCase(Locale l) returns a string in uppercase using specified locale.
19 String trim() removes beginning and ending spaces of this string.
converts given type into string. It is an overloaded
20 static String valueOf(int value)
method.
String Concatenation
• Strings are more commonly concatenated with the + operator
• The + operator can be used between strings to combine them.
Example:
"Hello," + " world" + "!“ results in −"Hello, world!"
//java program of concatenating strings
public class StringDemo {
public static void main(String args[]) {
String string1 = "Polytechnic ";
System.out.println("Govt " + string1 + "C.M.E");
}
}
You can also use the concat() method with string literals for concatenation.
Syntax: string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
Example: "My name is ".concat("RAMU");
Finding a Character in a String
The indexOf() method returns the index (the position) of the first occurrence of a specified
text in a string (including whitespace).
Example:
public class Main {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
Output: 7 //Java counts positions from zero. 0 is the first position in a string.
String equals()
The java string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched,it returns
true.
Example:
public class EqualsExample
{
public static void main(String args[]) {
String s1="polytechnic";
String s2="polytechnic";
String s3="POLYTECHNIC";
String s4="python";
System.out.println(s1.equals(s2));//true because content & case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}
}
String length()
The accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.Methods used to obtain information about
an object are known as accessor methods.
Example:
public class Main {
public static void main(String[] args) {
String txt = "APPLE";
System.out.println("The length of the txt string is: " + txt.length());
}
}
Output: 5
1.12. Objects and Classes
Everything in Java is associated with classes and objects, along with its attributes and
methods. For example, in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
A Class is like a "blueprint" for creating objects.An entity that has state and behavior is
known as an object.
Example: Pen is an object. Its state include name is Reynolds, color is white. Its behavior is
writing.
What is a class in Java?
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Syntax to declare a class:
class <class_name>
{
field;
methods;
}
Example:
class Box{
double width, height, depth; //fields
double volumeBox(){
return width*height*depth; //methods
}
}
What is Object in java?
An object is a runtime entity. The object is an entity which has state and behavior. The object
is an instance of a class.
How to create an object?
Objects are created by new keyword in Java. The primary purpose of the new keyword is to
create an instance of a class. When you use new, it allocates memory for the object and
invokes the constructor of the class to initialize that object.
Syntax to create an object:
Classname Object_name = new classname();
Example:
Box b1=new Box() // Box class name and b1 object name
Multiple objects can be created as
Box b1=new Box(), b2=new Box(); //creating two objects
Object and Class Example1:
In this example, we have created a Student class which has two data members, id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
public class Student
{
int id; //field or data member or instance variable
String name;
public static void main(String args[]) //main method inside the Student class
{
Student s1=new Student(); //creating an object of Student
s1.id=101; // Initializing an object through a reference variable
s1.name="SreeRam";
System.out.println(s1.id); //Printing values of the object
System.out.println(s1.name); //accessing member through reference variable
}
}
Object and Class Example2:
class Student
{
int id; //field or data member or instance variable
String name;
}
public class TestStudent
{
public static void main(String args[])
{
Student s1=new Student(); //creating an object of Student
s1.id=101; // Initializing an object through a reference variable
s1.name="SreeRam";
System.out.println(s1.id); //Printing values of the object
System.out.println(s1.name); //accessing member through reference variable
}
}
1.13. Method in java
In Java, a method is a block of code that performs a specific task and is defined within a
class.Methods are fundamental to organizing code, promoting reusability, and enhancing the
structure of Java programs. A method generally consists of:
Access Modifier: Defines the visibility of the method (e.g., public, private, protected).
Return Type: Indicates the type of value the method returns (e.g., int, void).
Method Name: A unique identifier for the method.
Parameter List: Optional input values that the method can accept.
Method Body: Contains the block of code executed when the method is called. The code
resides within { }.
Syntax:
accessModifier returnType methodName(parameterType1 parameterName1, parameterType2
parameterName2, ...)
{
// Method body - statements to perform a specific task
// Return statement (optional)
}
Example:
public class Calculator {
// Method to add two numbers
public int add(int a, int b) {
int result = a + b;
return result; // Returning the sum
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = calc.add(5, 10); // Calling the add method
System.out.println("Sum: " + sum); // Output: Sum: 15
}
}
1.13.1 Method Overloading
• Java allows multiple methods with the same name but different parameter lists. This is
known as method overloading and provides flexibility in method usage.
• Java differentiates overloaded methods based on the number and type of parameters
and not on the return type of the method.
• A compiler error would occur when two methods with the same name and same
parameter list but different return types are created.
Example ://java program to implement method overloading.
public class MethodOverloading {
void display(int a){
System.out.println("Arguments: " + a);
}
//Overloading by changing the number of parameters
void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
//Overloading by changing the data type of parameters
void display(String a){
System.out.println("Arguments: " + a);
}
//Overloading by mix of both
void display(int a, String s,int b){
System.out.println("Arguments: " + a + s + b);
}
public static void main(String[] args) {
MethodOverloading m= new MethodOverloading();
m.display(1);
m.display(2, 4);
m.display("hello");
m.display(3," world ",5);
}
}
1.14. Constructor
In Java, a constructor is a special method that is called when an object of a class is created.
Constructors are used to initialize the object's attributes. Key features of Constructors are:
• The name of the constructor must be identical to the class name.
• Constructors do not have a return type, not even void.
• A constructor is automatically invoked when an object is instantiated using the new
keyword.
Types of Constructors
There are primarily two types of constructors in Java:
1. Default Constructor (No-Argument Constructor): This constructor does not take
any parameters. If no constructor is defined in a class, Java automatically provides a
default constructor that initializes instance variables with default values (e.g., 0, null).
Example:
public class DefaultConstructor {
int num;
// Default constructor
public DefaultConstructor() {
num = 10; // Initialize num
}
public static void main(String[] args) {
DefaultConstructor obj = new DefaultConstructor();
System.out.println("Value of num: " + obj.num); //
}
}
Output:
Value of num: 10
2. Parameterized Constructor: This type of constructor accepts parameters to initialize
an object with specific values.
Example:
public class ParameterizedConstructor {
int num1, num2;
// Parameterized constructor
public ParameterizedConstructor(int a, int b) {
num1 = a;
num2 = b;
}
public static void main(String[] args) {
ParameterizedConstructor obj = new ParameterizedConstructor(5, 10);
System.out.println("num1: " + obj.num1 + ", num2: " + obj.num2);
}
}
Output:
num1: 5, num2: 10
1.14.1 Constructor Overloading
Java allows multiple constructors in the same class with different parameter lists. This feature
is known as constructor overloading.
Example:
class Box
{
double l;
double w;
double h;
Box() { // Default Constructor
l=1; w=1; h=1;
}
Box(double a) { // Parameter Constructor
l=w=h=a;
}
Box(double len,double wid,double hei) { // Multiple Parameter Constructor
l=len;
w=wid;
h=hei;
}
double volume() {
return(l*w*h);
}
}
public class ConstructorOverloading
{
public static void main(String args[]) {
Box b1=new Box();
Box b2=new Box(4,3,8);
Box b3=new Box(5);
System.out.println("Box1 volume= " +b1.volume());
System.out.println("Box2 volume= " +b2.volume());
System.out.println("Box3 volume= " +b3.volume());
}
}
Output:
Box1 volume= 1.0
Box2 volume= 96.0
Box3 volume= 125.0
1.15. this Keyword
The this keyword in Java is a reference variable that refers to the current object within an
instance method or constructor. It is commonly used to resolve naming conflicts between
instance variables and parameters when they share the same name.
Common Uses of this Keyword
1. To Refer to Instance Variables
2. To Call Another Constructor (Constructor Chaining)
3. To Pass the Current Object as a Parameter
4. To Returning Current Object
1. Using this to Refer to Instance Variables: When constructor or method parameters have
the same name as instance variables, this is used to refer to the instance variables to avoid
ambiguity.
Example:
public class Person {
String name;
int age;
// Constructor with parameters having the same name as instance variables
public Person(String name, int age) {
this.name = name; // 'this.name' refers to the instance variable, 'name' refers to the
parameter
this.age = age; // 'this.age' refers to the instance variable, 'age' refers to the parameter
}
public void displayInfo() {
System.out.println("Name: " + this.name + ", Age: " + this.age);
}
public static void main(String[] args) {
Person person = new Person("Alice", 25);
person.displayInfo();
}
}
Output:
Name: Alice, Age: 25
2. Using this to Invoking another Constructors: ‘this()’ can also be used to call another
constructor in the same class, known as constructor chaining.
Example:
class Circle {
double radius;
Circle() {
this(1.0); // Calls the parameterized constructor with default radius
}
Circle(double radius) {
this.radius = radius; // Initialize radius
}
}
public class CircleTest {
public static void main(String[] args) {
Circle defaultCircle = new Circle(); // Calls default constructor
Circle customCircle = new Circle(5); // Calls parameterized constructor
System.out.println("Default Circle Radius: " + defaultCircle.radius);
System.out.println("Custom Circle Radius: " + customCircle.radius);
}
}
Output:
Default Circle Radius: 1.0
Custom Circle Radius: 5.0
3. Using this to Pass the Current Object as a Parameter: ‘this’ can also be used to pass the
current object to another method, which is helpful in cases like event handling, callbacks, or
passing the current object to another method in a different class.
Example:
class Employee {
String name;
Employee(String name) {
this.name = name;
}
void display(Employee emp) {
System.out.println("Employee Name: " + emp.name);
}
void show() {
display(this); // Passes the current object
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee emp = new Employee("Alice");
emp.show();
}
}
Output:
Employee Name: Alice
4. Using this to Returning Current Object: A method can return the current object using
this.
Example:
class Sample {
int value;
Sample(int value) {
this.value = value;
}
Sample getObject() {
return this; // Returns the current object
}
}
public class SampleTest {
public static void main(String[] args) {
Sample obj = new Sample(10);
Sample returnedObj = obj.getObject();
System.out.println("Returned Object Value: " + returnedObj.value);
}
}
Output:
Returned Object Value: 10
1.16. static keyword
In Java, the static keyword is used to create variables, methods, and blocks that belong to the
class itself rather than to instances of the class. This means that static members are shared
across all instances of the class. Let's look at how static works with variables, methods, and
blocks.
1. Static Variables:
Static variables are class-level variables that are shared among all instances of a class.
Static variables are also known as class variables. They are initialized only once at the start of
the execution and retain their values throughout the program.
Example:
public class Counter {
// Static variable to keep count of instances
static int count = 0;
// Constructor increments the count each time an object is created
Counter() {
count++;
}
void displayCount() {
System.out.println("Count: " + count);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
c3.displayCount();
}
}
Output:
Count: 3
2. Static Methods:
A static method belongs to the class and can be called without creating an instance of
the class. Static methods can access only static variables and cannot refer to this or non-
static variables.
Example:
public class MathUtility {
// Static method for addition
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result;
result = MathUtility.add(10, 20); // Calling static method without an instance
System.out.println("Result: " + result);
}
}
Output:
Result: 30
3. Static Blocks:
A static block is a block of code that runs when the class is loaded into memory, and
it’s executed only once. Static blocks are mainly used for initialization of static variables or to
perform actions that need to happen only once, regardless of the number of instances created.
Example:
public class DatabaseConfig {
public static String url;
// Static block for initialization
static {
url = "jdbc:mysql://localhost:3306/mydb";
System.out.println("Static block executed. Database URL initialized.");
}
public static void main(String[] args) {
System.out.println("Database URL: " + DatabaseConfig.url);
}
}
Output:
Static block executed. Database URL initialized.
Database URL: jdbc:mysql://localhost:3306/mydb
1.17. Command-Line Arguments
Command-line arguments are values provided to the main method when a Java program is
executed. These arguments are passed to the main method as a String array (String[] args).
The main method in Java is defined as:
public static void main(String[] args)
Here, args is an array of String values that holds the command-line arguments passed to the
program.
Important Points about Command-Line Arguments
• Array Indexing: args[0] represents the first argument, args[1] the second, and so on.
• Length: Use args.length to check the number of arguments provided.
• Data Types: Arguments are always received as strings, so you may need to parse them
to other types (e.g., Integer.parseInt(args[0]) for an integer).
How to Pass Arguments
When running a Java program from the command line, you can specify arguments after the
class name:
java ClassName arg1 arg2 arg3
Example:
public class SumNumbers {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum= " + sum);
}
}
Usage
Run with two arguments: java SumNumbers 3 5
Output: Sum= 8
1.18. mmm
1.19. kkk