0% found this document useful (0 votes)
37 views65 pages

Java Unit 1

Uploaded by

kanhu polai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
37 views65 pages

Java Unit 1

Uploaded by

kanhu polai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 65

Unit – I 10 hours

Introduction to Java Programming, Concept of JVM, Data Types and Operations,


Structured Programming, Selection Statements, Loops, Methods, Method Abstraction and
Stepwise Refinement, Arrays, Classes and Objects, Constructors, Implementing &
Designing Classes, Use of Keywords: static, final, this, Class Abstraction and
Encapsulation, Strings and Text I/O

What is Java?

Java is a platform independent, High level, robust, object-oriented and secure


programming language. Java is general-purpose programming language made for
developers write once, and run anywhere (WORA), meaning that compiled Java code can
run on all platforms that support Java without the need for recompilation. Java
applications are compiled to byte code that can run on any Java Virtual Machine.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.

There are many devices where Java is currently used. Nearly 3 billion devices are running in
Java. Some of them are Desktop Applications, Web Applications like IRCTC, Enterprise
Applications such as banking applications, Mobile, Embedded System, Smart Card,
Robotics, Games, etc.

Java Platforms:

1) Java SE (Java Standard Edition): It is a Java programming platform. It includes Java


programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It
includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition): It is an enterprise platform that is mainly used to


develop web and enterprise applications. It is built on top of the Java SE platform. It includes
topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition): It is a micro platform that is dedicated to mobile


applications.

4) JavaFX: It is used to develop rich internet applications. It uses a lightweight user interface
API.

Features of Java: The primary objective of Java programming language creation was to
make it portable, simple and secure programming language.

Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand.

Object-oriented: Everything in Java is an object. Object-oriented means we organize our


software as a combination of different types of objects that incorporate both data and
behaviour. Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are: Object, Class, Inheritance, Polymorphism, Abstraction,
Encapsulation

Platform Independent: Java is platform independent, which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the
hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
o Runtime Environment
o API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).

Secured: Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because No explicit pointer and Java Programs run inside a virtual
machine sandbox

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust: The English mining of Robust is strong. Java is robust because:


o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get
rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.

Architecture-neutral: Because there are no implementation dependent features, for


example, the size of primitive types is fixed.

Portable: It facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.

High-performance: Java is faster than other traditional interpreted programming languages


because Java bytecode is "close" to native code.

Distributed: 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.

Multi-threaded: A thread is like a separate program, executing concurrently. We can write


Java programs that deal with many tasks at once by defining multiple threads. Threads are
important for multi-media, Web applications, etc.
Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

Example: MyFirst.java
class MyFirst{
public static void main(String args[]){
System.out.println("Hello World");
} }
Save the above file as MyFirst.java.
To compile: javac MyFirst.java
To execute: java MyFirst
Output: Hello World

Compilation Flow: When we compile Java program using javac tool, the Java compiler
converts the source code into byte code.
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to invoke
the static method. The main() method is executed by the JVM, so it doesn't require creating
an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of
the PrintStream class, println() is a method of the PrintStream class.

Java JDK, JRE and 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 (set of instructions that a
computer's CPU executes directly).

Java is a platform-independent language. It's because when you write Java code, it's
ultimately written for JVM but not your physical machine (computer). Since JVM executes
the Java bytecode which is platform-independent, Java is platform-independent. Working of
Java Program-

The JVM performs the following main tasks:


 Loads code
 Verifies code
 Executes code
 Provides runtime environment

What is JRE?

JRE (Java Runtime Environment) is a software package that provides Java class libraries such
as java.lang, java.util, java.math, etc. and Java Virtual Machine (JVM) and other components
that are required to run Java applications. JRE is the superset of JVM.

What is JDK?

JDK (Java Development Kit) is a software development kit required to develop applications
in Java. When you download JDK, JRE is also downloaded with it. JDK includes the Java
Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), Java Debugger and other tools needed in Java
development.

Relationship between JVM, JRE, and JDK.

Let’s look at some of the important differences between JDK, JRE, and JVM.
 JDK is for development purpose whereas JRE is for running the java programs.
 JDK and JRE both contains JVM so that we can run our java program.
 JVM is the heart of java programming language and provides platform independence.

Data Types

In Java, data types play a crucial role in defining the kind of information that can be stored
and manipulated. Data types in Java specify how memory stores the values of the variable.
Each variable has a data type that decides the value the variable will hold. Data types in
Java are all about handling and storing data. Java data types are divided into two types such
as
 Primitive Data Types
 Non-Primitive Data Types

 Primitive Data Types: There are 8 Primitive data types in Java – Boolean, char, byte,
int, short, long, float, and double.
o Boolean type (Boolean): A boolean data type can store either True or False. They can
be used to check whether two values are equal or not (basically in conditional
statements to return True or False). Typically, programmers use it as a flag variable to
track true or false conditions. The default boolean value is False.

o Character type (char): The char data type stores a single character. It stores lowercase
and uppercase characters, which must be enclosed in single quotes. The char data type
in Java supports Unicode characters and provides provision to multiple languages like
English, French, German, etc.
o Integer type: An integer type stores an integer number with no fractional or decimal
places. Java has four integer types – byte, short, int, and long.
o Byte: The byte is the smallest data type among all the integer data types. It is an 8-bit
signed two’s complement integer..
Syntax: byte byteVariable;
o Short: Short is a 16-bit signed two’s complement integer.
Syntax: short shortVariable;
o Int: Int is a 32-bit signed two’s complement integer that stores integral values.
Syntax: int intVariable;
o Long: long is a 64-bit signed two’s complement integer that stores values. This data type
ends with ‘L’ or ‘l’.
Syntax: long longVariable;
o Float type –Floating-point is used for expressions involving fractional precision. It
has two types: float and double.
o Float: It is a floating-point data type that stores the values, including their decimal
precision.
Syntax: float floatVariable;
o Double: The double data type is similar to float. The difference between the two
is that is double twice the float in the case of decimal precision.
Syntax: double doubleVariable;

Primitive Data Types Default Value, Size and its Range

Data Default
Default size Range
Type Value

byte 0 1 byte or 8 bits -128 to 127

short 0 2 bytes or 16 bits -32,768 to 32,767

int 0 4 bytes or 32 bits 2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to
long 0L 8 bytes or 64 bits
9,223,372,036,854,775,807

float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038

double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308

char ‘\u0000’ 2 bytes or 16 bits 0 to 65536

boolean FALSE 1 byte or 2 bytes 0 or 1

 Non-Primitive Data Types: Non-primitive data types or reference data types refer to
instances or objects. They cannot store the value of a variable directly in memory. They
store a memory address of the variable. Programmers create them and can be assigned
with null. All non-primitive data types are of equal size.

o Array: An array holds elements of the same type. It is an object in Java, and the array
name (used for declaration) is a reference value that carries the base address of the
continuous location of elements of an array.

Example: int Array_Name = new int[7];

o String: The String data type stores a sequence or array of characters. A string is a
non-primitive data type, but it is predefined in Java. String literals are enclosed in
double quotes.
o Class: A class is a user-defined data type from which objects are created. It describes
the set of properties or methods common to all objects of the same type. It contains
fields and methods that represent the behaviour of an object. A class gets invoked by
the creation of the respective object.
o Interface: An interface is declared like a class. The key difference is that the interface
contains abstract methods by default; they have nobody.
o Enum: An enum, similar to a class, has attributes and methods. However, unlike
classes, enum constants are public, static, and final (unchangeable – cannot be
overridden). Developers cannot use an enum to create objects, and it cannot extend
other classes. But, the enum can implement interfaces.
//declaration of an enum
enum Level {
LOW,
MEDIUM,
HIGH
} Java operators

Operators in Java, a Java toolkit, are being used as a symbol that performs various operations
according to the code. Some Operators of JAVA are "+","-","*","/" etc. Below are types of
Operators in Java-
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Unary operator
6. Bitwise operator
7. Comparison operator
8. Ternary operator

Arithmetic Operators: Arithmetic Operators in Java are particularly used for performing
arithmetic operations on given data or variables. There are various types of operators in Java,
such as:

Operators Operations

+ Addition

- Subtraction

x Multiplication

/ Division

% Modulus

Assignment Operator: Assignment Operators are mainly used to assign the values to the
variable that is situated in Java programming. There are various assignment operators in Java,
such as:
Operators Examples Equivalent to

= X = Y; X = Y;

+= X += Y; X = X + Y;

-= X -= Y; X = X - Y;

*= X *= Y; X = X * Y;

/= X /= Y; X = X / Y;

%= X %= Y; X = X % Y;

Relational Operators: Java relational operators are assigned to check the relationships
between two particular operators. There are various relational operators in Java, such as:

Operators 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

Logical Operators: Logical Operators in Java check whether the expression is true or false.
It is generally used for making any decisions in Java programming. Not only that but Jump
statements in Java are also used for checking whether the expression is true or false. It is
generally used for making any decisions in Java programming.

Operators Example Meaning

&& [ logical AND expression1 && (true) only if both of the expressions
] expression2 are true

|| [ logical OR ] expression1 || expression2 (true) if one of the expressions in true


Operators Example Meaning

(true) if the expression is false and


! [ logical NOT ] !expression
vice-versa

Unary Operator: Unary Operators in Java are used in only one operand. There are various
types of Unary Operators in Java, such as:

Operators Description

+ Unary Plus

- Unary Minus

++ Increment operator

-- Decrement Operator

! Logical complement operator


Note: x++ is called post increment and ++x is called pre increment
class Main{
public static void main(String[] args) {
int a = 13, b = 13; // declare variables
int result1, result2; // original value
System.out.println("Value of a: " + a);
result1 = ++a; // increment operator also Check a++
System.out.println("After increment: " + result1);
System.out.println("Value of b: " + b);
result2 = --b; // decrement operator also Check b--
System.out.println("After decrement: " + result2);
}}
Output:
Value of a: 13
After increment: 14
Value of b: 13
After decrement: 12

