Java Unit 1
Java Unit 1
What is Java?
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:
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.
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.
Portable: It facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
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.
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.
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-
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.
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;
Data Default
Default size Range
Type Value
9,223,372,036,854,775,808 to
long 0L 8 bytes or 64 bits
9,223,372,036,854,775,807
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.
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:
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.
&& [ logical AND expression1 && (true) only if both of the expressions
] expression2 are true
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
Bitwise Operators: Bitwise Operators in Java are used to assist the performance of the
operations on individual bits.
Operators Descriptions
~ Bitwise Complement
Operators Descriptions
^ 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
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:
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
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.
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
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
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.
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
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
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
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:
Method Declaration:
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.
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
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;
}
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
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
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.
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;
} }
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.
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.
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.
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 name must be same as the The method name may or may not be same as
class name. the class name.
Strings
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.
Methods Description
String StringBuffer
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 was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
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");
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.
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 {
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.