Bitwise Operators: Bitwise Operators in Java are used to assist the performance of the
operations on individual bits.

Operators Descriptions

~ Bitwise Complement
Operators Descriptions

<< Left shift

>> Right shift

>>> Unsigned Right shift

& Bitwise AND

^ Bitwise exclusive OR
class Main {
public static void main(String[] args) {
String str = "ScholarHat";
boolean result;
result = str instanceof String; // checks if str is an instance of the String class
System.out.println("Is str an object of String? " + result);
}}
Output: Is str an object of String? true

Comparison Operators: To compare two values (or variables), comparison operators are
used. This is crucial to programming since it facilitates decision-making and the search for
solutions. A comparison's return value is either true or false. These are referred to as "Boolean
values."

Operators Operations

== Equal to

!= Not equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

public class ComparisonOperatorsExample {


public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
boolean isEqual = (num1 == num2); // Equal to (==) operator
System.out.println("num1 is equal to num2: " + isEqual);
boolean isNotEqual = (num1 != num2); // Not equal to (!=) operator
System.out.println("num1 is not equal to num2: " + isNotEqual);
boolean isGreaterThan = (num1 > num2); // Greater than (>) operator
System.out.println("num1 is greater than num2: " + isGreaterThan);
boolean isLessThan = (num1 < num2); // Less than (<) operator
System.out.println("num1 is less than num2: " + isLessThan);
boolean isGreaterThanOrEqual = (num1 >= num2); // Greater than or equal to (>=)
operator
System.out.println("num1 is greater than or equal to num2: " + isGreaterThanOrEqual);
boolean isLessThanOrEqual = (num1 <= num2); // Less than or equal to (<=) operator
System.out.println("num1 is less than or equal to num2: " + isLessThanOrEqual);
}}
Output
num1 is equal to num2: false
num1 is not equal to num2: true
num1 is greater than num2: false
num1 is less than num2: true
num1 is greater than or equal to num2: false
num1 is less than or equal to num2: true

Ternary Operators: The only conditional operator that accepts three operands is the ternary
operator in Java. Java programmers frequently use it as a one-line alternative to the if-then-
else expression. The ternary operator can be used in place of if-else statements, and it can
even be used to create switch statements with nested ternary operators. The conditional
operator uses less space and aids in writing if-else statements as quickly as possible even if it
adheres to the same algorithm as an if-else statement:
public class TernaryOperatorExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
// Using the ternary operator to find the maximum of two numbers
int max = (num1 > num2) ? num1 : num2;
System.out.println("The maximum number is: " + max);
}}
Output: The maximum number is: 20
Operator Precedence:

Structure of java Program

A Java program typically consists of the following components:


1. Documentation Section
2. Package Declaration
3. Import Statements
4. Interface Section
5. Class Definition
6. Class Variables and Variables
7. Main Method Class
8. Methods and Behaviours

 Documentation Section: The documentation section in the structure of a Java program


serves as a vital but optional part of a Java program, providing essential details about the
program. This includes the author's name, creation date, version, program name, company
name, and a brief description. While these details enhance the program's readability, the
Java compiler ignores them during program execution. To include these details,
programmers typically use comments.
Comments are non-executable parts of a program. A compiler does not execute a comment. It
is used to improve the readability of the code. Writing comments is a good practice as it
improves the documentation of the code. There are three different types of comments- single-
line, multi-line, and documentation comments.
 Single line comment- It is a comment that starts with // and is only used for a single
line.
//Single-line comment
 Multi line comment- It is a comment that starts with /* and ends with */ and is used
when more than one line has to be enclosed as comments.
/* Multiline comment
in Java Program */
 Documentation comment- It is a comment that starts with /** and ends with */
/** Documentation comment */

 Package Declaration: Declaring the package in the structure of Java is optional. It comes
right after the documentation section. You mention the package name where the class
belongs. Only one package statement is allowed in a Java program and must come before
any class or interface declaration. This declaration helps organize classes into different
directories based on the modules they're used in. You use the keyword package followed
by the package name. For instance:
package accountinfo; // accountinfo is the package name
package com. accountinfo; //com is the root directory and accountinfo is the subdirectory
In Java, we have to save the program file name with the same name as the name of public
class in that file.
The above is a good practice as it tells JVM which class to load and where to look for the
entry point (main method).
The extension should be java. Java programs are run using the following two commands:
javac fileName.java // To compile the Java program into byte-code
java fileName // To run the program

 Import Statements: Import statements are used to import classes, interfaces, or enums
that are stored in packages or the entire package. A package contains
many predefined classes and interfaces.
We need to mention which package we are using at the beginning of the program. We do
it by using the import keyword. We either import the entire package or a specific class
from that package.The following is the description of how we can write the import
statement.
import java.util.*; //imports all the classes in util package
import java.util.StringTokenizer; // imports only the StringTokenizer class from util package

 Explanation: We have imported java.util package in the first and second lines we have
imported only the StringTokenizer class from java.util package.
Interface Section: This is an optional section. The keyword interface is used to create an
interface. An interface comprises a set of cohesive methods that lack implementation
details., i.e. method declaration and constants.
interface Code {
void write();
void debug();
}
In the above code, we have defined an interface named Code, which contains two method
declarations, namely write() and debug(), with no method body. The body of abstract
methods is implemented in those classes that implement the interface Code.
Class Definition: This is a mandatory section in the structure of Java program. Each Java
program has to be written inside a class as it is one of the main principles of Object-oriented
programming that Java strictly follows, i.e., its Encapsulation for data security.
There can be multiple classes in a program. Some conventions need to be followed to name a
class. They should begin with an uppercase letter.
class Program{
// class definition
}
 Class Variables and Variables: Identifiers are used to name classes, methods, and
variables. It can be a sequence of uppercase and lowercase characters. It can also contain
'_' (underscore) and '$' (dollar) signs. It should not start with a digit(0-9) and not contain
any special characters.
Variables are also known as identifiers in Java. It is a named memory location which
contains a value. In a single statement, we're able to declare multiple variables of the
same type.
Syntax: <Data-Type> <Variable Name> or <Data-Type> <Variable Name> = value;
Example:
int var=100;
int g;
char c,d; // declaring more than one variable in a statement

Rules for Naming a Variable-


 A variable may contain characters, digits and underscores.
 The underscore can be used in between the characters.
 Variable names should be meaningful and depict the program's logic.
 Variable names should not start with a digit or a special character.

 Main Method Class: This is a compulsory part of the structure of Java program. This is
the entry point of the compiler where the execution starts. It is called/invoked by the Java
Virtual Machine or JVM.
The main() method should be defined inside a class. We can call other functions and
create objects using this method. The following is the syntax that is used to define.
public static void main(String[] args) {
// Method logic
}
 Methods and Behaviours: A method is a collection of statements that perform a specific
task. Method names typically begin with a lowercase letter. It provides the reusability of
code as we write a method once and use it many times by invoking the method. The most
important method is Java's main() method. The following are the important components
of the method declaration.
Modifier- Defines access type, i.e., the method's scope.
The return data type- It is the data type returned by the method or void if does not
return any value.
Method Name- The method names should start with a lowercase letter (convention) and
not be a keyword.
Parameter list- It is the list of the input parameters preceded by their data type within the
enclosed parenthesis. If there are no parameters, you must put empty parentheses ().
Exception list- The exceptions that a method might throw are specified.
Method body- It is enclosed between braces {}. The code to be executed is encapsulated
within them.
Method signature- It contains the method name and a parameter list (number, type, and
order of the parameters). The return data type and exceptions are not a part of it.
Example:
public void add(int a, int b){
int c = a + b;
System.out.println(c);
}
In the above method, we added two numbers passed as parameters and printed the result
after adding them. This is only executed when the method is called.The resulting structure
typically resembles the following format when incorporating the components above into a
Java program.
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception {
System.out.println("Hello, Java!");
}}
Output-Hello, Java!
In the above program, we printed a line on the console using System.out.println(), which
gets displayed after the code is executed.

Selection Statement in Java

In java, selection statements are also known as branching statements or conditional or decision-
making statements. It is used to select part of a program to be executed based on condition.

Selection Statement: These are statements that control programs in java. They are used for
selecting a path of execution if a certain condition is met. Following are the types of selection
statements in java:

 if Statement: if the test expression is true then the statement is executed else the
statement is not executed.

import java.util.Scanner;
public class IfCode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if((n % 2) == 0) {
System.out.println("This is if-block");
System.out.println("The number is divisible by 2");
}
System.out.println("outta if-block");
} }
Output:
Enter a number: 3
outta if-block

 if-else Statement: if the test expression is true then the statement is executed else
statement 2 is executed.

Example:
import java.util.Scanner;
public class IfElseCode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

if((n % 5) == 0) {
System.out.println("Condition is true");
} else {
System.out.println("Condition is false");
}
System.out.println("Outta f-block");
} }
Output:
Enter a number: 10
Condition is true

 Nested if Statement: In this, writing an if statement inside another if statement is called


the next if statement. If the first condition is true, it will check for the second condition
after which the inner block will be executed else not.

Example:
import java.util.Scanner;
public class NestedIfStatementTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n < 100) {
System.out.println("\nGiven number is less than 100");
if (n % 5 == 0)
System.out.println("And it is a factor of 5");
else
System.out.println("Not a factor of 5");
} else
System.out.println("Given number is greater than 100");
System.out.println("\noutta if-block");
} }
Output:
Enter a number: 10
Given number is less than 100
And it is a factor of 5

 if- else if- else Statement: if test expression1 is true then statement 1 is executed else if
test expression2 is true then statement2 is executed else statement3 will be executed.

Example:
import java.util.Scanner;
public class IfElseIfCode {
public static void main(String[] args) {
int n1, n2, n3;
Scanner sc = new Scanner(System.in);
System.out.print("Enter any three number: ");
n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();
if( n1>=n2 && n1>=n3)
System.out.println("\n largest number" + n1) ;
else if (n2>=n1 && n2>=n3)
System.out.println("\nlargest number " + n2) ;
else
System.out.println("\nlargest number" + n3) ;
System.out.println("\noutta if-block");
} }
Output:
Enter any three numbers: 3
2
4
largest number: 4
outta if-block
Example:
public class IfElseIfExample{
public static void main(String[] args) {
int marks = 75;
if (marks > 90){
System.out.println("Excellent");
}
else if (marks > 80){
System.out.println("Very Good");
}
else if (marks > 70){
System.out.println("Good");
}
else if (marks > 60){
System.out.println("Average");
}
else if (marks > 50){
System.out.println("poor");
}
// default statement
else {
System.out.println("Fail");
} }}
Example
public class IfElseIfExample {
public static void main(String args[]){
int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");

} }
}
Output: Its a four digit number
Example: Finding largest of three numbers using if-else..if
public class JavaExample{
public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
System.out.println(num1+" is the largest Number");
else if (num2 >= num1 && num2 >= num3)
System.out.println(num2+" is the largest Number");
else
System.out.println(num3+" is the largest Number");
} }

 Switch Statement: if the value of the expression is matched with value 1, then the
corresponding stmt sequence is executed. If not matched with value 1 then try with the
next case value and so on. If none of the cases match then default stmt is executed. All
cases should be unique. The expression must be of type byte, short, int, or char Each case
value should be literal. Default is not compulsory and can be written anywhere.

switch(expression){
case value1: stmt sequence;
break;
case value2: stmt sequence
break;
.
.
case value: stmt sequence
break;
default: stmt sequence
}

Example:
import java.util.Scanner;
public class SwitchCode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
switch( n ) {
case 0: System.out.println("ITS ZERO") ; break ;
case 1: System.out.println("ITS ONE") ; break ;
case 2: System.out.println("ITS TWO") ; break ;
case 3: System.out.println("ITS THREE") ; break ;
case 4: System.out.println("ITS FOUR") ; break ;
case 5: System.out.println("ITS FIVE") ; break ;
case 6: System.out.println("ITS SIX") ; break ;
case 7: System.out.println("ITS SEVEN") ; break ;
case 8: System.out.println("ITS EIGHT") ; break ;
case 9: System.out.println("ITS NINE") ; break ;
default: System.out.println("Not a single digit number") ;
} }}
Output:
Enter a number: 9
ITS NINE
Example: Write a program to Find week day from day number

Note: Single statement does not require { }, Block of statements require { }


 Ternary Operator: The ternary operator can be used to replace certain types
of if...else statements.

variable = Expression1 ? Expression2: Expression3;


example:
class Main {
public static void main(String[] args) {
int number = 24; // create a variable
if(number > 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
} } }

You can replace this code with

class Main {
public static void main(String[] args) {
int number = 24; // create a variable
String result = (number > 0) ? "Positive Number" : "Negative Number";
System.out.println(result);
} }

example: program to find the largest of 3 numbers using the nested ternary operator.
class Main {
public static void main(String[] args) {
// create a variable
int n1 = 2, n2 = 9, n3 = -11;
// nested ternary operator to find the largest number
int largest = (n1 >= n2) ? ((n1 >= n3) ? n1 : n3) : ((n2 >= n3) ? n2 : n3);
System.out.println("Largest Number: " + largest);
} }
 (n1 >= n2) - first test condition that checks if n1 is greater than n2
 (n1 >= n3) - second test condition that is executed if the first condition is true
 (n2 >= n3) - third test condition that is executed if the first condition is false
Note: It is not recommended to use nested ternary operators. This is because it makes our
code more complex.

Loops in Java

Looping is one of the key concepts behind programming and learning how to use loops in Java
can open up a new world of code. Loops are a block of code that executes itself until the
specified condition becomes false. In this section, we will look in detail at the types of loops
used in Java programming. There are three types of "Loops" in Java.

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

1. For loop: For loop primarily depends on the three major sections index of the control
statement which are the "declaration", "conditions" and "update" statements. This particular
loop statement generates iteration over a "collection of values". That can be the same value or
can be different. For loop is generally used when the user knows the exact number of
iterations.
There are various types of "For loop" which are "Empty For Loop", "Infinite For Loop", and
"For each loop".
Syntax:
for (initialization; termination condition; increment/decrement)
{
//Set of statements to be executed repeatedly
}

Initialization condition: Here, the variable in use is initialized. It is the beginning of a for
loop. An already declared variable can be used or a variable can be declared, local to loop
only.
Test Condition: It is used for testing the exit condition for a loop. It must return a boolean
value. For loop is an entry-controlled loop as the condition is checked before the execution of
the loop statements.
Statement execution: Once the condition is evaluated to be true, the statements in the loop
body are executed.
Update Statement: It is used for updating or incrementing/decrementing the variable for the
next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end
of the for loop.

//Program to print even numbers between 1-10.


class ForLoopDemo {
public static void main(String[] args) {
for (int i=1; i<=10; i++) {
if (i%2==0)
System.out.println(i);
}
System.out.println("Loop Ending");
} }
Output
2
4
6
8
10
Loop Ending
Example: PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
} } }
Output:
*
**
***
****
*****

for-each Loop: The for-each loop is used to traverse array or collection. 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
}
Example: ForEachExample.java
//Java For-each loop example which prints the elements of the array
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78}; //Declaring an array
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
} } }
Output:
12
23
44
56
78

2.While loop: While Loop is also an iteration statement that can iterate over various types of
values. After accepting the condition While loop evaluates it to a "boolean value". Execute a
particular statement or a block of the statement until it generates "false". While loop is used
when the user is not aware of the exact iteration number. There are various types of while loops;
those are "Empty While Loop", and "Infinite While Loops".

Syntax:
//initialization
while (condition) {
//Execute a set of statements
//increment
}
 Test Condition: It is used for testing the exit condition for a loop. It must return a boolean
value. While loop is an entry-controlled loop as the condition is checked before the
execution of the loop statements.
 Statement execution: Once the condition is evaluated to be true, the statements in the loop
body are executed. Normally the statements contain an update value for the variable being
processed for the next iteration.
 Loop termination: When the condition becomes false, the loop terminates marking the
end of the while loop.

Example:
class While_Loop_Demo
{ //print even numbers ranging from 1 to 10
public static void main(String args[])
{
int i = 1; //initialization
while (i<=10) //condition or termination {
if (i%2==0) {
System.out.println(i);
}
i++; //increment
} } }
Output:
2
4
6
8
10
Example: Factorial of a number:
public class Main {
public static void main(String args[]) {
int factorial = 1, number = 5, tempNum = 0;
if (number == 0) {
System.out.println("The factorial of " + number + " is: 1");
}else {
tempNum = number; // Initialization;
while (tempNum != 0) { // Test Expression
factorial = factorial * tempNum;
--tempNum; //Updation;
}
System.out.println("The factorial of " + number + " is: " + factorial);
} } }
Output: The factorial of 5 is: 120

3. Do..while: Do while loop works the same as while loop but it only generates the expression
only after the execution of the code block has been done. The concept of Abstraction in
Java can be applied to understand the Do-While loop better.

This statement first executes the statement under "do" after that it checks the condition of
"while". This statement executes at least once even though the statement generates a "false"
value. Do while loop is an "exit control loop". There is only one type of “Do while loop” which
is called "Infinite Do While Loop".

Statement execution: The loop starts with the execution of the statement(s). There is no
checking of any condition for the first time.
Test Condition: After the statements execution step, the condition is checked for true or
false value. If it is evaluated to be true, the next iteration of the loop starts.
Loop termination: When the condition becomes false, the loop terminates marking the end
of the do...while loop.
Syntax:
do{
//statements to be iterated
} while(conditions);
Example: print even number
class Do_While_Loop_Demo {
//print even number
public static void main(String args[]) {
int i = 1; //initialization
do {
System.out.println(i);
i++; //increment
} while (i%2==0);//condition or termination
} }
Output
1
2
Example : Sum of Positive Numbers
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
// create an object of Scanner class
Scanner input = new Scanner(System.in);
// do...while loop continues
// until entered number is positive
do {
// add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
} while(number >= 0);
System.out.println("Sum = " + sum);
input.close();
} }
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
Infinite loops: An infinite for loop gets created if the for loop condition remains true, or if
the programmer forgets to apply the test condition/terminating statement within the for loop
statement.
Syntax:
for(; ;) {
// body of the for loop.
}
In the above syntax, there is no condition hence, this loop will execute infinite times.
Example:
public class Main {
public static void main(String[] args) {
for (;;) {
System.out.println("Hello World");
} }}
In the above code, we have run the for loop infinite times, so "Hello World" will be displayed
infinitely.
Output
Hello World
Hello World
Hello World
Hello World
Hello World
...
2. Infinite while loop: If the condition of a loop is always true, the loop becomes an infinite
one.
Syntax:
while(true) {
// body of the loop..
}
Example:
public class Main {
public static void main(String[] args) {
String str = "Infinite while loop";
int i = 0;
while (true) {
i++;
System.out.println("i is: " + i);
}
// The return statement may never be reached in an infinite loop.
// return 0; // In Java, return 0 is not applicable for the main method.
}}
Here, the value of i will be printed n number of times due to the absence of a terminating
condition.
Output
i is: 1
i is: 2
i is: 3
i is: 4
i is: 5
...
3. Infinite do...while loop: It gets created when the testCondition remains true.
Syntax:
do {
// body of the loop
}while(true);
Example:
public class Main {
public static void main(String[] args) {
do {
System.out.println("This is an infinite do-while loop.");
} while (true);
// The return statement may never be reached in an infinite loop.
// return 0; // In Java, return 0 is not applicable for the main method.
}}
Output
This is an infinite do-while loop.
This is an infinite do-while loop.
This is an infinite do-while loop.
...
1. Nested for loop: It is any type of loop inside a for loop.

Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
} }}
This Java code generates a pattern of numbers using nested loops. The inner loop j iterates
from 1 to the current value of i, printing numbers and spaces. The outer loop i iterates from 1
to 5, regulating the number of rows. As a result, there is a pattern of numerals rising in each
row, with a new line between each row.
Output
1
12
123
1234
12345

2. Nested While Loop: It is any type of loop inside a while loop.

Example:
public class Main {
public static void main(String[] args) {
int i = 1, j = 1;
while (i <= 3) {
System.out.println("Outer loop iteration " + i);
while (j <= 3) {
System.out.println(" Inner loop iteration " + j);
j++;
}
j = 1; // reset j to 1 for the next iteration of the outer loop
i++;
} }}
The inner loop j iterates within each iteration of the outer loop i, printing "Inner loop
iteration" messages. The outer loop i iterates three times, printing "Outer loop iteration"
messages. After each inner loop is finished, j is reset to 1, resulting in nested iteration.
Output:
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3

3. Nested Do...While Loop: It is a do...while loop inside any do...while loop.

Example:
public class Main {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.println(i + " * " + j + " = " + (i * j));
j++;
} while (j <= 10);
i++;
} while (i <= 2);
}}
The above code creates and outputs multiplication tables of 1 and 2 from 1 to 10 using
a nested loop structure. It iterates over the values of i (1 and 2) and j (1 to 10), outputting the
result of i * j after each iteration using two nested do...while loops.
Output
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1 * 10 = 10
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

4. Nested while and for loop: Example of Nested while and for loop in Java in Java Online
Compiler
public class NestedLoopsExample {
public static void main(String[] args) {
int rows = 5;
// Nested for loop
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
int num = 1;
int col = 1;
// Nested while loop
while (col <= i) {
System.out.print(num + " ");
num++;
col++;
}
System.out.println();
} } }
This Java program generates a triangle pattern with numbers increasing sequentially from 1
to the row number. The outer loop is a for loop, while the inner loop is a while loop,
demonstrating the use of nested loops in Java.
Output
1
12
123
1234
12345

Java while Loop vs do...while Loop

while loop do-while loop


It first needs to check the condition, and The execution of statement(s) occurs at least once.
only then can we execute the After that, the checking of the condition occurs.
statement(s).
while(condition) while(condition);
No semicolon is present at the end of the A semicolon is present at the end of the do-while
while loop. loop.
We don’t require any brackets if there is We would always require brackets in this case.
only a single statement.
The while loop is an entry-controlled The do-while loop is an exit-controlled type of loop.
type of loop.

Methods:

A method in Java is a block of code that, when called, performs specific actions mentioned in
it. For instance, if you have written instructions to draw a circle in the method, it will do that
task. You can insert values or parameters into methods and they will only be executed when
called. They are also referred to as functions. The primary uses of methods in Java are:

 It allows code reusability (define once and use multiple times)


 You can break a complex program into smaller chunks of code
 It increases code readability

Method Declaration:

Method Signature: It is a part of the method declaration. It includes the method


name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: The method is accessible only in the classes in which it is defined.
o Protected: The method is accessible within the same package or subclasses in a
different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method: While defining a method, remember that the method name must be
a verb and start with a lowercase letter. If the method name has more than two words, the first
name must be a verb followed by adjective or noun. In the multi-word method name, the first
letter of each word must be in uppercase except the first word.
For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class,
it is known as method overloading.

Types of Method: There are two types of methods in Java:


o Predefined Method
o User-defined Method

Predefined Method: In Java, predefined methods are the method that is already defined in
the Java class libraries is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already stored in the
library. Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Example: Demo.java
public class Demo {
public static void main(String[] args) {
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
} }
Output: The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max()
method is a method of the Math class that returns the greater of two numbers.

We can also see the method signature of any predefined method by using the
link https://docs.oracle.com/. When we go through the link and see the max() method
signature, we find the following:

User-defined Method: The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
//user defined method
public static void findEvenOdd(int num) {
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.

Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the
called method.
import java.util.Scanner;
public class EvenOdd {
public static void main (String args[]) {
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd {
public static void main (String args[]) {
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
} //user defined method
public static void findEvenOdd(int num) {
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
} }
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd
In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the
value of a and b, respectively. Therefore, the method adds the value of a and b and store it in
the variable s and returns the sum.
Addition.java
public class Addition {
public static void main(String[] args) {
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
} //user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters {
int s;
s=n1+n2;
return s; //returning the sum
} }
Output: The sum of a and b is= 24

Static Method: A method that has static keyword is known as static method. In other words,
a method that belongs to a class rather than an instance of a class is known as a static method.
We can also create a static method by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.
Example: Display.java
public class Display {
public static void main(String[] args) {
show();
}
static void show() {
System.out.println("It is an example of static method.");
} }
Output: It is an example of a static method.

Instance Method: The method of the class is known as an instance method. It is a non-
static method defined in the class. Before calling or invoking the instance method, it is
necessary to create an object of its class. Let's see an example of an instance method.
InstanceMethodExample.java
public class InstanceMethodExample {
public static void main(String [] args) {
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b) {
s = a+b;
return s; //returning the sum
} }
Output: The sum is: 25

There are two types of instance method:


o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.
Example
public int getId() {
return Id;
}
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data type
that depends on the field. It is used to set the value of the private field.
Example
public void setRoll(int roll) {
this.roll = roll;
}

Example of accessor and mutator method Student.java


public class Student {
private int roll;
private String name;
public int getRoll() //accessor method {
return roll;
}
public void setRoll(int roll) //mutator method {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
} }

Abstract Method: The method that does not has method body is known as abstract method.
In other words, without an implementation is known as abstract method. It always declares in
the abstract class. It means the class itself must be abstract if it has abstract method. To create
an abstract method, we use the keyword abstract.
Syntax: abstract void method_name();
Example Demo.java
abstract class Demo //abstract class {
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo {
//method impelmentation
void display() {
System.out.println("Abstract method?");
}
public static void main(String args[]) {
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
} }
Output:Abstract method...

Factory method: It is a method that returns an object to the class to which it belongs. All static
methods are factory methods.
For example, NumberFormat obj = NumberFormat.getNumberInstance();

Arrays

An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed. You
have seen an example of arrays already, in the main method of the "Hello World!"
application.

An array of 10 elements.
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the preceding illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop: We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable, then executes the
body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Example
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
Passing Array to a Method: We can pass the java array to method so that we can reuse the
same logic on any array. Example to get the minimum number of an array using a method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output: 3
Anonymous Array in Java: Java supports the feature of an anonymous array, so you don't
need to declare the array while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Output:
10
22
44
66
Returning Array from the Method: We can also return an array from the method in Java.
//Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
int arr[]=get(); //calling method which returns an array
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException: The Java Virtual Machine (JVM) throws an
ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or
greater than the array size while traversing the array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
} }}
Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Array : In such case, data is stored in row and column based index (also
known as matrix form). Syntax to Declare Multidimensional Array.
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array:
int[][] arr=new int[3][3];//3 row and 3 column
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.
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.

OOPs

Object-oriented programming is a core of Java Programming, which is used for designing a


program using classes and objects. OOPs, can also be characterized as data controlling for
accessing the code. It’s a powerful paradigm that drives Java’s design and development
principles. Java’s strength lies in its adherence to the OOP principles.

Objects: In Java, an object is more than just a runtime entity; it’s the embodiment of a class.
These objects mirror real-world entities, complete with both state and behavior. Think of a
‘Car’ object based on a ‘Car’ class. It possesses attributes like color, brand, and speed, along
with behaviors like ‘accelerate’ and ‘brake’. This is where Java OOP concepts come to life.

These objects always correspond to things found in the real world, i.e., real entities. When we
treat animals as objects, it has states like colour, name, breed etc., and behaviours such as
eating, wagging the tail etc.
Example: Suppose, we have created a class called My book, we specify the class name
followed by the object name, and we use the keyword new.
Public class Mybook {
int x=10;
Public static void main (String args []) {
Mybook Myobj= new Mybook ();//This is the statement used for creating objects.
System.out.println(MyObj.x); //This statement is used to return the value of x of an
object.
} }

In the above example, a new object is created, and it returns the value of x which may be the
number of books.

We can also create multiple objects in the same class and we can create in one class and access
it in another class. This method is used for better organization of classes and always remember
that name of the java file and the class name remains the same.

Example: The below example shows how multiple objects are created in the same class and
how they are accessed from another class.
Mybook.java
Public class Mybook {
int x=10;
int y=8;
}
Count.java
Class Count {
Public static void main (String [] args) {
Mybook myobj1 = new myobj1();
Mybook myobj2 = new myobj2();
System.out.println (myobj1.x);
System.out.println (myobj2.y);
}}
It gives the result as 10, and 8 respectively.

Classes: A class in Java serves as a blueprint for creating objects. It bundles data (attributes)
and behaviour (methods) that define the object. Consider a ‘Car’ class; it defines attributes like
colour and methods like ‘accelerate()’. Essentially, a class is a template that characterizes what
can be instantiated as an object, exemplifying OOPs concepts. A class declaration consists of:
Modifiers: These can be public or default access.
Class name: Initial letter.
Superclass: A class can only extend (subclass) one parent.
Interfaces: A class can implement more than one interface.
Body: Body surrounded by braces, { }.
class classname {
type instance variable 1;
type instance variable 2;
.
.
type instance variable n;
type methodname 1 (parameter list) {
// body od method
}
type methodname 2 (parameter list) {
// body od method
}
type methodnamen (parameter list) {
// body od method
}}
The variables or data defined within a class are called instance variables. Code is always
contained in the methods. Therefore, the methods and variables defined within a class are called
members of the class. All the methods have the same form as the main () these methods are not
specified as static or public

Abstraction: Abstraction is a process which displays only the information needed and hides
the unnecessary information. We can say that the main purpose of abstraction is data hiding..
Abstraction in Java involves concealing complexity while exposing only the essential aspects.
It’s realized through abstract classes and interfaces. For instance, a ‘Vehicle’ interface declares
a ‘move()’ method, but the actual implementation is left to classes like ‘Car’ or ‘Bike’. This
focus on “what an object does” rather than “how it does it” is a core OOPs concept in Java.

There are also abstract classes and abstract methods. An abstract class is a type of class that
declares one or more abstract methods. An abstract method is a method that has a method
definition but not implementation. Once we have modelled our object using data abstraction,
the same sets of data can also be used in different applications—abstract classes, generic types
of behaviours and object-oriented programming hierarchy. Abstract methods are used when
two or more subclasses do the same task in different ways and through different
implementations. An abstract class can have both methods, i.e., abstract methods and regular
methods.
Now let us see an example related to abstraction. Suppose we want to create a student
application and ask to collect information about the student. We collect the information. Name,
Class, Address, Dob, Fathers name, Mothers’ names and so on. We may not require every
information that we have collected to fill out the application. So, we select the data that is
required to fill out the application. Hence, we have fetched, removed, and selected the data, the
student information from large data. This process is known as abstraction in the oops concept.
Abstract class example:
//abstract parent class
Abstract class animal {
public abstract void sound ( ) ; //abstract method
}
Public class lion extends animal {
Public void sound ( ) {
System.out.println (“ roar “ );
}
public Static void main ( String args [ ] ) {
animal obj = new lion ( );
obj. sound ();
}}
Output: roar
Inheritance: Extending existing class functionality to new class. Inheritance is a mechanism
where a new class (subclass) derives attributes and methods from an existing class (superclass).
This fosters code reusability and establishes a hierarchical relationship between classes. For
example, an ‘ElectricCar’ class can inherit traits from the ‘Car’ class.

For example, a whale is a part of the classification of marine animals, which is part of class
mammal, which is under that class of animal. We use hierarchical classification, i.e., top-down
classification. If we want to describe a more specific class of animals such as mammals, they
would have more specific attributes such as teeth; cold-blooded, warm-blooded, etc. This
comes under the subclass of animals whereas animals come under the superclass. The subclass
is a class which inherits properties of the superclass. This is also called a derived class. A
superclass is a base class or parental class from which a subclass inherits properties.

We use inheritance mainly for method overriding and R: To inherit a class, we use the extend
keyword. There are five types of inheritance single, multilevel, multiple, hybrid and
hierarchical.

Single level: In this one class i.e., the derived class inherits properties from its parental class.
This enables code reusability and also adds new features to the code. Example: class b inherits
properties from class a. Class A is the base or parental class and class b is the derived class.
Syntax:
Class a {

}
Class b extends class a {

}
Multilevel: This one class is derived from another class which is also derived from another
class i.e., this class has more than one parental class, hence it is called multilevel inheritance.
Syntax:
Class a {
….
}
Class b extends class a {
….
}
Class c extends class b {

}
Hierarchical level: In this one parental class has two or more derived classes or we can say
that two or more child classes have one parental class.
Syntax:
Class a {

}
Class b extends class a {
..
}
Class c extends class a {
..
}
Hybrid inheritance: This is the combination of multiple and multilevel inheritances and in
java, multiple inheritances are not supported as it leads to ambiguity and this type of inheritance
can only be achieved through interfaces. Consider that class a is the parental or base class of
class b and class c and in turn, class b and class c are parental or a base class of class d. Class
b and class c are derived classes from class a and class d is derived class from class b and class
c. The following program creates a superclass called add and a subclass called sub, using extend
keyword to create a subclass add.

//create a superclass
Class Add {
int my;
int by;
void setmyby (int xy, int hy) {
my=xy;
by=hy;
}}
//create a sub class
class b extends add {
int total;
void sum () {
public Static void main (String args [ ] ) {
b subOb= new b ( );
subOb. Setmyby (10, 12);
subOb. Sum ( ) ;
System.out.println(“total =” + subOb. Total);
}}
output– total = 22

Polymorphism: One behaving differently in different situation. Polymorphism allows Java


methods and objects to assume multiple forms. It finds common use in method overloading
(same method name, different parameters) and method overriding (same method name and
parameters in subclass as in parent class). Consider a ‘draw()’ method implemented differently
in ‘Circle’, ‘Square’, and ‘Triangle’ classes as a prime example of polymorphism in Java.
Example:
public class Bird {

Public void sound ( ) {
System.out.println ( “ birds sounds “ );
} }
public class pigeon extends Bird {

@override
public void sound ( ) {
System.out.println( “ cooing ” ) ;
} }
public class sparrow extends Bird ( ) {
….
@override
Public void sound ( ){
System.out.println( “ chip ” ) ;
} }
In the above example, we can see common action sound () but there are different ways to do
the same action. Polymorphism in java can be classified into two types:

 Static / Compile-Time polymorphism is also known as Static Polymorphism. to resolved


at compile-time which is achieved through the Method Overloading.

 Dynamic / Runtime polymorphism is also known as Dynamic Binding which is used to


call an overridden method and dynamic dispatch (Creating sub class object by using super
class reference variable).
Encapsulation: Binding variable and method in single unit. It entails bundling data (attributes)
and code (methods) into a cohesive unit. Moreover, it limits direct access to an object’s
components, preventing inadvertent interference. Techniques like using private variables and
offering public getter and setter methods exemplify Java OOPs concepts put into practice.
Example:
class animal {
private int age;// private field
//getter method
Public int getage ( ) {
return age;
}
//setter method
public void setAge ( int age ) {
this. Age = age;
} }
class Main {
public static void main (String args []);
Animal a1= new Animal ();//create an object of person
A1. setAge (12);//change age using setter
System.out.println(“ animal age is ” + a1. getage ( ) );// access age using getter
} }
Output: Animal age is 12

In this example, we declared a private field called age that cannot be accessed outside of the
class. To access age, we used public methods. These methods are called getter and setter
methods. Making age private allows us to restrict unauthorized access from outside the class.
Hence this is called data hiding.

Advanced OOP Concepts:


• Coupling and Cohesion: Concepts focusing on the interdependence and
responsibilities of classes in Java.
• Association, Aggregation, and Composition: These concepts define how objects
interact and depend on each other.

 Coupling: In OOP, coupling refers to the degree of direct knowledge one class has of
another. Coupling refers to the relationship between two classes. It indicates the knowledge
one object or class has of another. That means that if one class changes its properties or
behaviour, it will affect the dependent changes in the other class. Therefore, these changes
will depend upon the level of interdependence the two classes have between them. There
are two types of coupling – tight and loose.
• Tight Coupling: Here, classes are highly dependent on each other. This is generally
discouraged as it makes the system more rigid and less adaptable to change. For example, if
Class A directly uses data or methods of Class B, any change in Class B can significantly
impact Class A.
public class College{
public void status() {
System.out.println("College is open today");
} }
public class Student{
College obj = new College();
public void goToCollege() {
obj.status();
} }
In the above code example, the student class is dependent on the college class. That is, any
change in the college class requires student classes to change. Here, therefore, student class
and college class are tightly coupled with each other.

• Loose Coupling: This is the more desirable form of coupling in OOP. In this scenario,
classes are designed to interact with each other but do so in a way that reduces their direct
dependencies. For instance, using interfaces or abstract classes can help achieve loose coupling,
allowing a class to communicate with another class without needing to know the intricate
details of its implementation.
If one class is weakly interrelated to another class, it is said to have loose coupling with that
class. Loose coupling is preferred over tight coupling. A class can achieve this with the help of
interfaces, as shown below.
public interface College{
void status();
}
class CollegeStatus1 implements College{
public void status() {
System.out.println("College is open monday to friday");
} }
class CollegeStatus2 implements College{
public void status() {
System.out.println("College is open on saturday");
} }
public class Student{
College obj = new CollegeStatus1();
public void goToCollege() {
obj.status();
} }
In the above code example, CollegeStatus1 and CollegeStatus2 are loosely coupled. Here,
student class is not directly or tightly coupled with a CollegeStatus1 or CollegeStatus2 class.
By applying a dependency injection mechanism, the loose coupling implementation is achieved
to allow a student to go to college with any class which has implemented a college interface.
In addition, it means we can use CollegeStatus2 whenever the college is open on Saturday.
 Cohesion: Cohesion refers to how closely related and focused the responsibilities of a class
or module are. High cohesion is generally preferable as it indicates that a class is designed
to do a specific job well without taking on responsibilities that should be delegated to other
classes.

• Low Cohesion: Low cohesion suggests that a class performs a wide variety of actions
and is not focused on a specific task. This often leads to classes that are difficult to understand,
maintain, and can lead to redundant code.
In the following code, we have a class called Book. But it is less cohesive because it comprises
less focussed and independent attributes and methods to the class. This class should contain
information related to the Book. Therefore, the person’s name and age method are making this
classless cohesive.
class Book{
int price = 299; //related attribute
String name = "Sam"; //unrelated attribute
//related methods to Book class
public String author(String name) {
return name;
}
public String title(String subject) {
return subject;
}
public int id(int number) {
return number;
}
//unrelated methods to Book class
public int age(int age) {
return age;
} }

• High Cohesion: In a highly cohesive system, each class has a clearly defined role,
making the system easier to maintain, test, and understand. For example, a class designed solely
for database interactions should not contain business logic or UI code.
When the class has a single well-defined purpose or task, it is said to be highly cohesive. So,
in the above example code, if we remove the information related to the person, then the class
becomes highly cohesive, as shown below.
class Book{
int price = 299; //related attribute
//related methods to Book class
public String author(String name) {
return name;
}
public String title(String subject) {
return subject;
}
public int id(int number) {
return number;
} }

 Association, Aggregation, and Composition


• Association: Association is a relation between two separate classes that establishes
with the help of their Objects. It specifies the relationship between two or more Objects.
Association can be one-to-one, one-to-many, many-to-one, and many-to-many. Let us
understand this with real-world examples, suppose the relationship between the bus and the
passengers. A bus can have only one driver(one-to-one). Many passengers can associate with
the single bus(many-to-one). A single passenger can associate with many different buses(one-
to-many). Also, many passengers can associate with the many different buses(many-to-many).
One object is associated with another object to use the functionality and services provided by
another object. Consider the following code below:
//class bus
class Bus{
private String name;
// bus name
Bus(String name){
this.name = name;
}
public String getBusName(){
return this.name;
} }
//passenger class
class Passenger{
private String name; // passenger name
private int seatId; // passenger seat id number
Passenger(String name, int seatId){
this.name = name;
this.seatId = seatId;
}
public String getPassengerName(){
return this.name;
}
public int getPassengerId(){
return this.seatId;
} }
//Association between both the classes in the main method
class Demo{
public static void main (String[] args){
Bus bus = new Bus("Shree Travels");
Passenger psg = new Passenger("Sneha", 52);
System.out.println(psg.getPassengerName() + " with seat number " +
psg.getPassengerId()
+ " is a passenger of " + bus.getBusName());
} }
Output: Sneha with seat number 52 is a passenger of Shree Travels
Explanation: In the above example, two separate classes Bus and Passenger, are associated
through their Objects inside the class Demo. In this way, we can establish the relationship
between two different classes by using the concept of association. A bus can have many
passengers, So it is a one-to-many relationship.

• Aggregation: This is a specialized form of association where the relationship is a “has-


a” type but the lifetime of the owned object doesn’t depend on the owner. It represents a whole-
part relationship. For instance, a ‘Department’ class can have a list of ‘Professor’ objects, but
the existence of ‘Professor’ objects is not strictly tied to the ‘Department’.
Java Aggregation is a weak association and represents a relationship between an object
containing other objects. This represents a part of a whole relationship where a part can exist
without a whole. Let’s take an example of the relationship between Group and Person. A Person
may belong to multiple Groups. Hence a Group can have multiple Persons. But if we delete a
Group, the Person object will not destroy. Aggregation represents the Has-A relationship,
unidirectional association, i.e., a one-way relationship. For instance, the group can have
persons, but vice versa is not possible and thus unidirectional. In this section, both entries can
survive individually, which means ending one entity will not affect the other entity. Hence,
both objects are independent in aggregation. Considering the following code example:
import java.util.*;
class Person{
private String name;
private int age ;
Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
} }
/* Group class contains the list of person Objects. It is associated with the person class
through its Object(s). */
class Group{
private String groupName;
private List<Person> persons;
Group(String groupName, List<Person> persons){
this.groupName = groupName;
this.persons = persons;
} }
class Demo{
public static void main (String[] args){
//creating objects of person class
Person a = new Person("Tanmay", 17);
Person b = new Person("Sam", 18);
Person c = new Person("Pitu", 19);
Person d = new Person("Khushi", 20);
//making a list of persons belongs to social welfare group
List<Person> p1 = new ArrayList<>();
p1.add(a);
p1.add(c);
//making a list of persons belongs to drama fest group
List<Person> p2 = new ArrayList<>();
p2.add(b);
p2.add(d);
//creating objects of group class
Group swGrp = new Group("Social Welfare", p1);
Group dfGrp = new Group("Drama Fest", p2);
//before deleting drama fest group
System.out.println("List of persons in Drama Fest group:");
for(Person p : p2) {
System.out.println("Person name: " + p.getName() + ", Age:" + p.getAge() + ", Group:
Drama Fest");
}
//deleting drama fest group
dfGrp = null;
//after deleting drama fest group person list will not destroy
System.out.println("List of persons after deleting Drama Fest group:");
for(Person p : p2) {
System.out.println("Person name: " + p.getName() + ", Age: " + p.getAge());
} } }
Output:
List of persons in Drama Fest group:
Person name: Sam, Age:18, Group: Drama Fest
Person name: Khushi, Age:20, Group: Drama Fest
List of persons after deleting Drama Fest group:
Person name: Sam, Age: 18
Person name: Khushi, Age: 20
Explanation: Here, we can see that the two classes Person and Group, are associated with each
other with the help of objects. There are two groups social welfare and drama fest. We created
these groups by using the person class. The group has a list of persons. We have two people
Sam and Khushi, in the Drama Fest group as shown in the output. Afterwards, we deleted this
group by setting the instance of group equals to null. But, our list of persons remains
undestroyed due to the weak association, i.e., aggregation, even after the group was deleted.

• Composition: This is also a type of association but with a stronger relationship. In


composition, the lifetime of the owned object is managed by the owner, meaning if the owner
object is destroyed, the owned objects are also destroyed. It represents a stronger whole-part
relationship. A classic example is the relationship between a ‘House’ and ‘Room’; if the
‘House’ is destroyed, the ‘Rooms’ within it also cease to exist.
Java Composition is an association that represents a part of a whole relationship where a part
cannot exist without a whole. Let’s take an example of the relationship between School and
Room. The school object consists of several rooms. Whenever the school object destroys
automatically, all the room objects will be destroyed, i.e., without the existing school object,
there is no chance of an existing dependent object. So these are strongly associated, and this
relationship is called composition. If a whole is deleted, then all parts are deleted. So
composition represents the part-of relationship.
Whenever there is a composition between two entities, the created object cannot exist without
the other object. Thus, in composition, both entities are dependent on each other. Consider the
following code example:
import java.util.*;
class ActivityRoom {
public String subject;
public int id;
ActivityRoom(String subject, int id) {
this.subject = subject;
this.id = id;
} }
class Department {
private String name;
//list of activity rooms in a department.
private List<ActivityRoom> ar;
Department(List<ActivityRoom> ar) {
this.ar = ar;
}
// Getting total number of colleges
public List<ActivityRoom> getActivityRoomsInDepartment()
{
return ar;
} }
class Demo {
public static void main(String[] args) {
// Creating the Objects of activity room class.
ActivityRoom a1 = new ActivityRoom("Technical", 601);
ActivityRoom a2 = new ActivityRoom("Business", 602);
ActivityRoom a3 = new ActivityRoom("Economics", 603);
// making the list of activity rooms.
List<ActivityRoom> act = new ArrayList<ActivityRoom>();
act.add(a1);
act.add(a2);
act.add(a3);
// Creating the Object of department class.
Department d = new Department(act);
// making the list of activity rooms in department.
List<ActivityRoom> arlist = d.getActivityRoomsInDepartment();
for (ActivityRoom a : arlist) {
System.out.println(a.subject + " activity room with id " + a.id);
} } }
Output:
Technical activity room with id 601
Business activity room with id 602
Economics activity room with id 603
Explanation: Here we have two classes Activity room and Department. A department
composed of different subject activity rooms. So, If the department gets destroyed, then All
activity rooms within that department will be destroyed, i.e., the activity room can not exist
without the department. That’s why it is composition.

Static Method: A method that has the static keyword in the declaration is known as the static
method. In other words, a method that belongs to a class rather than an instance of a class is
known as a static method. We can also create a static method by using the keyword static before
the method name. The main benefit of a static method is that we can invoke the static method
without even creating an object. It can access static data members and also change their values
and is also used to create an instance method. The main() method is a common example of the
static method.
Example:
public class Demo {
public static void main(String[] args) {
displaymethod();
}
static void displaymethod() {
System.out.println("It is an example of static method.");
} }
Output:It is an example of a static method.
Abstract Method: A method that is declared with keyword abstract is called an abstract
method. The abstract method does not have an implementation or body, or block of code. The
abstract method must always be declared in an abstract class, or we can say that if a class has
an abstract method, it should be declared abstract. If a class has an abstract method, it should
be declared abstract, but vice versa is not true, which means that an abstract class doesn’t need
to have an abstract method compulsory. Also, If a normal class extends an abstract class, then
the class must have to implement all the abstract parent class’s abstract methods, or it has to be
declared abstract.
Example:
abstract class Area{
// These two are abstract methods, the child class must implement these methods
public abstract int areaSquare(int s);
public abstract int areaRectangle(int l, int b);
public void display(){ //Normal method
System.out.println("Normal method in abstract class Area");
} }
//Normal class extends the abstract class
class Demo extends Area{
/* If we don't provide the implementation of these two methods, the program will throw
compilation error. */
public int areaSquare(int s){
return s*s;
}
public int areaRectangle(int l, int b){
return l*b;
}
public static void main(String args[]){
Area a = new Demo();
System.out.println("Area of square " + a.areaSquare(9));
System.out.println("Area of rectangle " + a.areaRectangle(3,4));
a.display();
} }
Output:
Area of square 81
Area of rectangle 12
The normal method in abstract class Area
Final Method: A method that is declared final is called a final method. We cannot override a
final method. This means the child class can still call the final method of the parent class
without any problem, but it cannot override it. This is because the main purpose of making a
method final is to stop the modification of the method by the sub-class.
Example:
class DemoParent{
final void method(){
System.out.println("Parent class final method");
} }
class Demo extends DemoParent{
//error
void method(){
System.out.println("final method modified inside child class");
}
public static void main(String args[]){
Demo d = new Demo();
d.method();
} }
The above code will throw an error as we are trying to modify the final method inside the child
class(demo) of the parent class(demoParent). Instead of modifying the method, we can use it
as shown below:
class DemoParent{
final void method(){
System.out.println("Parent class final method");
} }
class Demo extends DemoParent{
public static void main(String args[]){
Demo d = new Demo();
d.method();
} }
Output:
Parent class final method
Equals Method in Java
As the name suggests in java, .equals() is a method used to compare two objects for equality.
The .equals() method in java is used to check if the two strings have similar values. It checks
them character by character. One should not confuse .equals() method with == operator. The
String equals() method compares the two given strings based on the content of the string,
whereas the == operator is used for address comparison. If all the contents of both the strings
are the same, then .equals() returns true otherwise, it returns false. If all characters are not
matched, then it returns false. Let us understand this with the help of an example:
public class Demo {
public static void main(String[] args) {
String s1 = "GreatLearning";
String s2 = "GreatLearning";
String s3 = new String("GreatLearning");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
} }
Even though s1 and s3 are created with the same field(content), they are pointing to two
different objects in memory. Hence at different addresses. Therefore == operator gives false
and .equals() method gives true as both contain similar content greatLearning.
Message Passing: Message Passing in terms of computers is a communication phenomenon
between the processes. It is a kind of communication used in object-oriented programming.
Message passing in Java is the same as sending an object, i.e., a message from one thread to
another thread. It is utilized when threads do not have shared memory and are not able to share
monitors or any other shared variables to communicate. In message passing calling program
sends a message to a process and relies on that process to run its own functionality or code.
Message passing is easy to implement, has faster performance, and we can build massive
parallel models by using it. There are two types of it: Synchronous and Asynchronous.
• Synchronous message passing occurs when the objects run at the same time.
• In the case of an Asynchronous message passing, the receiving object can be down or
busy when the requesting object sends the message.

Advantages of OOPs Concept:


• Re-usability: When we say re-usability, it means that “write once, use it multiple
times” i.e., reusing some facilities rather than building it again and again, which can be
achieved by using class. We can use it n number of times whenever required.
• Data redundancy: It is one of the greatest advantages in oops. This is the condition
which is created at the data storage when the same piece of data is held at two different places.
If we want to use similar functionality in multiple classes, we can just write common class
definitions for similar functionalities by inheriting them.
• Code maintenance: It is easy to modify or maintain existing code as new objects which
can be created with small differences from the existing ones. This helps users from doing
rework many times and modifying the existing codes by incorporating new changes to it.
• Security: Data hiding and abstraction are used to filter out limited exposure which
means we are providing only necessary data to view as we maintain security.
• Design benefits: The designers will have a long and more extensive design phase,
which results in better designs. At a point of time when the program has reached critical limits,
it will be easier to program all non-oops separately.
• Easy troubleshooting: Using encapsulation objects is self-constrained. So, if
developers face any problem easily it can be solved. And there will be no possibility of code
duplicity.
• Flexibility and Problem-solving

Disadvantages of OOPs Concept


• Effort – A lot of work is put into creating these programs.
• Speed – These programs are slower compared to other programs.
• Size – OOPs programs are bigger when compared to other programs.

Constructors
 Constructors are special methods with the same name as the class, used for initializing
objects.
 Constructor does not have any return type, not even void.
 If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time.
 A constructor cannot be abstract or static or final.
 A constructor can be overloaded but cannot be overridden.
 Constructor overloading allows for multiple constructors with different parameter lists
within the same class.
 Constructor chaining enables one constructor to call another constructor within the same
class using the this() keyword.
 The super keyword is used to explicitly call the constructor of the superclass within a
subclass constructor.
 Constructors can have access modifiers like public, protected, or private.
 Constructors are not inherited but are invoked when objects of subclasses are created.
class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
} }
Output: Constructor Called:The name is Programiz
In the above example, we have created a constructor named Main(). Inside the constructor, we
are initializing the value of the name variable. Notice the statement creating an object of
the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And the value of
the name variable is initialized.Hence, the program prints the value of the name variables
as Programiz.

Types of Constructor: Constructors can be divided into three types:

1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. No-Arg Constructors: Similar to methods, a Java constructor may or may not have any
parameters (arguments). If a constructor does not accept any parameters, it is known as a no-
argument constructor.
Example:
class Main {
int i;
private Main() { // constructor with no parameter
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
Main obj = new Main();// calling the constructor without any parameter
System.out.println("Value of i: " + obj.i);
} }
Output:
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main(). Here, the constructor does not
accept any parameters. Hence, it is known as a no-arg constructor.
Notice that we have declared the constructor as private. Once a constructor is declared private,
it cannot be accessed from outside the class. So, creating objects from outside the class is
prohibited using the private constructor. Here, we are creating the object inside the same class.
However, if we want to create objects outside the class, then we need to declare the constructor
as public.
Example: Public no-arg Constructors
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
} }
class Main {
public static void main(String[] args) {
Company obj = new Company();// object is created in another class
System.out.println("Company name = " + obj.name);
} }
Output: Company name = Programiz
2. Parameterized Constructor: A Java constructor can also accept one or more parameters.
Such constructors are known as parameterized constructors (constructors with parameters).
Example:
class Main {
String languages;
Main(String lang) { // constructor accepting single value
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
} }
Output
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main(). Here, the constructor takes
a single parameter. Notice the expression:
Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor. Based on the argument passed, the
language variable is initialized inside the constructor.

3. Default Constructor: If we do not create any constructor, the Java compiler automatically
creates a no-arg constructor during the execution of the program. This constructor is called the
default constructor.
Example:
class Main {
int a;
boolean b;
public static void main(String[] args) {
Main obj = new Main();// calls default constructor
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
} }
Output:
Default Value:
a=0
b = false
Here, we haven't created any constructors. Hence, the Java compiler automatically creates the
default constructor.

Java Constructor Java Method

A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default


The method is not provided by the compiler
constructor if you don't have any constructor
in any case.
in a class.

The constructor name must be same as the The method name may or may not be same as
class name. the class name.

Strings

A string is a sequence of characters. For example, "hello" is a string containing a sequence of


characters 'h', 'e', 'l', 'l', and 'o'.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

String objects are immutable: Immutable simply means unmodifiable or unchangeable. Once
a string object is created its data or state can’t be changed but a new string object is created.

Memory Allotment of String: Whenever a String Object is created as a literal, the object will
be created in the String constant pool. This allows JVM to optimize the initialization of String
literal.
Example: String demoString = "MyString";
The string can also be declared using a new operator i.e. dynamically allocated. In case of
String are dynamically allocated they are assigned a new memory location in the heap. This
string will not be added to the String constant pool.
Ways of Creating a String: There are two ways to create a string in Java:
String Literal: To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
Example: String demoString = “Hello”;
Using new Keyword: In such a case, JVM will create a new string object in normal (non-pool)
heap memory and the literal “Welcome” will be placed in the string constant pool. The variable
s will refer to the object in the heap (non-pool)
Example: String s = new String(“Welcome”);
In the given example only one object will be created. Firstly JVM will not find any string object
with the value “Welcome” in the string constant pool, so it will create a new object. After that
it will find the string with the value “Welcome” in the pool, it will not create a new object but
will return the reference to the same instance.

Interfaces and Classes in Strings:


CharBuffer: This class implements the CharSequence interface. This class is used to allow
character buffers to be used in place of CharSequences. An example of such usage is the
regular-expression package java.util.regex.
String: It is a sequence of characters. In Java, objects of String are immutable which means a
constant and cannot be changed once created.
CharSequence Interface: CharSequence Interface is used for representing the sequence of
Characters in Java. Classes that are implemented using the CharSequence interface are
mentioned below and these provides much of functionality like substring, lastoccurence, first
occurence, concatenate , toupper, tolower etc.
 String
 StringBuffer
 StringBuilder
1. String: String is an immutable class which means a constant and cannot be changed once
created and if wish to change, we need to create an new object and even the functionality it
provides like toupper, tolower, etc all these return a new object, its not modify the original
object. It is automatically thread safe.
Syntax:
String str= "Hello";
or
String str= new String("Hello");
2. StringBuffer: StringBuffer is a peer class of String, it is mutable in nature and it is thread
safe class , we can use it when we have multi threaded environment and shared object of string
buffer i.e, used by mutiple thread. As it is thread safe so there is extra overhead, so it is mainly
used for multithreaded program.
Syntax: StringBuffer demoString = new StringBuffer("Hello");
3. StringBuilder: StringBuilder in Java represents an alternative to String and StringBuffer
Class, as it creates a mutable sequence of characters and it is not thread safe. It is used only
within the thread, so there is no extra overhead, so it is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder();
demoString.append("KGF");
StringTokenizer: StringTokenizer class in Java is used to break a string into tokens.

Methods of Java String:

Methods Description

contains() Checks whether the string contains a substring.


substring() Returns the substring of the string.

join() Joins the given strings using the delimiter.

Replaces the specified old character with the


replace()
specified new character.

replaceAll() Replaces all substrings matching the regex pattern.

replaceFirst() Replaces the first matching substring.

Returns the character present in the specified


charAt()
location.

getBytes() Converts the string to an array of bytes.

Returns the position of the specified character in the


indexOf()
string.

compareTo() Compares two strings in the dictionary order.

compareToIgnoreCase() Compares two strings, ignoring case differences.

trim() Removes any leading and trailing whitespaces.

format() Returns a formatted string.

split() Breaks the string into an array of strings.

toLowerCase() Converts the string to lowercase.

toUpperCase() Converts the string to uppercase.

Returns the string representation of the specified


valueOf()
argument.

toCharArray() Converts the string to a char array.

matches() Checks whether the string matches the given regex.

startsWith() Checks if the string begins with the given string.

endsWith() Checks if the string ends with the given string.


isEmpty() Checks whether a string is empty or not.

intern() Returns the canonical representation of the string.

contentEquals() Checks whether the string is equal to charSequence.

hashCode() Returns a hash code for the string.

subSequence() Returns a subsequence from the string.

String StringBuffer

The String class is immutable. The StringBuffer class is mutable.

String is slow and consumes more memory


StringBuffer is fast and consumes less memory
when we concatenate too many strings
when we concatenate t strings.
because every time it creates new instance.

String class overrides the equals() method


StringBuffer class doesn't override the equals()
of Object class. So you can compare the
method of Object class.
contents of two strings by equals() method.

String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.

String class uses String constant pool. StringBuffer uses Heap memory

StringBuffer StringBuilder

StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e. not thread


safe. It means two threads can't call the safe. It means two threads can call the methods of
methods of StringBuffer simultaneously. StringBuilder simultaneously.

StringBuffer is less efficient than


StringBuilder is more efficient than StringBuffer.
StringBuilder.

StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

How to create Immutable class?


There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable. We can also create
immutable class by creating final class that have final data members as the example given
below: Example to create Immutable class. In this example, we have created a final class named
Employee. It has one final datamember, a parameterized constructor and getter method.
ImmutableDemo.java
public final class Employee {
final String pancardNumber;
public Employee(String pancardNumber) {
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
} }
public class ImmutableDemo {
public static void main(String ar[]) {
Employee e = new Employee("ABC123");
String s1 = e.getPancardNumber();
System.out.println("Pancard Number: " + s1);
} }
Output: Pancard Number: ABC123

The above class is immutable because:


o The instance variable of the class is final i.e. we cannot change the value of it after
creating an object.
o The class is final so we cannot create the subclass.
o There is no setter methods i.e. we have no option to change the value of the instance
variable.

 Difference between equals() method and == operator: The equals() method matches
content of the strings whereas == operator matches object or reference of the strings.
 String class is final
 How many objects will be created in the following code? one
String s1="javatpoint";
String s2="javatpoint";
 toString() Method: If you want to represent any object as a string, toString() method comes
into existence. The toString() method returns the String representation of the object.
 StringTokenizer: The java.util.StringTokenizer class allows you to break a String into
tokens. It is simple way to break a String. It is a legacy class of Java.
Simple.java
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
} } }
Output:
my
name
is
khan
Text I/O

The java.io package is used to handle input and output operations. Java IO has various classes
that handle input and output sources. A stream is a sequence of data. Java input stream classes
can be used to read data from input sources such as keyboard or a file. Similarly output stream
classes can be used to write data on a display or a file again. We can also perform File
Handling using Java IO API.
A Stream is also a sequence of data. It is neither a data structure nor a store of data. For
example, a river stream is where water flows from source to destination. Similarly, these are
data streams; data flows through one point to another. The java.io package helps the user
perform all input-output operations. Java IO package is primarily focused on input-output files,
network streams, internal memory buffers, etc. Data is read and written from Java
IO's InputStream and OutputStream classes. In other words, IO streams in Java help to read the
data from an input stream, such as a file and write the data into an output stream, such as the
standard display or a file again. It represents the source as input and the destination as output.
It can handle all types of data, from primitive values to advanced objects.
The java.io package consists of output and input streams used to write and read data to files or
other output and input sources.
There are 3 categories of classes in java.io package:
 Input Streams.
 Output Streams.
 Error Streams.
Java supports three streams that are automatically attached with the console.
1. System.out: Standard output stream
2. System.in: Standard input stream
3. System.err: Standard error stream
Input Streams: As we know, an input source consists of data that needs to be read in order to
extract information from it. Input Streams help us read data from the input source. They are
an abstract class that provides a programming interface for all input streams. Input streams are
opened implicitly as soon as they are created. We use a close() method on the source object to
close the input stream.
It is an abstract superclass of the java.io package and is used to read the data from an input
source. In other words, it means reading data from files, using a keyboard, etc. We can create
an object of the input stream class using the new keyword. The input stream class has several
types of constructors. The following code takes the file name as a string, to read the data stored
in the file.
InputStream f = new FileInputStream("input.txt");

Useful methods of InputStream:


1. public abstract int read() throws IOException: The method above returns the data of the
next byte in the input stream. The value returned is between 0and 255. If no byte is read, the
code returns -1, indicating the file's end.
2. public int available() throws IOException: The method above returns the number of bytes
that can be read from the input stream.
3. public void close() throws IOException: The method above closes the current input stream
and releases any associated system resources.
4. public void mark(int readlimit): It marks the current position in the input stream.
The readlimit argument tells the input stream to read that many bytes before the mark position
becomes invalid.
5. public boolean markSupported(): It tells whether a particular input stream supports
the mark() and reset() method. It returns true if the particular input stream supports the mark
and reset methods or returns false.
6. public int read(byte[ ] b) throws IOException: The method above reads the bytes from
the input stream and stores every byte in the buffer array. It returns the total number of bytes
stored in the buffer array. If there is no byte in the input stream, it returns -1 as the stream is at
the end of the file.
7. public int read(byte[ ] b , int off , len) throws IOException: It reads up to len bytes of
data from the input stream and returns the total number of bytes stored in the buffer. Here,
the “off” is the start offset in buffer array b where the data is written, and the “len” represents
the maximum number of bytes to read.
8. public void reset() throws IOException: It repositions the stream to the last called mark
position. The reset method does nothing for input stream class except throwing an exception.
9. public long skip(long n) throws IOException: This method discards n bytes of data from
the input stream.
Examples:
We will use FileInputStream class to read the input file: input.txt. Create a file input.txt and
place it in the same directory as Main.java
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
try {
FileInputStream f = new FileInputStream("input.txt"); // loading a file into f
variable
int x = 0;
// while loop untill the end of the file.
while ((x = f.read()) != -1) {
System.out.print((char) x); // printing the character
}
f.close();// closing a file
} catch (Exception e) {
System.out.println(e); // printing exception
} } }
Example: we will use BufferedInputStream class to read the file.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("input.txt");

// loading a file into f2 variable using BufferInputStream


BufferedInputStream f2 = new BufferedInputStream(f1);
System.out.println("Available bytes: " + f2.available()); // using the available
method
int x = 0;
// while loop untill the end of the file.
while ((x = f2.read()) != -1) {
System.out.print((char) x); // printing the character
}
System.out.println();
f2.close(); // closing a file
} catch (Exception e) {
System.out.println(e); // printing exception
} } }
Output:
Available bytes: 31
Stream Topics
From InterviewBit
In the below example, we will use the ByteArrayInputStream class to read the file.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f1 variable using FileInputStream
FileInputStream f1 = new FileInputStream("input.txt");
int x = 0;
String S = "";
// while loop untill the end of the file.
while ((x = f1.read()) != -1) {
S = S + (char) x; // printing the character
}
f1.close();// closing a input stream
byte[] b = S.getBytes();// converting string to array of bytes
// declaring ByteArrayInputStream
ByteArrayInputStream b1 = new ByteArrayInputStream(b);
x = b1.read();
while (x != -1) {
System.out.print((char) x);
x = b1.read();
}
System.out.println();
b1.close();// close the input stream
} catch (Exception e) {
System.out.println(e); // printing exception
} } }
Output:
Stream Topics
From InterviewBit

Output Streams: The executed program's output must be stored in a file for further use. Output
streams help us write data to an output source(such as a file). Similarly to input streams, output
streams are abstract classes that provide a programming interface for all output streams. The
output stream is opened as soon as it is created and explicitly closed using the "close() "method.
It is an abstract superclass of the java.io package that writes data to an output resource, which
is, in other words, writing the data into files. We can create an object of the output stream class
using the new keyword. The output stream class has several types of constructors.

Useful methods of OutputStream:


1. public void close() throws IOException: This method closes the current output stream and
releases any associated system resources. The closed stream cannot be reopened, and
operations cannot be performed on it.
2. public void flush() throws IOException: It flushes the current output stream and forces
any buffered output to be written out.
3. Public void write(byte[ ] b) throws IOException: This method writes the b.length bytes
from the specified byte array to the output stream.
4. Public void write(byte[ ] b ,int off ,int len) throws IOException: It writes up to len bytes
of data for the output stream. Here, the “off” is the start offset in buffer array b, and
the “len” represents the maximum number of bytes to be written in the output stream.
5. Public abstract void write(int b) throws IOException: The method above writes the
specific bytes to the output stream. It does not return a value.

Some methods that are inherited from class java.lang.Object. These methods are used for both
input stream and output stream purposes. Example: clone, equals, finalise, getclass, hashCode,
notify, notifyAll, toString, wait.
Examples: In the example below, we will use the FileOutputStream class to read the file.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("output.txt");
String s = "Stream Topics";
char arr[] = s.toCharArray();
int x = 0; // initializing x to 0
// while loop untill the end of the string.
while (x < s.length()) {
// writing a byte into "output.txt" file
f.write(arr[x++]);
}
f.close();// closing a file
} catch (Exception e) {
// printing exception
System.out.println(e);
} } }
Output: The output.txt file will contain the following text:
Stream Topics
In the example below, we will use the BufferedOutputStream class to read the file.
import java.io.*;
class Main {

public static void main(String[] args) throws IOException {


try {
// loading a file into f variable
FileOutputStream f1 = new FileOutputStream("output.txt");
// declaring a f1 as BufferedOutputStream
BufferedOutputStream f2 = new BufferedOutputStream(f1);
String s = "Scaler Topics";
char arr[] = s.toCharArray();
int x = 0; // initializing x to 0
// while loop untill the end of the string.
while (x < s.length()) {
f2.write(arr[x++]);// writing a byte into "output.txt" file
}
f2.close();// closing a file
f1.close();
} catch (Exception e) {
System.out.println(e); // printing exception
} } }
Output: The output.txt file will contain the following text:
Stream Topics
In the below example, we will use the ByteArrayOutputStream class to read the file.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f variable
FileOutputStream f = new FileOutputStream("output.txt");
String s = "Scaler Topics";
// declaring ByteArrayOutputStream
ByteArrayOutputStream b1 = new ByteArrayOutputStream();
b1.write(s.getBytes());// writing a data to "output.txt" file
b1.writeTo(f);
b1.close(); // closing a file
} catch (Exception e) {
System.out.println(e); // printing exception
} } }
Output: The output.txt`` file will contain the following text:
Stream Topics
Quiz Pop
Quiz Type
SCQ
100
Success Rate:99%

Error Streams: Error streams are the same as output streams. In some ide’s, the error is
displayed in different colours (other than the colour of the output colour). It gives output on
the console the same as output streams.

You might also like