Java College Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 176

BASICS OF JAVA

Java is an object-oriented programming language developed by


Sun Micro-Systems in USA in 1971 . It was called originally
Oak by James Goslin the developer of java . JAVA is a purely
object oriented programming language. The code written by us
in the machine is first converted into the byte code by the java
compiler(javac) and then it is interpreted into the machine code.

SOURCE --------> BYTECODE -----------> MACHINE


CODE CODE

INSTALLATION IN JAVA

JDK : - To run our java code we need to install a Java


Development Kit which is a collection of tools used for
developing and running java programs .

CODE EDITOR : - To write our java code we need a place to


write a code where it can be viewed and then sent later on for
execution .

JRE : - Java Runtime Environment helps us to execute our


programs developed in Java.

HELLO WORLD PROGRAM

public class HELLOWORLD {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

EXPLANATION OF ABOVE CODE


package com.company;
public class Main{
public static void main(String args[]){
System.out.println(“Hello World”);
}
}

Here com.company package means that the java program is


stored in the folder com which has a file named company in it .

The main function is here as existent which basically means that


it is the entry point to every program in a java program .

The System.out.println is used to give the output in the java as


in any format .

CLASSES : - A class in java is a set of objects which shares


common characteristics/behaviour and common
properties/attributes . It is a user defined blueprint/prototype
from which objects are created . For - Example: Student is a
class while a particular student named Ravi is an object .

PROPERTIES OF CLASSES : -

1. Class is not a real world entity. It is just a template or


blueprint using which the objects are created .

2. Classes do not occupy memory.

3. Class is a group of variables of different data types and a


group of methods.

4. A class in a java can contain:


 Data Member
 Methods
 Constructor
 Nested class
 Interface

NAMING CONVENCTIONS IN JAVA

 For classes we do use Pascal Convention i.e. the first


letter of every word is capital letter .
 For functions we do use Camel Case Convention i.e.
first letter of every word is capital letter apart from
the first letter and no spaces allowed in both of them .

COMMENTS IN JAVA

Comments in java is a way of writing the notes in java and is


used to hide the text from the compiler in java. The code written
in the comments is ignored by the compiler and is never
executed .

Comments can be classified into two types. They are :

1. SINGLE - LINE COMMENTS : - These comments are


used to comment down a single line in java and cannot be
used to comment multiple lines in java . It is written as // .
2. MULTI-LINE COMMENTS : - These comments are used
to comment multiple lines in java at the same time . This is
denoted by /* */ .

VARIABLES AND DATATYPES IN JAVA

Variables are like a container of some specific data type which


can hold some value in it .
A Data type is defined for a variable and defines the type of the
data one can store in a particular variable . Datatypes can be of
many types such as : -

I. PRIMITIVE DATATYPES : -

 Int(stores integral values in range of -2147483648 to


2147483647)(4 bytes)
 Long(stores integral values in the range of -
9223372036854775808 to 9223372036854775807)(8 bytes)
 Double(stores decimal values in range of 15 decimal
digits)(8 bytes)
 Short(stores integral values in range of -32768 to 32767)(2
bytes)
 Bool(stores the values as true or false)(1 bit)
 Char(stores a single character or an ASCII value)(2 bytes)
 Float(stores fractional values from in range of 6 to 7 digits)(4
bytes)
 Byte(stores integral values in rane of -128 to 127)(1 byte)

II. NON PRIMITIVE DATATYPES : - It consists of objects


classes and many other datatypes like strings arrays etc .
RULES FOR DECLARING VARIABLES

1. Must not begin with an integer or digit .


2. Name is case sensitive.
3. Should not be a keyword(like void).
4. White space is not allowed .
5. Can contain alphabets and characters like $ and _ if only all
the other conditions are met .

WRITE A JAVA PROGRAM TO ADD THREE NUMBERS

public class HELLOWORLD {


public static void main(String[] args) {
int a = 411;
int b = 343;
int c = 422;
int sum = a+b+c;
System.out.println(sum);
}
}

LITERALS

Literals are the constant values that we can assign to the


variables are called as Literals .

For a float literal we do place a ‘f’ after it to specify it as float


else it is taken as a double .

For a long literal we do place a ‘l’ after it to specify it as long .

For a char literal we do place a ‘ ’ surrounding our literal to


specify it as a character .
For a String literal we do place a “ “ surrounding our literal to
specify it as a String of characters.

KEYWORDS

Keywords are reserved words in java that is used to by the java


compiler and cannot be used as a identifier.

There are many keyword in java . They are : -

abstract continue for new switch

assert*** default goto* package synchronized

boolean do if private this


break double implements protected throw

byte else import public throws

case enum**** instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp** volatile

const* float native super while

INPUTS FROM THE USER

In order to take the data as an input from the keyboard we do


use a Scanner class in java to do so . Scanner class has a lot
number of methods to take the inputs from the users throug the
keyboard .

Scanner class in Java is found in the java.util package. Java


provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a
delimiter which is whitespace by default. It provides many
methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings
and primitive types using a regular expression. It is the simplest
way to get input in Java. By the help of Scanner in Java, we can
get input from the user in primitive types such as int, long,
double, byte, float, short, etc.

The Java Scanner class extends Object class and implements


Iterator and Closeable interfaces.

The Java Scanner class provides nextXXX() methods to return


the type of value such as nextInt(), nextByte(), nextShort(),
next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc.
To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.

Java Scanner Class Declaration

1. public final class Scanner


2. extends Object
3. implements Iterator<String>

How to get Java Scanner

To get the instance of Java Scanner which reads input from the
user, we need to pass the input stream (System.in) in the
constructor of Scanner class. For Example:

1. Scanner in = new Scanner(System.in);

To get the instance of Java Scanner which parses the strings, we


need to pass the strings in the constructor of Scanner class. For
Example:

1. Scanner in = new Scanner("Hello Javatpoint");

Java Scanner Class Constructors


SN Constructor Description
1) Scanner(File source) It constructs a new Scanner that produces
values scanned from the specified file.
2) Scanner(File source, It constructs a new Scanner that produces
String charsetName) values scanned from the specified file.
3) Scanner(InputStream It constructs a new Scanner that produces
source) values scanned from the specified input
stream.
4) Scanner(InputStream It constructs a new Scanner that produces
source, String values scanned from the specified input
charsetName) stream.
5) Scanner(Readable It constructs a new Scanner that produces
source) values scanned from the specified source.
6) Scanner(String source) It constructs a new Scanner that produces
values scanned from the specified string.
7) Scanner(ReadableByte It constructs a new Scanner that produces
Channel source) values scanned from the specified channel.
8) Scanner(ReadableByte It constructs a new Scanner that produces
Channel source, String values scanned from the specified channel.
charsetName)
9) Scanner(Path source) It constructs a new Scanner that produces
values scanned from the specified file.
10) Scanner(Path source, It constructs a new Scanner that produces
String charsetName) values scanned from the specified file.

Java Scanner Class Methods

The following are the list of Scanner methods:

SN Modifier & Method Description


Type
1) void close() It is used to close this scanner.
2) pattern delimiter() It is used to get the Pattern which the
Scanner class is currently using to
match delimiters.
3) Stream<Matc findAll() It is used to find a stream of match
hResult> results that match the provided pattern
string.
4) String findInLine() It is used to find the next occurrence of
a pattern constructed from the specified
string, ignoring delimiters.
5) string findWithinHor It is used to find the next occurrence of
izon() a pattern constructed from the specified
string, ignoring delimiters.
6) boolean hasNext() It returns true if this scanner has
another token in its input.
7) boolean hasNextBigDe It is used to check if the next token in
cimal() this scanner's input can be interpreted
as a BigDecimal using the
nextBigDecimal() method or not.
8) boolean hasNextBigInt It is used to check if the next token in
eger() this scanner's input can be interpreted
as a BigDecimal using the
nextBigDecimal() method or not.
9) boolean hasNextBoole It is used to check if the next token in
an() this scanner's input can be interpreted
as a Boolean using the nextBoolean()
method or not.
10) boolean hasNextByte() It is used to check if the next token in
this scanner's input can be interpreted
as a Byte using the nextBigDecimal()
method or not.
11) boolean hasNextDoubl It is used to check if the next token in
e() this scanner's input can be interpreted
as a BigDecimal using the nextByte()
method or not.
12) boolean hasNextFloat() It is used to check if the next token in
this scanner's input can be interpreted
as a Float using the nextFloat() method
or not.
13) boolean hasNextInt() It is used to check if the next token in
this scanner's input can be interpreted
as an int using the nextInt() method or
not.
14) boolean hasNextLine() It is used to check if there is another
line in the input of this scanner or not.
15) boolean hasNextLong() It is used to check if the next token in
this scanner's input can be interpreted
as a Long using the nextLong() method
or not.
16) boolean hasNextShort( It is used to check if the next token in
) this scanner's input can be interpreted
as a Short using the nextShort() method
or not.
17) IOException ioException() It is used to get the IOException last
thrown by this Scanner's readable.
18) Locale locale() It is used to get a Locale of the Scanner
class.
19) MatchResult match() It is used to get the match result of the
last scanning operation performed by
this scanner.
20) String next() It is used to get the next complete
token from the scanner which is in use.
21) BigDecimal nextBigDecim It scans the next token of the input as a
al() BigDecimal.
22) BigInteger nextBigInteger It scans the next token of the input as a
() BigInteger.
23) boolean nextBoolean() It scans the next token of the input into
a boolean value and returns that value.
24) byte nextByte() It scans the next token of the input as a
byte.
25) double nextDouble() It scans the next token of the input as a
double.
26) float nextFloat() It scans the next token of the input as a
float.
27) int nextInt() It scans the next token of the input as
an Int.
28) String nextLine() It is used to get the input string that
was skipped of the Scanner object.
29) long nextLong() It scans the next token of the input as a
long.
30) short nextShort() It scans the next token of the input as a
short.
31) int radix() It is used to get the default radix of the
Scanner use.
32) void remove() It is used when remove operation is not
supported by this implementation of
Iterator.
33) Scanner reset() It is used to reset the Scanner which is
in use.
34) Scanner skip() It skips input that matches the specified
pattern, ignoring delimiters
35) Stream<Strin tokens() It is used to get a stream of delimiter-
g> separated tokens from the Scanner
object which is in use.
36) String toString() It is used to get the string
representation of Scanner using.
37) Scanner useDelimiter() It is used to set the delimiting pattern
of the Scanner which is in use to the
specified pattern.
38) Scanner useLocale() It is used to sets this scanner's locale
object to the specified locale.
39) Scanner useRadix() It is used to set the default radix of the
Scanner which is in use to the specified
radix.

Example 1

Let's see a simple example of Java Scanner where we are getting


a single input from the user. Here, we are asking for a string
through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }

Output:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal

Example 2

1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
4. String s = "Hello, This is JavaTpoint.";
5. //Create scanner Object and pass string in it
6. Scanner scan = new Scanner(s);
7. //Check if the scanner has a token
8. System.out.println("Boolean Result: " + scan.hasNe
xt());
9. //Print the string
10. System.out.println("String: " +scan.nextLine());
11. scan.close();
12. System.out.println("--------Enter Your Details--------
");
13. Scanner in = new Scanner(System.in);
14. System.out.print("Enter your name: ");
15. String name = in.next();
16. System.out.println("Name: " + name);
17. System.out.print("Enter your age: ");
18. int i = in.nextInt();
19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
21. double d = in.nextDouble();
22. System.out.println("Salary: " + d);
23. in.close();
24. }
25. }

Output:

Boolean Result: true


String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

Example 3
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
4. String str = "Hello/This is JavaTpoint/My name is A
bhishek.";
5. //Create scanner with the specified String Object
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasN
extBoolean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.deli
miter());
17. scanner.close();
18. }
19. }

Output:

Boolean Result: false


---Tokenizes String---
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /
JAVA CBSE PERCENTAGE CALCULATOR

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int div = (a+b+c+d+e)/500;
int percentage = div * 100 ;
System.out.println(percentage);
}
}

PRACTICE SET 1

WRITE A PROGRAM TO ADD THREE NUMBERS IN


JAVA

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int sum = (a+b+c+d+e);
System.out.println(sum);
}
}
WRITE A PROGRAM TO PRINT THE CGPA OF A
STUDENT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int cgpa = (a+b+c)/300;
System.out.println(cgpa);
}
}

WRITE A PROGRAM TO TAKE INPUT OF A USER


AND PRINT IT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println("Hello " + a + " , have a good day");
}
}
WRITE A PROGRAM TO CONVERT KILOMETERS TO
MILES

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float kilometers = sc.nextFloat();
float miles = kilometers * (0.62f) ;
System.out.println(miles);
}
}

WRITE A PROGRAM TO CHECK WHETHER THE


ENTERED NUMBER IS INTEGER OR NOT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean a = sc.hasNextInt();
if(a == true){
System.out.println("Integer");
}
else{
System.out.println("Decimal");
}

}
}
************END OF PRACTICE SET
1***********

OPERATORS AND EXPRESSIONS IN JAVA

Operators are used to perform operations on variables and


values . There are a wide variety of operators used in java .
They are :

a. Arithmetic Operators
b. Assignment Operators
c. Comparison Operators
d. Logical Operators
e. Bit wise Operators

ARITHMETIC OPERATORS

It consists of operators like +,-,*,/ and %,++,--,etc These are


used to perform arithmetic operations in java in between two
operands(binary operators) or for one operators(unary
operators) .

BINARY OPERATORS
UNARY OPERATORS

Java unary operators are the types that need only one operand to
perform any operation like increment, decrement, negation, etc.
It consists of various arithmetic, logical and other operators that
operate on a single operand. Let’s look at the various unary
operators in detail and see how they operate.

Operator 1: Unary minus(-)


This operator can be used to convert a positive value to a
negative one.

Syntax:

-(operand)
Illustration:

a = -10
Example:
// Java Program to Illustrate Unary - Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring a custom variable
int n1 = 20;

// Printing the above variable


System.out.println("Number = " + n1);

// Performing unary operation


n1 = -n1;

// Printing the above result number


// after unary operation
System.out.println("Result = " + n1);
}
}

Output
Number = 20
Result = -20
Operator 2: ‘NOT’ Operator(!)
This is used to convert true to false or vice versa. Basically, it
reverses the logical state of an operand.

Syntax:

!(operand)
Illustration:

cond = !true;
// cond < false
Example:

// Java Program to Illustrate Unary NOT Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
boolean cond = true;
int a = 10, b = 1;

// Displaying values stored in above variables


System.out.println("Cond is: " + cond);
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);

// Displaying values stored in above variables


// after applying unary NOT operator
System.out.println("Now cond is: " + !cond);
System.out.println("!(a < b) = " + !(a < b));
System.out.println("!(a > b) = " + !(a > b));
}
}

Output
Cond is: true
Var1 = 10
Var2 = 1
Now cond is: false
!(a < b) = true
!(a > b) = false
Operator 3: Increment(++)
It is used to increment the value of an integer. It can be used in
two separate ways:

3.1: Post-increment operator

When placed after the variable name, the value of the operand is
incremented but the previous value is retained temporarily until
the execution of this statement and it gets updated before the
execution of the next statement.

Syntax:

num++
Illustration:

num = 5
num++ = 6
3.2: Pre-increment operator

When placed before the variable name, the operand’s value is


incremented instantly.

Syntax:

++num
Illustration:

num = 5
++num = 6
Operator 4: Decrement ( — )
It is used to decrement the value of an integer. It can be used in
two separate ways:

4.1: Post-decrement operator

When placed after the variable name, the value of the operand is
decremented but the previous values is retained temporarily
until the execution of this statement and it gets updated before
the execution of the next statement.

Syntax:

num--
Illustration:

num = 5
num-- = 4 // Value will be decremented before execution of next
statement.
4.2: Pre-decrement operator

When placed before the variable name, the operand’s value is


decremented instantly.

Syntax:

--num
Illustration:

num = 5
--num = 4 //output is 5, value is decremented before execution
of next statement
Operator 5: Bitwise Complement(~)
This unary operator returns the one’s complement representation
of the input value or operand, i.e, with all bits inverted, which
means it makes every 0 to 1, and every 1 to 0.

Syntax:
~(operand)
Illustration:

a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
Example:

// Java program to Illustrate Unary


// Bitwise Complement Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring a variable
int n1 = 6, n2 = -2;

// Printing numbers on console


System.out.println("First Number = " + n1);
System.out.println("Second Number = " + n2);

// Printing numbers on console after


// performing bitwise complement
System.out.println(
n1 + "'s bitwise complement = " + ~n1);
System.out.println(
n2 + "'s bitwise complement = " + ~n2);
}
}

Output
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Example program in Java that implements all basic unary
operators for user input:

import java.util.Scanner;

public class UnaryOperators {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Uncomment this block for user input


// System.out.print("Enter a number: ");
// int num = sc.nextInt();

// Initialize num
int num = 10;

// Unary plus
int result = +num;
System.out.println("The value of result after unary plus is:
" + result);

// Unary minus
result = -num;
System.out.println("The value of result after unary minus is:
" + result);
// Pre-increment
result = ++num;
System.out.println("The value of result after pre-increment
is: " + result);

// Post-increment
result = num++;
System.out.println("The value of result after post-
increment is: " + result);

// Pre-decrement
result = --num;
System.out.println("The value of result after pre-decrement
is: " + result);

// Post-decrement
result = num--;
System.out.println("The value of result after post-
decrement is: " + result);

// Close the scanner


sc.close();
}
}

Output
The value of result after unary plus is: 10
The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of re...
Explanation:
The above program implements all basic unary operators in Java
using user input. The program uses the Scanner class from the
java.util package to read user input from the console. The
following steps describe how the program works in detail:
Import the java.util.Scanner class: The program starts by
importing the Scanner class, which is used to read input from
the console.
Create a Scanner object: Next, a Scanner object sc is created and
associated with the standard input stream System.in.
Read the number from the user: The program prompts the user
to enter a number and uses the nextInt() method of the Scanner
class to read the input. The input is stored in the num variable of
type int.
Use unary plus operator: The program uses the unary plus
operator + to perform a positive operation on num. The result of
the operation is stored in the result variable of type int.
Use unary minus operator: The program uses the unary minus
operator – to perform a negative operation on num. The result of
the operation is stored in the result variable.
Use pre-increment operator: The program uses the pre-
increment operator ++ to increment the value of num before
using it in an expression. The result of the operation is stored in
the result variable.
Use post-increment operator: The program uses the post-
increment operator ++ to increment the value of num after using
it in an expression. The result of the operation is stored in the
result variable.
Use pre-decrement operator: The program uses the pre-
decrement operator — to decrement the value of num before
using it in an expression. The result of the operation is stored in
the result variable.
Use post-decrement operator: The program uses the post-
decrement operator — to decrement the value of num after using
it in an expression. The result of the operation is stored in the
result variable.
Print the results: The program prints out the final values of
result using the println method of the System.out object after
each operation.
This program demonstrates how to use basic unary operators in
Java. The Scanner class makes it easy to read user input from
the console, and various unary operators are used to modify the
value of the num variable in the program.
Advantages
The main advantage of using unary operators in Java is that they
provide a simple and efficient way to modify the value of a
variable. Some specific advantages of using unary operators are:

Concise and Easy to Use: Unary operators are simple to use and
require only one operand. They are easy to understand and make
code more readable and concise.
Faster than Other Operators: Unary operators are faster than
other operators as they only require one operand. This makes
them ideal for operations that need to be performed quickly,
such as incrementing a counter.
Pre- and Post-Increment/Decrement: Unary operators provide
both pre- and post-increment and decrement options, which
makes them useful for a variety of use cases. For example, the
pre-increment operator can be used to increment the value of a
variable before using it in an expression, while the post-
increment operator can be used to increment the value of a
variable after using it in an expression.
Modifying Primitive Types: Unary operators can be used to
modify the value of primitive types such as int, long, float,
double, etc.
Overall, unary operators provide a simple and efficient way to
perform operations on variables in Java, and they can be used in
a variety of scenarios to make code more readable and concise.

ASSIGNMENT OPERATORS

These operators are used to assign values to a variable. The left


side operand of the assignment operator is a variable, and the
right side operand of the assignment operator is a value. The
value on the right side must be of the same data type of the
operand on the left side. Otherwise, the compiler will raise an
error. This means that the assignment operators have right to left
associativity, i.e., the value given on the right-hand side of the
operator is assigned to the variable on the left. Therefore, the
right-hand side value must be declared before using it or should
be a constant. The general format of the assignment operator is,

variable operator value;


Types of Assignment Operators in Java
The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment


Operator is used with the “=” sign where the left side consists of
the operand and the right side consists of a value. The value of
the right side must be of the same data type that has been
defined on the left side.

2. Compound Assignment Operator: The Compound Operator is


used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they


operate:

1. (=) operator:
This is the most straightforward assignment operator, which is
used to assign the value on the right to the variable on the left.
This is the basic definition of an assignment operator and how it
functions.

Syntax:

num1 = num2;
Example:

a = 10;
ch = 'y';
// Java code to illustrate "=" operator

import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num;
String name;

// Assigning values
num = 10;
name = "GeeksforGeeks";

// Displaying the assigned values


System.out.println("num is assigned: " + num);
System.out.println("name is assigned: " + name);
}
}
Output
num is assigned: 10
name is assigned: GeeksforGeeks
2. (+=) operator:
This operator is a compound of ‘+’ and ‘=’ operators. It operates
by adding the current value of the variable on the left to the
value on the right and then assigning the result to the operand on
the left.

Syntax:

num1 += num2;
Example:

a += 10

This means,
a = a + 10
// Java code to illustrate "+="

import java.io.*;
class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Adding & Assigning values


num1 += num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = 30
Note: The compound assignment operator in Java performs
implicit type casting. Let’s consider a scenario where x is an int
variable with a value of 5.

int x = 5;

If you want to add the double value 4.5 to the integer variable x
and print its value, there are two methods to achieve this:

Method 1: x = x + 4.5

Method 2: x += 4.5

As per the previous example, you might think both of them are
equal. But in reality, Method 1 will throw a runtime error stating
the “incompatible types: possible lossy conversion from double
to int“, Method 2 will run without any error and prints 9 as
output.

Reason for the Above Calculation


Method 1 will result in a runtime error stating “incompatible
types: possible lossy conversion from double to int.” The reason
is that the addition of an int and a double results in a double
value. Assigning this double value back to the int variable x
requires an explicit type casting because it may result in a loss
of precision. Without the explicit cast, the compiler throws an
error.

Method 2 will run without any error and print the value 9 as
output. The compound assignment operator += performs an
implicit type conversion, also known as an automatic narrowing
primitive conversion from double to int. It is equivalent to x =
(int) (x + 4.5), where the result of the addition is explicitly cast
to an int. The fractional part of the double value is truncated,
and the resulting int value is assigned back to x.

It is advisable to use Method 2 (x += 4.5) to avoid runtime


errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable


for other compound assignment operators as well, including -=,
*=, /=, and %=.

3. (-=) operator:
This operator is a compound of ‘-‘ and ‘=’ operators. It operates
by subtracting the variable’s value on the right from the current
value of the variable on the left and then assigning the result to
the operand on the left.

Syntax:

num1 -= num2;
Example:

a -= 10

This means,
a = a - 10
// Java code to illustrate "-="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Subtracting & Assigning values


num1 -= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = -10
4. (*=) operator:
This operator is a compound of ‘*’ and ‘=’ operators. It
operates by multiplying the current value of the variable on the
left to the value on the right and then assigning the result to the
operand on the left.
Syntax:

num1 *= num2;
Example:

a *= 10
This means,
a = a * 10
// Java code to illustrate "*="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Multiplying & Assigning values


num1 *= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = 200
5. (/=) operator:
This operator is a compound of ‘/’ and ‘=’ operators. It operates
by dividing the current value of the variable on the left by the
value on the right and then assigning the quotient to the operand
on the left.

Syntax:

num1 /= num2;
Example:

a /= 10
This means,
a = a / 10
// Java code to illustrate "/="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 20, num2 = 10;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Dividing & Assigning values


num1 /= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 20
num2 = 10
num1 = 2
6. (%=) operator:
This operator is a compound of ‘%’ and ‘=’ operators. It
operates by dividing the current value of the variable on the left
by the value on the right and then assigning the remainder to the
operand on the left.

Syntax:

num1 %= num2;
Example:

a %= 3

This means,
a=a%3
// Java code to illustrate "%="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 5, num2 = 3;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Moduling & Assigning values


num1 %= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 5
num2 = 3
num1 = 2

COMPARISON OPERATORS

Comparison operators can be classified into many types. They


are as follows : -

1. Relational Operators
2. Logical operators
3. Ternary Operators

RELATIONAL OPERATORS

Java Relational Operators are a bunch of binary operators used


to check for relations between two operands, including equality,
greater than, less than, etc. They return a boolean result after the
comparison and are extensively used in looping statements as
well as conditional if-else statements and so on. The general
format of representing relational operator is:

Syntax:

variable1 relation_operator variable2


Let us look at each one of the relational operators in Java:

Operator 1: ‘Equal to’ operator (==)

This operator is used to check whether the two given operands


are equal or not. The operator returns true if the operand at the
left-hand side is equal to the right-hand side, else false.

Syntax:

var1 == var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 == var2 results in false
Example:

// Java Program to Illustrate equal to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 == var2: "
+ (var1 == var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 == var3: "
+ (var1 == var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
Operator 2: ‘Not equal to’ Operator(!=)

This operator is used to check whether the two given operands


are equal or not. It functions opposite to that of the equal-to-
operator. It returns true if the operand at the left-hand side is not
equal to the right-hand side, else false.

Syntax:

var1 != var2
Illustration:

var1 = "GeeksforGeeks"
var2 = 20

var1 != var2 results in true


Example:

// Java Program to Illustrate No- equal-to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;
// Displaying var1, var2, var3
System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 != var2: "
+ (var1 != var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 != var3: "
+ (var1 != var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 != var2: true
var1 != var3: false
Operator 3: ‘Greater than’ operator(>)

This checks whether the first operand is greater than the second
operand or not. The operator returns true when the operand at
the left-hand side is greater than the right-hand side.

Syntax:

var1 > var2


Illustration:

var1 = 30
var2 = 20

var1 > var2 results in true


Example:

// Java code to Illustrate Greater than operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 30, var2 = 20, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 > var2: " + (var1 > var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var3 > var1: "
+ (var3 >= var1));
}
}
Output
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false
Operator 4: ‘Less than’ Operator(<)

This checks whether the first operand is less than the second
operand or not. The operator returns true when the operand at
the left-hand side is less than the right-hand side. It functions
opposite to that of the greater-than operator.

Syntax:

var1 < var2


Illustration:

var1 = 10
var2 = 20

var1 < var2 results in true


Example:

// Java code to Illustrate Less than Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 20, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);
// Comparing var1 and var2 and
// printing corresponding boolean value
System.out.println("var1 < var2: " + (var1 < var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 < var3: " + (var2 < var3));
}
}
Output
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
Operator 5: Greater than or equal to (>=)

This checks whether the first operand is greater than or equal to


the second operand or not. The operator returns true when the
operand at the left-hand side is greater than or equal to the right-
hand side.

Syntax:

var1 >= var2


Illustration:

var1 = 20
var2 = 20
var3 = 10

var1 >= var2 results in true


var2 >= var3 results in true
Example:

// Java Program to Illustrate Greater than or equal to


// Operator
// Importing I/O classes
import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 20, var2 = 20, var3 = 10;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 >= var2: "
+ (var1 >= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 >= var3: "
+ (var2 >= var3));
}
}
Output
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: true
Operator 6: Less than or equal to (<=)
This checks whether the first operand is less than or equal to the
second operand or not. The operator returns true when the
operand at the left-hand side is less than or equal to the right-
hand side.

Syntax:

var1 <= var2


Illustration:

var1 = 10
var2 = 10
var3 = 9

var1 <= var2 results in true


var2 <= var3 results in false
Example:

// Java Program to Illustrate Less


// than or equal to operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 10, var3 = 9;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);
// Comparing var1 and var2 and
// printing corresponding boolean value
System.out.println("var1 <= var2: "
+ (var1 <= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 <= var3: "
+ (var2 <= var3));
}
}
Output
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false
program that implements all relational operators in Java for user
input:
import java.util.Scanner;

public class RelationalOperators {


public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

//System.out.println("Enter first number: ");


// int num1 = scan.nextInt();

// System.out.println("Enter second number: ");


// int num2 = scan.nextInt();

int num1 =1;


int num2 = 2;

System.out.println("num1 > num2 is " + (num1 > num2));


System.out.println("num1 < num2 is " + (num1 < num2));
System.out.println("num1 >= num2 is " + (num1 >= num2));
System.out.println("num1 <= num2 is " + (num1 <= num2));
System.out.println("num1 == num2 is " + (num1 == num2));
System.out.println("num1 != num2 is " + (num1 != num2));
}
}
Output
num1 > num2 is false
num1 < num2 is true
num1 >= num2 is false
num1 <= num2 is true
num1 == num2 is false
num1 != num2 is true
Explanation
The code above implements all relational operators in Java for
user input. The following is an explanation of the code in detail:
Importing the Scanner class: The code starts by importing the
Scanner class, which is used to read input from the user. The
Scanner class is part of the java.util package, so it needs to be
imported in order to be used.
Defining the main method: The program then defines the main
method, which is the starting point of the program. This is
where the program logic is executed.
Reading user input: The code uses the Scanner object to read
two integers from the user. The first number is stored in the
num1 variable, and the second number is stored in the num2
variable.
Using relational operators: The code then uses the relational
operators >, <, >=, <=, ==, and != to compare the values of
num1 and num2. The results of these comparisons are stored in
boolean variables, which are then displayed to the user.
Displaying results: The results of the comparisons are displayed
to the user using the System.out.println method. This method is
used to print a message to the console.
Closing the Scanner object: Finally, the code closes the Scanner
object to prevent memory leaks and to ensure that the program
terminates cleanly.
The relational operators in Java return a boolean value of true or
false, depending on the result of the comparison. For example,
num1 > num2 returns true if num1 is greater than num2, and
false otherwise. Similarly, num1 == num2 returns true if num1
is equal to num2, and false otherwise.

Advantages
There are several advantages of using relational operators in
Java, including:
Easy to understand: Relational operators are simple and easy to
understand, making it easy to write code that performs
comparisons.
Versatile: Relational operators can be used to compare values of
different data types, such as integers, floating-point numbers,
and strings.
Essential for making decisions: Relational operators are
essential for making decisions in a program, as they allow you
to control the flow of a program based on the results of
comparisons.
Efficient: Relational operators are efficient, as they perform
comparisons quickly and accurately.
Reusable code: The code that uses relational operators can be
reused in different parts of a program, making it easier to
maintain and update the code.
Improved code readability: By using relational operators, you
can make your code more readable and understandable, as the
comparisons are clearly stated in the code.
Debugging made easier: Relational operators make debugging
easier, as you can use them to check the values of variables and
to find out where a problem is occurring in your code.

LOGICAL OPERATORS
Logical operators are used to perform logical “AND”, “OR” and
“NOT” operations, i.e. the function similar to AND gate and OR
gate in digital electronics. They are used to combine two or
more conditions/constraints or to complement the evaluation of
the original condition under particular consideration. One thing
to keep in mind is, while using AND operator, the second
condition is not evaluated if the first one is false. Whereas while
using OR operator, the second condition is not evaluated if the
first one is true, i.e. the AND and OR operators have a short-
circuiting effect. Used extensively to test for several conditions
for making a decision.

AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true to execute
else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
Example For Logical Operator in Java
Here is an example depicting all the operators where the values
of variables a, b, and c are kept the same for all the situations.

a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a

Condition 2: c > b

Output:

True [Both Conditions are true]

For OR Operator:

Condition 1: c > a
Condition 2: c > b

Output:

True [One of the Condition if true]

For NOT Operator:

Condition 1: c > a

Condition 2: c > b

Output:

False [Because the result was true and NOT operator did it’s
opposite]

Logical ‘AND’ Operator (&&)


This operator returns true when both the conditions under
consideration are satisfied or are true. If even one of the two
yields false, the operator results false. In Simple terms, cond1
&& cond2 returns true when both cond1 and cond2 are true (i.e.
non-zero).

Syntax:

condition1 && condition2


Illustration:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b == c
if(condition1 && condition2)
d=a+b+c

// Since both the conditions are true


d = 50.
Example:

// Java code to illustrate


// logical AND operator

import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);

// using logical AND to verify


// two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}

Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

Now in the below example, we can see the short-circuiting


effect. Here when the execution reaches to if statement, the first
condition inside the if statement is false and so the second
condition is never checked. Thus the ++b(pre-increment of b)
never happens, and b remains unchanged.

Example:

import java.io.*;

class shortCircuiting {
public static void main(String[] args)
{

// initializing variables
int a = 10, b = 20, c = 15;

// displaying b
System.out.println("Value of b : " + b);

// Using logical AND


// Short-Circuiting effect as the first condition is
// false so the second condition is never reached
// and so ++b(pre increment) doesn't take place and
// value of b remains unchanged
if ((a > c) && (++b > c)) {
System.out.println("Inside if block");
}

// displaying b
System.out.println("Value of b : " + b);
}
}
Output:

AND Operator Output


Logical ‘OR’ Operator (||)
This operator returns true when one of the two conditions under
consideration is satisfied or is true. If even one of the two yields
true, the operator results true. To make the result false, both the
constraints need to return false.

Syntax:

condition1 || condition2
Example:

a = 10, b = 20, c = 20

condition1: a < b

condition2: b > c

if(condition1 || condition2)

d=a+b+c

// Since one of the condition is true

d = 50.

Illustration:

// Java code to illustrate


// logical OR operator

import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1, c = 10, d = 30;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
System.out.println("Var4 = " + d);

// using logical OR to verify


// two constraints
if (a > b || c == d)
System.out.println(
"One or both + the conditions are true");
else
System.out.println(
"Both the + conditions are false");
}
}

Output
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true

Now in the below example, we can see the short-circuiting


effect for OR operator. Here when the execution reaches to if
statement, the first condition inside the if statement is true and
so the second condition is never checked. Thus the ++b (pre-
increment of b) never happens, and b remains unchanged.
Example:

import java.io.*;

class ShortCircuitingInOR {
public static void main (String[] args) {

// initializing variables
int a = 10, b = 20, c = 15;

// displaying b
System.out.println("Value of b: " +b);

// Using logical OR
// Short-circuiting effect as the first condition is true
// so the second condition is never reached
// and so ++b (pre-increment) doesn't take place and
// value of b remains unchanged
if((a < c) || (++b < c))
System.out.println("Inside if");

// displaying b
System.out.println("Value of b: " +b);

}
}

Output
Value of b: 20
Inside if
Value of b: 20

Logical ‘NOT’ Operator (!)


Unlike the previous two, this is a unary operator and returns true
when the condition under consideration is not satisfied or is a
false condition. Basically, if the condition is false, the operation
returns true and when the condition is true, the operation returns
false.

Syntax:

!(condition)
Example:

a = 10, b = 20

!(a<b) // returns false

!(a>b) // returns true

Illustartion:

// Java code to illustrate


// logical NOT operator
import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);

// Using logical NOT operator


System.out.println("!(a < b) = " + !(a < b));
System.out.println("!(a > b) = " + !(a > b));
}
}
Output
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

Implementing all logical operators on Boolean values (By


default values – TRUE or FALSE)
Syntax:
boolean a = true;
boolean b = false;
Example:

public class LogicalOperators {


public static void main(String[] args) {
boolean a = true;
boolean b = false;

System.out.println("a: " + a);


System.out.println("b: " + b);
System.out.println("a && b: " + (a && b));
System.out.println("a || b: " + (a || b));
System.out.println("!a: " + !a);
System.out.println("!b: " + !b);
}
}

Output
a: true
b: false
a && b: false
a || b: true
!a: false
!b: true
Explanation:
The code above is a Java program that implements all logical
operators with default values. The program defines a class
LogicalOperators with a main method.
In the main method, two boolean variables a and b are defined
and assigned default values true and false, respectively.
The program then prints the values of a and b to the console
using the System.out.println method. This allows us to verify the
values assigned to a and b.
Next, the program calculates the result of the logical operators
&& (and), || (or), and ! (not) applied to a and b. The results of
these operations are also printed to the console using the
System.out.println method.
The && operator returns true if both operands are true;
otherwise, it returns false. In this case, the result of a && b is
false.
The || operator returns true if either operand is true; otherwise, it
returns false. In this case, the result of a || b is true.
The ! operator negates the value of its operand. If the operand is
true, the result is false, and if the operand is false, the result is
true. In this case, the results of !a and !b are false and true,
respectively.
The output of the program shows the truth table for all logical
operators. This table provides a visual representation of how
these operators behave for all possible combinations of true and
false inputs.
Advantages of logical operators:
Short-circuit evaluation: One of the main advantages of logical
operators is that they support short-circuit evaluation. This
means that if the value of an expression can be determined
based on the left operand alone, the right operand is not
evaluated at all. While this can be useful for optimizing code
and preventing unnecessary computations, it can also lead to
subtle bugs if the right operand has side effects that are expected
to be executed.
Readability: Logical operators make code more readable by
providing a clear and concise way to express complex
conditions. They are easily recognizable and make it easier for
others to understand the code.
Flexibility: Logical operators can be combined in various ways
to form complex conditions, making the code more flexible.
This allows developers to write code that can handle different
scenarios and respond dynamically to changes in the program’s
inputs.
Reusability: By using logical operators, developers can write
code that can be reused in different parts of the program. This
reduces the amount of code that needs to be written and
maintained, making the development process more efficient.
Debugging: Logical operators can help to simplify the
debugging process. If a condition does not behave as expected,
it is easier to trace the problem by examining the results of each
logical operator rather than having to navigate through a
complex code structure.
Disadvantages of logical operators:
Limited expressiveness: Logical operators have a limited
expressive power compared to more complex logical constructs
like if-else statements and switch-case statements. This can
make it difficult to write complex conditionals that require more
advanced logic, such as evaluating multiple conditions in a
specific order.
Potential for confusion: In some cases, the use of logical
operators can lead to confusion or ambiguity in the code. For
example, consider the expression a or b and c. Depending on the
intended order of operations, this expression can have different
interpretations. To avoid this kind of confusion, it is often
recommended to use parentheses to explicitly specify the order
of evaluation.
Boolean coercion: Logical operators can sometimes lead to
unexpected behavior when used with non-Boolean values. For
example, when using the or operator, the expression a or b will
evaluate to a if a is truthy, and b otherwise. This can lead to
unexpected results if a or b are not actually Boolean values, but
instead have a truthy or false interpretation that does not align
with the programmer’s intentions.
Overall, logical operators are an important tool for developers
and play a crucial role in the implementation of complex
conditions in a program. They help to improve the readability,
flexibility, reusability, and debuggability of the code.

TERNARY OPERATORS

Java ternary operator is the only conditional operator that takes


three operands. It’s a one-liner replacement for the if-then-else
statement and is used a lot in Java programming. We can use the
ternary operator in place of if-else conditions or even switch
conditions using nested ternary operators. Although it follows
the same algorithm as of if-else statement, the conditional
operator takes less space and helps to write the if-else statements
in the shortest way possible.

Ternary Operator in Java

Syntax:

variable = Expression1 ? Expression2: Expression3

If operates similarly to that of the if-else statement as in


Exression2 is executed if Expression1 is true else Expression3 is
executed.

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Example:

num1 = 10;
num2 = 20;

res=(num1>num2) ? (num1+num2):(num1-num2)

Since num1<num2,
the second operation is performed
res = num1-num2 = -10

Flowchart of Ternary Operation


Flowchart for Ternary Operator

Examples of Ternary Operators in Java


Example 1:
Below is the implementation of the Ternary Operator:

// Java program to find largest among two


// numbers using ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, max;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;
// Print the largest number
System.out.println("Maximum is = " + max);
}
}

Output
First num: 5
Second num: 10
Maximum is = 10

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2:
Below is the implementation of the above method:

// Java code to illustrate ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, res;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);

// Performing ternary operation


res = (n1 > n2) ? (n1 + n2) : (n1 - n2);

// Print the largest number


System.out.println("Result = " + res);
}
}

Output
First num: 5
Second num: 10
Result = -5

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)

Example 3:
Implementing ternary operator on Boolean values:

// Java Program for Implementing


// Ternary operator on Boolean values

// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";

System.out.println(result);
}
}

Output
True

Explanation of the above method:


In this program, a Boolean variable condition is declared and
assigned the value true. Then, the ternary operator is used to
determine the value of the result string. If the condition is true,
the value of result will be “True”, otherwise it will be “False”.
Finally, the value of result is printed to the console.

Advantages of Java Ternary Operator


Compactness: The ternary operator allows you to write simple
if-else statements in a much more concise way, making the code
easier to read and maintain.
Improved readability: When used correctly, the ternary operator
can make the code more readable by making it easier to
understand the intent behind the code.
Increased performance: Since the ternary operator evaluates a
single expression instead of executing an entire block of code, it
can be faster than an equivalent if-else statement.
Simplification of nested if-else statements: The ternary operator
can simplify complex logic by providing a clean and concise
way to perform conditional assignments.
Easy to debug: If a problem occurs with the code, the ternary
operator can make it easier to identify the cause of the problem
because it reduces the amount of code that needs to be examined.
It’s worth noting that the ternary operator is not a replacement
for all if-else statements. For complex conditions or logic, it’s
usually better to use an if-else statement to avoid making the
code more difficult to understand.

BITWISE OPERATORS

Bitwise operators are used to performing the manipulation of


individual bits of a number. They can be used with any integral
type (char, short, int, etc.). They are used when performing
update and query operations of the Binary indexed trees.

Now let’s look at each one of the bitwise operators in Java:

1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit
by bit OR of input values, i.e., if either of the bits is 1, it gives 1,
else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’ It returns bit


by bit AND of input values, i.e., if both bits are 1, it gives 1, else
it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)

This operator is a binary operator, denoted by ‘^.’ It returns bit


by bit XOR of input values, i.e., if corresponding bits are
different, it gives 1, else it shows 0.

Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the


one’s complement representation of the input value, i.e., with all
bits inverted, which means it makes every 0 to 1, and every 1 to
0.

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e.,
2’s complement of 10 will be -6.

// Java program to illustrate


// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise not
// ~00000000 00000000 00000000 00000101=11111111
11111111 11111111 11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}

Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Auxiliary space:O(1)
Time complexity:O(1)

// Demonstrating the bitwise logical operators

class GFG {
public static void main (String[] args) {

String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};

// initializing the values of a and b


int a=3; // 0+2+1 or 0011 in binary
int b=6; // 4+2+0 or 0110 in binary

// bitwise or
int c= a | b;

// bitwise and
int d= a & b;

// bitwise xor
int e= a ^ b;

// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;

System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}

Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)

Shift operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively.
They can be used when we have to multiply or divide a number
by two.

Syntax:

number shift_op number_of_places_to_shift;


Types of Shift Operators:

Shift Operators are further divided into 3 types. These are:

Signed Right shift operator (>>)


Unsigned Right shift operator (>>>)
Left shift operator(<<)
Note: For more detail about the Shift Operators in Java, refer
Shift Operator in Java.

program to implement all Bitwise operators in java for user


input
import java.util.Scanner;

public class BitwiseOperators {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = input.nextInt();

System.out.print("Enter second number: ");


int num2 = input.nextInt();

System.out.println("Bitwise AND: " + (num1 & num2));


System.out.println("Bitwise OR: " + (num1 | num2));
System.out.println("Bitwise XOR: " + (num1 ^ num2));
System.out.println("Bitwise NOT: " + (~num1));
System.out.println("Bitwise Left Shift: " + (num1 << 2));
System.out.println("Bitwise Right Shift: " + (num1 >> 2));
System.out.println("Bitwise Unsigned Right Shift: " +
(num1 >>> 2));

input.close();
}
}
Input

Enter first number: 4


Enter second number: 8
Output

Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two numbers, num1
and num2. It then performs the following bitwise operations
using the &, |, ^, ~, <<, >>, and >>> operators:

Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift

Advantages
The advantages of using Bitwise Operators in Java are:

Speed: Bitwise operations are much faster than arithmetic


operations as they operate directly on binary representations of
numbers.
Space Optimization: Bitwise operations can be used to store
multiple values in a single variable, which can be useful when
working with limited memory.
Bit Manipulation: Bitwise operators allow for precise control
over individual bits of a number, which can be useful in various
applications such as cryptography, error detection, and
compression.
Code Simplification: Bitwise operations can simplify the code
by reducing the number of conditional statements and loops
required to perform certain tasks.
In summary, Bitwise Operators are an important tool for
optimizing performance, improving code readability, and
reducing code complexity in Java applications.
SHIFT OPERATORS

By shifting the bits of its first operand right or left, a shift


operator performs bit manipulation on data. The shift operators
available in the Java programming language are listed below.
The shift operator is a java operator that is used to shift bit
patterns right or left.

Types of Shift Operators in Java:


Name of operator

Sign Description
Signed Left Shift << The left shift operator moves all bits
by a given number of bits to the left.
Signed Right Shift >> The right shift operator moves all
bits by a given number of bits to the right.
Unsigned Right Shift >>> It is the same as the signed right
shift, but the vacant leftmost position is filled with 0 instead of
the sign bit.
1. Signed Left Shift Operator in Java
This operator is represented by a symbol <<, read as double less
than.

Syntax:

left_operand << number


Illustration:

// Left Shifting a byte value

class GFG {
public static void main(String[] args)
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte)(a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Calculating the value of number<<2 if number=2. When the
value of a number is shifted to the left two places, the leftmost
two bits are lost. The number has a value of two. 0010 is the
binary representation of the number 2. In the following example,
the method for doing a left shift is explained:

Example:

In the below example below, the binary number 0010 (in


decimal 2) becomes 1000 after shifting the bits to the left (in
decimal 8).

// Java Program to demonstrate


// Signed Left-Shift Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// main driver method


public static void main(String[] args)
{
int number = 2;

// 2 bit left shift operation


int Ans = number << 2;

System.out.println(Ans);
}
}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a number in a given
number of places to the right. The >> sign represents the right
shift operator, which is understood as double greater than. When
you type x>>n, you tell the computer to move the bits x to the
right n places.

When we shift a number to the right, the least significant bits


(rightmost) are deleted, and the sign bit is filled in the most
considerable place (leftmost).

Syntax:

left_operand >> number


Illustration:

Calculate the value of number>>2 if number=8.

When the value of a number is shifted to the right two places,


the rightmost two bits are lost. The number has a value of eight.
1000 is the binary representation of the number 8. The following
is an example of how to perform the right shift:

In the example above, the binary number 1000 (in decimal 8)


becomes 0010 after shifting the bits to the right (in decimal 2).

Example:

// Java program to demonstrate


// the Signed right shift operator
import java.io.*;
class GFG
{
public static void main (String[] args) {
{
int number = 8;

// 2 bit signed right shift


int Ans = number >> 2;

System.out.println(Ans);
}
}
}

// Masking sign extension

class GFG {
public static void main (String[] args) {
char hex[]={
'0','1','2','3','4','5',
'6','7','8','9','a','b','c',
'd','e','f'
};

byte b=(byte) 0xf1;

System.out.println("b = 0x" + hex [(b>>4) & 0x0f] + hex[b


& 0x0f]);
}
}
3. Unsigned Right Shift Operator in Java
Unsigned Right Shift Operator moves the bits of the integer a
given number of places to the right. The sign bit was filled with
0s. The Bitwise Zero Fill Right Shift Operator is represented by
the symbol >>>.
Syntax:

left_operand >>> number

// Java program to demonstrate


// the Unsigned right shift operator
import java.io.*;

class GFG
{
public static void main (String[] args)
{
byte num1 = 8;
byte num2 = -8;

System.out.println(num1 >>> 2);


System.out.println(num2 >>> 2);
}
}
Output
2
1073741822
Note: For negative bits, the signed and unsigned right shift
operators provide different results.

4. Unsigned Left Shift Operator in Java


Unlike unsigned Right Shift, there is no “<<<” operator in Java
because the logical (<<) and arithmetic left-shift (<<<)
operations are identical.
PRECEDENCE OF OPERATORS

Precedence Operator Type Associativity


() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Left to Right
-- Unary post-decrement
13 ++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

ASSOCIATIVITY OF OPERATORS

Java Operator Precedence and Associativity

Operators Precedence Associativity

postfix increment and decrement ++ -- left to right


prefix increment and decrement, and
++ -- + - ~ ! right to left
unary

multiplicative * / % left to right

additive + - left to right

shift << >> >>> left to right

relational < > <= >= instanceof left to right

equality == != left to right

bitwise AND & left to right

bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

ternary ? : right to left

= += -= *= /= %=
assignment &= ^= |= right to left
<<= >>= >>>=

CHAPER 2 PRACTICE SET

DETERMINE THE OUTPUT OF


Float a = 7/4*9/2

public class HELLOWORLD{


public static void main(String[] args) {
float a = 7/4*9/2;
System.out.println(a);
}
}

OUTPUT :
4.0

ENCRYPT A GRADE BY ADDING 8 TO IT

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int grade = sc.nextInt();
int newgrade = grade + 8;
System.out.println(grade);
}
}

COMPARE A GIVEN NUMBER TO ENTERED NUMBER

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 10;
int b = sc.nextInt();
if(a>b){
System.out.println("Smaller");
}
else{
System.out.println("Bigger");
}
}
}

WRITE THE GIVEN EXPRESSION


import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v,u,a,s ;
v = sc.nextInt();
u = sc.nextInt();
a = sc.nextInt();
s = sc.nextInt();
int x = (v*v - u*u)/(2*a*s);
System.out.println(x);
}
}

FIND THE VALUE OF EXPRESSION

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 7*49/7+35/7 ;
System.out.println(a);
}
}
****************END OF PRACTICE SET
2******************

STRINGS IN JAVA

Strings are the type of objects that can store the character of
values and in Java, every character is stored in 16 bits i,e using
UTF 16-bit encoding. A string acts the same as an array of
characters in Java.

Example:
String name = "Geeks";
String Example in Java
String Example in Java

Below is an example of a String in Java:

// Java Program to demonstrate


// String
public class StringExample {

// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
// this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.

System.out.println(str);
}
}

Output
example
Ways of Creating a String
There are two ways to create a string in Java:

String Literal
Using new Keyword
Syntax:

<String_Type> <string_variable> = "<sequence_of_string>";


1. 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 = “GeeksforGeeks”;


2. Using new keyword
String s = new String(“Welcome”);
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 demoString = new String (“GeeksforGeeks”);


Interfaces and Classes in Strings in Java
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= "geeks";


or
String str= new String("geeks")
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("GeeksforGeeks");


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("GFG");
StringTokenizer
StringTokenizer class in Java is used to break a string into
tokens.

Example:
String Tokenizer in Java
A StringTokenizer object internally maintains a current position
within the string to be tokenized. Some operations advance this
current position past the characters processed. A token is
returned by taking a substring of the string that was used to
create the StringTokenizer object.

StringJoiner is a class in java.util package which is used to


construct a sequence of characters(strings) separated by a
delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix. Though this can also be done with
the help of the StringBuilder class to append a delimiter after
each string, StringJoiner provides an easy way to do that without
much code to write.

Syntax:

public StringJoiner(CharSequence delimiter)


Above we saw we can create a string by String Literal.

String demoString =”Welcome”;

Here the JVM checks the String Constant Pool. If the string does
not exist, then a new string instance is created and placed in a
pool. If the string exists, then it will not create a new object.
Rather, it will return the reference to the same instance. The
cache that stores these string instances is known as the String
Constant pool or String Pool. In earlier versions of Java up to
JDK 6 String pool was located inside PermGen(Permanent
Generation) space. But in JDK 7 it is moved to the main heap
area.

Immutable String in Java


In Java, 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.
Below is the implementation of the topic:

// Java Program to demonstrate Immutable String in Java


import java.io.*;

class GFG {
public static void main(String[] args)
{
String s = "Sachin";

// concat() method appends


// the string at the end
s.concat(" Tendulkar");

// This will print Sachin


// because strings are
// immutable objects
System.out.println(s);
}
}

Output
Sachin
Here Sachin is not changed but a new object is created with
“Sachin Tendulkar”. That is why a string is known as immutable.

As you can see in the given figure that two objects are created
but s reference variable still refers to “Sachin” and not to
“Sachin Tendulkar”. But if we explicitly assign it to the
reference variable, it will refer to the “Sachin Tendulkar” object.

For Example:

// Java Program to demonstrate Explicitly assigned strings


import java.io.*;

class GFG {
public static void main(String[] args)
{
String name = "Sachin";
name = name.concat(" Tendulkar");
System.out.println(name);
}
}

Output
Sachin Tendulkar
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 = "Geeks";


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.

Example:

String demoString = new String("Geeks");


If you want to store this string in the constant pool then you will
need to “intern” it.

Example:

String internedString = demoString.intern();


// this will add the string to string constant pool.
It is preferred to use String literals as it allows JVM to optimize
memory allocation.

An example that shows how to declare a String

// Java code to illustrate String


import java.io.*;
import java.lang.*;

class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String name = "GeeksforGeeks";

// Prints the String.


System.out.println("String name = " + name);

// Declare String using new operator


String newString = new String("GeeksforGeeks");

// Prints the String.


System.out.println("String newString = " + newString);
}
}

Output
String name = GeeksforGeeks
String newString = GeeksforGeeks

Note: String Object is created in Heap area and Literals are


stored in special memory area known as string constant pool.

Why did the String pool move from PermGen to the normal
heap area?
PermGen space is limited, the default size is just 64 MB. it was
a problem with creating and storing too many string objects in
PermGen space. That’s why the String pool was moved to a
larger heap area. To make Java more memory efficient, the
concept of string literal is used. By the use of the ‘new’ keyword,
The JVM will create a new string object in the normal heap area
even if the same string object is present in the string pool.

For example:

String demoString = new String("Bhubaneswar");


Let us have a look at the concept with a Java program and
visualize the actual JVM memory structure:

Below is the implementation of the above approach:

// Java program and visualize the


// actual JVM memory structure
// mentioned in image
class StringStorage {
public static void main(String args[])
{
// Declaring Strings
String s1 = "TAT";
String s2 = "TAT";
String s3 = new String("TAT");
String s4 = new String("TAT");

// Printing all the Strings


System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
Output
TAT
TAT
TAT
TAT
String Pool in Java
String Pool in Java

Note: All objects in Java are stored in a heap. The reference


variable is to the object stored in the stack area or they can be
contained in other objects which puts them in the heap area also.

Example 1:

// Construct String from subset of char array

// Driver Class
class GFG {
// main function
public static void main(String args[])
{
byte ascii[] = { 71, 70, 71 };

String firstString = new String(ascii);


System.out.println(firstString);

String secondString = new String(ascii, 1, 2);


System.out.println(secondString);
}
}

Output
GFG
FG
Example 2:
// Construct one string from another

class GFG {
public static void main(String args[])
{

char characters[] = { 'G', 'f', 'g' };

String firstString = new String(characters);


String secondString = new String(firstString);

System.out.println(firstString);
System.out.println(secondString);
}
}

Output
Gfg
Gfg

STRING METHODS

Method Description Return Type

charAt() Returns the character at the specified index char


(position)

codePointAt() Returns the Unicode of the character at the int


specified index

codePointBefore() Returns the Unicode of the character before int


the specified index

codePointCount() Returns the number of Unicode values found int


in a string.

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, int


ignoring case differences

concat() Appends a string to the end of another String


string

contains() Checks whether a string contains a boolean


sequence of characters
contentEquals() Checks whether a string contains the exact boolean
same sequence of characters of the
specified CharSequence or StringBuffer

copyValueOf() Returns a String that represents the String


characters of the character array

endsWith() Checks whether a string ends with the boolean


specified character(s)

equals() Compares two strings. Returns true if the boolean


strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the String


specified locale, format string, and
arguments

getBytes() Converts a string into an array of bytes byte[]

getChars() Copies characters from a string to an array void


of chars

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found int


occurrence of specified characters in a
string

intern() Returns the canonical representation for the String


string object

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

join() Joins one or more strings with a specified String


separator

lastIndexOf() Returns the position of the last found int


occurrence of specified characters in a
string

length() Returns the length of a specified string int

matches() Searches a string for a match against a boolean


regular expression, and returns the matches

offsetByCodePoints() Returns the index within this String that is int


offset from the given index by
codePointOffset code points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, and String


returns a new string where the specified
values are replaced

replaceAll() Replaces each substring of this string that String


matches the given regular expression with
the given replacement

replaceFirst() Replaces the first occurrence of a substring String


that matches the given regular expression
with the given replacement
split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with boolean


specified characters

subSequence() Returns a new character sequence that is a CharSequence


subsequence of this sequence

substring() Returns a new string which is the substring String


of a specified string

toCharArray() Converts this string to a new character char[]


array

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a String


string

valueOf() Returns the string representation of the String


specified value

ESCAPE SEQUENCES IN JAVA

Control Sequence:
A control sequence is nothing however the backslash(\) glued
with a character (the character which has to be escaped) is called
a control sequence.

Example:

\\ is a control sequence used for displaying a backslash as output.


so let’s use this concept in the previous java code to avoid the
compile-time error:

Java
public class Test {
public static void main(String[] args)
{
System.out.println("Hi geek, welcome to
\"GeeksforGeeks\".");
}
}
Output: Hi geek, welcome to "GeeksforGeeks".
Some Coding Examples of Java Escape Characters

Java code for the escape sequence \t:


Java
// \t -> It gives a tab between two words.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning\t Geeks! ");
}
}

Output:
Good Morning Geeks!
Java code for the escape sequence \b :
Java
// The escape sequence \b is a backspace character
// It moves the cursor one character back with
// or without deleting the character(depending upon compiler)

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning\bg Geeks! ");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!

Java code for the escape sequence \n :


Java
// This \n escape sequence is for a new line.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \n How are you
all? ");
}
}

Output:
Good Morning Geeks!
How are you all?

Java code for the escape sequence \r:


Java
// This \r escape sequence is a carriage return character
// It moves the output point back to the beginning of the line
without moving down a line (usually).

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \r How are you
all? ");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!
How are you all?

Java code for the escape sequence \f:


Java
// This \f escape sequence is a form feed character
// It is an old technique and used to indicate a page break.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \f How are you
all? ");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!
How are you all?

Java code for the escape sequence \’


Java
// This \' escape sequence is for printing a single quotation mark
on the text string

public class Gfg {


public static void main(String[] args)
{
System.out.println("Good Morning \'Geeks!\' How are you
all? ");
}
}

Output:
Good Morning 'Geeks!' How are you all?
Java code for the escape sequence \”
Java
// This \" escape sequence is for printing a double quotation
mark on the text string

public class Gfg {


public static void main(String[] args)
{
System.out.println("Good Morning \"Geeks!\" How are
you all? ");
}
}

Output:
Good Morning "Geeks!" How are you all?
Java code for the escape sequence \\
Java
// This \\ escape sequence is for printing a backslash on the text
string

public class Gfg {


public static void main(String[] args)
{
System.out.println("\\- this is a backslash. ");
}
}

Output:
\- this is a backslash.
Explanation:It contains two backslashes, this means after
reading the first \ the compiler read the next \ as a new character
STRINGS PRACTICE SET

CONVERT A STRING TO LOWER CASE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.toLowerCase());
}
}

CONVERTING SPACES TO UNDERSCORES IN STRING

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.replace(" ", "_"));
}
}

REPLACING A NAME WITH ANOTHER ONE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Yash Thanks a Lot";
System.out.println(letter.replace("Yash", a));
}
}

DETECTING THE PRESENCE OF DOUBLE AND


TRIPLE SPACES

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = a.replace(" ", "--");
String c = a.replace(" ", "---");
System.out.println(b);
System.out.println(c);
}
}

USE ESCAPE SEQUENCE TO MAKE A TITLE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Harry , This java course is nice .
Thanks ! ";
}
}
************END OF PRACTICE SET ON
STRINGS***********

CONDITIONALS

Conditional statements are used to take decisions based on some


specific conditions. There are two types of conditionals . They
are : -

1) If - Else Statements.

2) Switch Case Statements .

IF - ELSE STATEMENTS

Decision-making in Java helps to write decision-driven


statements and execute a particular set of code based on certain
conditions. The if statement alone tells us that if a condition is
true it will execute a block of statements and if the condition is
false it won’t. In this article, we will learn about Java if-else.

If-Else in Java
If- else together represents the set of Conditional statements in
Java that are executed according to the condition which is true.

Syntax of if-else Statement


if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Java if-else Flowchart
Java if-else flowchart

if-else Program in Java


Dry-Run of if-else statements
1. Program starts.
2. i is initialized to 20.
3. if-condition is checked. 20<15, yields false.
4. flow enters the else block.
4.a) "i is greater than 15" is printed
5. "Outside if-else block" is printed.
Below is the implementation of the above statements:

// Java program to illustrate if-else statement

class IfElseDemo {
public static void main(String args[])
{
int i = 20;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");

System.out.println("Outside if-else block");


}
}

Output
i is greater than 15
Outside if-else block
Nested if statement in Java
In Java, we can use nested if statements to create more complex
conditional logic. Nested if statements are if statements inside
other if statements.
Syntax:
if (condition1) {
// code block 1
if (condition2) {
// code block 2
}
}
Below is the implementation of Nested if statements:

// Java Program to implementation


// of Nested if statements

// Driver Class
public class AgeWeightExample {
// main function
public static void main(String[] args) {
int age = 25;
double weight = 65.5;

if (age >= 18) {


if (weight >= 50.0) {
System.out.println("You are eligible to donate
blood.");
} else {
System.out.println("You must weigh at least 50
kilograms to donate blood.");
}
} else {
System.out.println("You must be at least 18 years old to
donate blood.");
}
}
}

Output
You are eligible to donate blood.
Note: The first print statement is in a block of “if” so the second
statement is not in the block of “if”. The third print statement is
in else but that else doesn’t have any corresponding “if”. That
means an “else” statement cannot exist without an “if” statement.

SWITCH - CASE STATEMENTS

Unlike if-then and if-then-else statements, the switch statement


can have a number of possible execution paths. A switch works
with the byte, short, char, and int primitive data types. It also
works with enumerated types (discussed in Enum Types),
the String class, and a few special classes that wrap certain
primitive types: Character, Byte, Short, and Integer (discussed
in Numbers and Strings).

The following code example, SwitchDemo, declares


an int named month whose value represents a month. The code
displays the name of the month, based on the value of month,
using the switch statement.

public class SwitchDemo {


public static void main(String[] args) {

int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}

In this case, August is printed to standard output.

The body of a switch statement is known as a switch block. A


statement in the switch block can be labeled with one or
more case or default labels. The switch statement evaluates its
expression, then executes all statements that follow the
matching case label.

You could also display the name of the month with if-then-
else statements:

int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on

Deciding whether to use if-then-else statements or


a switch statement is based on readability and the expression
that the statement is testing. An if-then-else statement can test
expressions based on ranges of values or conditions, whereas
a switch statement tests expressions based only on a single
integer, enumerated value, or String object.
Another point of interest is the break statement.
Each break statement terminates the enclosing switch statement.
Control flow continues with the first statement following
the switch block. The break statements are necessary because
without them, statements in switch blocks fall through: All
statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered. The
program SwitchDemoFallThrough shows statements in
a switch block that fall through. The program displays the
month corresponding to the integer month and the months that
follow in the year:

public class SwitchDemoFallThrough {

public static void main(String[] args) {


java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();

int month = 8;

switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}

if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}

This is the output from the code:

August
September
October
November
December

Technically, the final break is not required because flow falls


out of the switch statement. Using a break is recommended so
that modifying the code is easier and less error prone.
The default section handles all values that are not explicitly
handled by one of the case sections.
The following code example, SwitchDemo2, shows how a
statement can have multiple case labels. The code example
calculates the number of days in a particular month:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:

Number of Days = 29

Using Strings in switch Statements

In Java SE 7 and later, you can use a String object in


the switch statement's expression. The following code
example, StringSwitchDemo, displays the number of the month
based on the value of the String named month:

public class StringSwitchDemo {

public static int getMonthNumber(String month) {

int monthNumber = 0;

if (month == null) {
return monthNumber;
}

switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}

return monthNumber;
}

public static void main(String[] args) {

String month = "August";

int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);

if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}

The output from this code is 8.

The String in the switch expression is compared with the


expressions associated with each case label as if
the String.equals method were being used. In order for
the StringSwitchDemo example to accept any month regardless
of case, month is converted to lowercase (with
the toLowerCase method), and all the strings associated with
the case labels are in lowercase.

Note: This example checks if the expression in


the switch statement is null. Ensure that the expression in
any switch statement is not null to prevent
a NullPointerException from being thrown.

PRACTICE SET CHAPTER 4

DETERMINE THE OUTPUT

public class HELLOWORLD{


public static void main(String[] args) {
int a =10;
if(a=11){
System.out.println("i am 11");
}
else{
System.out.println("i am not 11");
}
}
}

OUTPUT :
I am 11
DETERMINE IF A STUDENT IS PASS OR FAIL

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int percentage = ((a+b+c)/300) * 100;
if(a>33 && b>33 && c>33 && percentage > 40){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}

INCOME TAX CALCULATION

import java.util.Scanner;
class Income
{
public static void main(String args[])
{
double tax=0,it;
Scanner sc=new Scanner(System.in);
System.out.println("Enter income ");
it=sc.nextDouble();
if(it<=200000)
tax=0;
else if(it<=300000)
tax=0.1*(it-200000);
else if(it<=500000)
tax=(0.2*(it-300000))+(0.1*100000);
else if(it<=1000000)
tax=(0.3*(it-500000))+(0.2*200000)+(0.1*100000);
else
tax=(0.4*(it-
1000000))+(0.3*500000)+(0.2*200000)+(0.1*100000);
System.out.println("Income tax amount is "+tax);
}
}

WEEKDAYS OF THE WEEK

import java.util.Scanner;
public class Exercise5 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int day = in.nextInt();
System.out.println(getDayName(day));
}
// Get the name for the Week
public static String getDayName(int day) {
String dayName = "";
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default:dayName = "Invalid day range";
}
return dayName;
}
}

*******END OF PRACICE SET ON IF - ELSE *******

ROCK - PAPER - SCISSORS GAMES IN JAVA

import java.util.*;
public class RockPaperScissor {

public static void main(String[] args) {

Scanner scn = new Scanner(System.in);

while(true) {

//1. RANDOMIZED COMPUTER MOVE

// array of string containing available


moves.
String [] availableMoves = {"Rock",
"Paper", "Scissors"};

// using Random() function on indices of


array so that it chooses a random move.
String computerMove =
availableMoves[new Random().nextInt(availableMoves.length)];

System.out.println("Computer has chosen


it's move.");
System.out.println();
System.out.println("Now it's your turn to
choose. Good Luck!");
System.out.println();
//2. PLAYER MOVE

//input
String userMove;

// loop until the user chooses the correct


move
while(true) {
System.out.println("Please choose
your move from these available moves : 'Rock' 'Paper' 'Scissors'
");
System.out.println("Enter the move
you chose : ");
userMove = scn.nextLine();

// checking if user's move is one of


the available moves or not
if(userMove.equals("Rock") ||
userMove.equals("Paper") || userMove.equals("Scissors")){
System.out.println();
break;
}

// if user didn't enter a valid input


System.out.println();
System.out.println("Invalid
Move!!");
System.out.println("Please enter the
move from the available moves only!");
System.out.println();
}

//printing what computer chose


System.out.println("Computer chose : " +
computerMove);
//3. COMPARING THE MOVES & DECIDING
THE WINNER

// checking for a tie

if(userMove.equals(computerMove)) {
System.out.println("Its a tie!");
}

//checking for all other moves possible

else if(userMove.equals("Rock")) {

if(computerMove.equals("Paper"))
{

System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
else
if(computerMove.equals("Scissors")) {
System.out.println("You
won!");

System.out.println("Congratulations!");
}
}

else if(userMove.equals("Paper")) {

if(computerMove.equals("Rock"))
{
System.out.println("You
won!");

System.out.println("Congratulations!");
}
else
if(computerMove.equals("Scissors")) {

System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
}

else if(userMove.equals("Scissors")) {

if(computerMove.equals("Paper"))
{
System.out.println("You
won!");

System.out.println("Congratulations!");
}
else
if(computerMove.equals("Rock")) {

System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
}

System.out.println();
String playAgain;
System.out.println("Do you want to play
again? ");

// loop until the user chooses the correct


option
while(true) {
System.out.println("Type 'yes' or
'no' ");
playAgain = scn.nextLine();

if(playAgain.equals("yes") ||
playAgain.equals("Yes") || playAgain.equals("no") ||
playAgain.equals("No")) {
System.out.println();

System.out.println("*****************************
************************************************");
System.out.println();
break;
}
System.out.println();
System.out.println("Invalid Input");
System.out.println();
}

if(playAgain.equals("no") ||
playAgain.equals("No")) {
break;
}
}
}}

Output 1 (Computer Won):

Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available moves : 'Rock'


'Paper' 'Scissors'
Enter the move you chose :
Paper

Computer chose : Scissors


Computer won!
Better luck next time!

Do you want to play again?


Type 'yes' or 'no'
Yes
***************************************************
*********

Output 2 (Player wins):

Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available moves : 'Rock'


'Paper' 'Scissors'
Enter the move you chose :
Rock

Computer chose : Scissors


You won!
Congratulations!

Do you want to play again?


Type 'yes' or 'no'
yes
***************************************************
*********

Output 3 (It's a Tie):


Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available moves : 'Rock'


'Paper' 'Scissors'
Enter the move you chose :
Rock

Computer chose : Rock


Its a tie!

Do you want to play again?


Type 'yes' or 'no'
No
***************************************************
********

LOOPS IN JAVA

Looping in programming languages is a feature which facilitates


the execution of a set of instructions/functions repeatedly while
some condition evaluates to true. Java provides three ways for
executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and
condition checking time.

There are three types of loops in java . They are : -

1. For Loops
2. While Loops
3. Do - While Loops

FOR LOOPS
Loops in Java come into use when we need to repeatedly
execute a block of statements. Java for loop provides a concise
way of writing the loop structure. The for statement consumes
the initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.
Let us understand Java for loop with Examples.

For Loop in Java

Syntax:

for (initialization expr; test expr; update exp)


{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop


Java for loop is divided into various parts as mentioned below:

Initialization Expression
Test Expression
Update Expression
1. Initialization Expression
In this expression, we have to initialize the loop counter to some
value.

Example:

int i=1;

2. Test Expression
In this expression, we have to test the condition. If the condition
evaluates to true then, we will execute the body of the loop and
go to the update expression. Otherwise, we will exit from the for
a loop.
Example:

i <= 10

3. Update Expression:
After executing the loop body, this expression
increments/decrements the loop variable by some value.

Example:

i++;

How does a For loop work?


Control falls into the for loop. Initialization is done
The flow jumps to Condition
Condition is tested.
If the Condition yields true, the flow goes into the Body
If the Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
The flow goes to the Updation
Updation takes place and the flow goes to Step 3 again
The for loop has ended and the flow has gone outside.
Flow Chart For “for loop in Java”
Flow chart for loop in Java
Flow chart for loop in Java

Examples of Java For loop


Example 1: (This program will print 1 to 10)
Java

/*package whatever //do not write package name here */


// Java program to write a code in for loop from 1 to 10

class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10

Example 2: This program will try to print “Hello World” 5 times.


Java

// Java program to illustrate for loop


class forLoopDemo {
public static void main(String args[])
{
// Writing a for loop
// to print Hello World 5 times
for (int i = 1; i <= 5; i++)
System.out.println("Hello World");
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
The complexity of the method:
Time Complexity: O(1)
Auxiliary Space : O(1)

Dry-Running Example 1
The program will execute in the following manner.

Program starts.
i is initialized with value 1.
Condition is checked. 1 <= 5 yields true.
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 <= 5 yields true.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 <= 5 yields true.
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 <= 5 yields true.
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 <= 5 yields true.
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 <= 5 yields false.
Flow goes outside the loop. Program terminates.
Example 3: (The Program prints the sum of x ranging from 1 to
20)
Java

// Java program to illustrate for loop.


class forLoopDemo {
public static void main(String args[])
{
int sum = 0;
// for loop begins
// and runs till x <= 20
for (int x = 1; x <= 20; x++) {
sum = sum + x;
}
System.out.println("Sum: " + sum);
}
}
Output
Sum: 210

Nested For Loop in Java


Java Nested For Loop is a concept of using a for loop inside
another for loop(Similar to that of using nested if-else). Let us
understand this with an example mentioned below:

Java

// Java Program to implement


// Nested for loop
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times)
// first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
12345
12345
12345
12345
12345

To know more about Nested loops refer Nested loops in Java.

Java For-Each Loop


Enhanced For Loop or Java For-Each loop in Java is another
version of for loop introduced in Java 5. Enhanced for loop
provides a simpler way to iterate through the elements of a
collection or array. It is inflexible and should be used only when
there is a need to iterate through the elements in a sequential
manner without knowing the index of the currently processed
element.

Note: The object/variable is immutable when enhanced for loop


is used i.e it ensures that the values in the array can not be
modified, so it can be said as a read-only loop where you can’t
update the values as opposed to other loops where values can be
modified.

Syntax:

for (T element:Collection obj/array)


{
// loop body
// statement(s)
}
Let’s take an example to demonstrate how enhanced for loop
can be used to simplify the work. Suppose there is an array of
names and we want to print all the names in that array. Let’s see
the difference between these two examples by this simple
implementation:

Java

// Java program to illustrate enhanced for loop


public class enhancedforloop {

// Main Function
public static void main(String args[])
{
// String array
String array[] = { "Ron", "Harry", "Hermoine" };

// enhanced for loop


for (String x : array) {
System.out.println(x);
}

/* for loop for same function


for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
Output
Ron
Harry
Hermoine

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space : O(1)

Recommendation: Use this form of statement instead of the


general form whenever possible. (as per JAVA doc.)

Java Infinite for Loop


This is an infinite loop as the condition would never return false.
The initialization step is setting up the value of variable i to 1,
since we are incrementing the value of i, it would always be
greater than 1 so it would never return false. This would
eventually lead to the infinite loop condition.

Example:

Java
// Java infinite loop
class GFG {
public static void main(String args[])
{
for (int i = 1; i >= 1; i++) {
System.out.println("Infinite Loop " + i);
}
}
}
Output
Infinite Loop 1
Infinite Loop 2
...

There is another method for calling the Infinite loop

If you use two semicolons ;; in the for loop, it will be infinitive


for a loop.

Syntax:
for(;;){
//code to be executed
}

Example:

Java
public class GFG {
public static void main(String[] args)
{
for (;;) {
System.out.println("infinitive loop");
}
}
}
Output
infinite loop
infinite loop
....

WHILE LOOP

Java while loop is a control flow statement that allows code to


be executed repeatedly based on a given Boolean condition. The
while loop can be thought of as a repeating if statement. While
loop in Java comes into use when we need to repeatedly execute
a block of statements. The while loop is considered as a
repeating if statement. If the number of iterations is not fixed, it
is recommended to use the while loop.

while loop in Java

Syntax:

while (test_expression)
{
// statements
update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after
while( condition ) then by default while statement will consider
the immediate one statement to be inside its block.

while (test_expression)
// single statement in while only

Parts of Java While Loop


The various parts of the While loop are:

1. Test Expression: In this expression, we have to test the


condition. If the condition evaluates to true then we will execute
the body of the loop and go to update expression. Otherwise, we
will exit from the while loop.

Example:

i <= 10
2. Update Expression: After executing the loop body, this
expression increments/decrements the loop variable by some
value.

Example:

i++;
How Does a While loop execute?
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone outside.
Flowchart For while loop (Control Flow):
Flow chart while loop (for Control Flow

Examples of Java while loop


Example 1: This program will try to print “Hello World” 5 times.

// Java program to illustrate while loop.

class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
System.out.println("Hello World");

// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space : O(1)
Dry-Running Example 1: The program will execute in the
following manner.

1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.

Example 2: This program will find the summation of numbers


from 1 to 10.

// Java program to illustrate while loop

class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;

// Exit when x becomes greater than 4


while (x <= 10) {
// summing up x
sum = sum + x;

// Increment the value of x for


// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
Output
Summation: 55

Complexity of the above method


Time Complexity: O(1)
Auxiliary Space : O(1)

DO - WHILE LOOPS

Loops in Java come into use when we need to repeatedly


execute a block of statements. Java do-while loop is an Exit
control loop. Therefore, unlike for or while loop, a do-while
check for the condition after executing the statements of the
loop body.

Syntax:

do
{
// Loop Body
Update_expression
}

// Condition check
while (test_expression);
Note: The test_expression for the do-while loop must return a
boolean value , else we would get compile-time error.
Application of do-while : Its example application is showing
some kind of menu to the users.

For example:

You are implementing a game where you show some options to


the user, press 1 to do this .., press 2 to do this .. etc and press ‘Q’
to quit the game. So here you want to show the game menu to
the user at least once, so you write the code for the game menu
inside the do-while loop.

Illustration:

// Java Program to Illustrate One Time Iteration


// Inside do-while Loop
// When Condition IS Not Satisfied

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// initial counter variable
int i = 0;

do {

// Body of loop that will execute minimum


// 1 time for sure no matter what
System.out.println("Print statement");
i++;
}
// Checking condition
// Note: It is being checked after
// minimum 1 iteration
while (i < 0);
}
}
Output
Print statement
Output explanation:

In the above code, we figured out that the condition is checked


later as the body inside do will get executed one time without
fail as the condition is checked later onwards. Hence whenever
we want to display the menu and later on proceed command on
the terminal, we always use do-while loop.

Components of do-while Loop


A. Test Expression: In this expression, we have to test the
condition. If the condition evaluates to true then we will execute
the body of the loop and go to update expression. Otherwise, we
will exit from the while loop. For example:

i <= 10
B. Update Expression: After executing the loop body, this
expression increments/decrements the loop variable by some
value. For example:

i++;
Execution of do-While loop
Control falls into the do-while loop.
The statements inside the body of the loop get executed.
Updation takes place.
The flow jumps to Condition
Condition is tested.
If Condition yields true, go to Step 6.
If Condition yields false, the flow goes outside the loop
The flow goes back to Step 2.
Flowchart do-while loop:

Implementation:

Example 1: This program will try to print “Hello World” 5 times.

// Java Program to Illustrate Do-while Loop

// Class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initialization expression


int i = 1;

// Do-while loop
do {

// Body of do-while loop


// Print statement
System.out.println("Hello World");

// Update expression
i++;
}

// Test expression
while (i < 6);
}
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World

Auxiliary Space: O(1)

Output explanation:

The program will execute in the following manner as follows:

Program starts.
i is initialized with value 1.
Execution enters the loop
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 < 6 yields true.
Execution enters the loop.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 < 6 yields false.
The flow goes outside the loop.
Example 2
// Java Program to Illustrate Do-while Loop

// Class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring and initializing integer values
int x = 21, sum = 0;

// Do-while loop
do {

// Execution statements(Body of loop)

// Here, the line will be printed even


// if the condition is false
sum += x;
x--;
}

// Now checking condition


while (x > 10);

// Summing up
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 176

Example 3: do-while loop without curly braces {}


/*package whatever //do not write package name here */

import java.io.*;

class GFG {
public static void main (String[] args) {
int i=1;
do
// only single statement in do block
System.out.println("Hello GFG!");
// this condition is false so only do block will execute
while(i>=3);

}
}
Output
Hello GFG!

BREAK AND CONTINUE STATEMENTS

The break and continue statements are the jump statements that
are used to skip some statements inside the loop or terminate the
loop immediately without checking the test expression. These
statements can be used inside any loops such as for, while, do-
while loop.

Break: The break statement in java is used to terminate from the


loop immediately. When a break statement is encountered inside
a loop, the loop iteration stops there, and control returns from
the loop immediately to the first statement after the loop.
Basically, break statements are used in situations when we are
not sure about the actual number of iteration for the loop, or we
want to terminate the loop based on some condition.
Syntax :

break;
In Java, a break statement is majorly used for:

To exit a loop.
Used as a “civilized” form of goto.
Terminate a sequence in a switch statement.
Using break to exit a loop

Using break, we can force immediate termination of a loop,


bypassing the conditional expression and any remaining code in
the body of the loop. When we use break inside the nested loops,
it will only break out of the innermost loop.

Example:

Java
// Java program to demonstrate using
// break to exit a loop
class GFG {
public static void main(String[] args)
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Out of Loop");
}
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto

Java does not have a goto statement because it provides a way to


branch in an arbitrary and unstructured manner. Java uses a
label. A Label is used to identify a block of code.

Syntax:

label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump out of the target
block. We cannot break to any label which is not defined for an
enclosing block.

Syntax:

break label;
Example:

Java
// Java program to demonstrates using break with goto
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using break statement with label


break first;
}
System.out.println(i + " " + j);
}
}
}
}
Output
00
01
02
10
Using break to terminate a sequence in a switch statement.

The switch statement is a multi-way branch statement. It


provides an easy way to dispatch execution to different parts of
code based on the value of the expression. The break statement
is used inside the switch to terminate a statement sequence. The
break statement is optional. If omitted, execution will continue
on into the next case.

Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:

Java
// Java program to demonstrate using break to terminate a
// sequence in a switch statement.
class GFG {
public static void main(String args[])
{
int i = 2;
switch (i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("Invalid number");
}
}
}
Output
i is two.
Continue:

The continue statement in Java is used to skip the current


iteration of a loop. We can use continue statement inside any
types of loops such as for, while, and do-while loop. Basically
continue statements are used in the situations when we want to
continue the loop but do not want the remaining statement after
the continue statement.

Syntax:

continue;
Using continue to continue a loop

Using continue, we can skip the current iteration of a loop and


jumps to the next iteration of the loop immediately.

Example:

Java
// Java program to demonstrates the continue
// statement to continue a loop
class GFG {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is 2
// skip and continue
if (i == 2)
continue;

System.out.print(i + " ");


}
}
}
Output
013456789
Using continue as a labelled continue statement

The unlabeled continue statement is used to continue the


innermost loop. However, since JDK 1.5 java introduces another
feature known as labelled continue statement. We can use a
labelled continue statement to continue the outermost loop.

Example:

Java
// Java program to demonstrates labeled continue statement
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using continue statement with label


continue first;
}
System.out.println(i + " " + j);
}
}
}
}
Output
00
01
02
10
20
21
22
Break Continue

The break statement is used to The continue statement is used to skip


terminate the loop immediately. the current iteration of the loop.

break keyword is used to indicate continue keyword is used to indicate


break statements in java programming. continue statement in java programming.

We can use a break with the switch We can not use a continue with the
statement. switch statement.

The break statement terminates the The continue statement brings the next
whole loop early. iteration early.

It does not stop the execution of the


It stops the execution of the loop.
loop.

PRACTICE SET ON LOOPS

PATTERN PRINTING

public class HELLOWORLD {

public static void main(String[] args)


{
for(int i=4;i>=0;i--){
for(int j=0;j<i;j++){
System.out.print("*");
}
System.out.println();
}
}
}

SUM OF FIRST N EVEN NUMBERS


import java.util.*;
import java.lang.*;

public class GfG{

// function to find sum of


// first n even numbers
static int evenSum(int n)
{
int curr = 2, sum = 0;

// sum of first n even numbers


for (int i = 1; i <= n; i++) {
sum += curr;

// next even number


curr += 2;
}

// required sum
return sum;
}

// driver function
public static void main(String argc[])
{
int n = 20;
System.out.println("Sum of first " + n +
" Even numbers is: " +
evenSum(n));
}

PRINTING MULLTIPLICATION TABLE OF A GIVEN


NO.
import java.util.Scanner;

public class Exercise7 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input a number


System.out.print("Input a number: ");

// Read and store the input number


int num1 = in.nextInt();

// Use a loop to calculate and print the multiplication table for


the input number
for (int i = 0; i < 10; i++) {
// Calculate and print the result of num1 multiplied by (i+1)
System.out.println(num1 + " x " + (i + 1) + " = " + (num1 * (i
+ 1)));
}
}
}

Whatever we can do using one type of loop can be done using


another type of loops as well .

*************END OF PRACTICE SET ON


LOOPS************

FOR EACH LOOPS

For-each is another array traversing technique like for loop,


while loop, do-while loop introduced in Java5.
It starts with the keyword for like a normal for-loop.
Instead of declaring and initializing a loop counter variable, you
declare a variable that is the same type as the base type of the
array, followed by a colon, which is then followed by the array
name.
In the loop body, you can use the loop variable you created
rather than using an indexed array element.

It’s commonly used to iterate over an array or a Collections


class (eg, ArrayList)
Syntax:

for (type var : array)


{
statements using var;
}
Simple program with for each loop:

/*package whatever //do not write package name here */

import java.io.*;

class Easy

public static void main(String[] args)

// array declaration

int ar[] = { 10, 50, 60, 80, 90 };


for (int element : ar)

System.out.print(element + " ");


}
}

Output

10 50 60 80 90
The above syntax is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}
// Java program to illustrate
// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };

int highest_marks = maximum(marks);


System.out.println("The highest score is " +
highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];

// for each loop


for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
}

Output

The highest score is 132


Limitations of for-each loop
decision-making

For-each loops are not appropriate when you want to modify the
array:

for (int num : marks)


{
// only changes num, not the array element
num = num*2;
}
2. For-each loops do not keep track of index. So we can not
obtain array index using For-Each loop

for (int num : numbers)


{
if (num == target)
{
return ???; // do not know the index of num
}
}
3. For-each only iterates forward over the array in single
steps
// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}
4. For-each cannot process two decision making statements
at once

// cannot be easily converted to a for-each loop


for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}
5. For-each also has some performance overhead over
simple iteration:

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime -
startTime) + " ms");

// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime
- startTime) + " ms");

// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: "
+ (endTime - startTime) + " ms");

// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] ::
" + (endTime - startTime) + " ms");
}
}

// This code is contributed by Ayush Choudhary


@gfg(code_ayush)
Output

For each loop :: 45 ms


Using collection.size() :: 11 ms
By calculating collection.size() first :: 13 ms
Using [int j = list.size(); j > size ; j--] :: 15 ms

ARRAYS IN JAVA

In Java, Array is a group of like-typed variables referred to by a


common name. Arrays in Java work differently than they do in
C/C++. Following are some important points about Java arrays.

Arrays in Java
In Java, all arrays are dynamically allocated. (discussed below)
Arrays may be stored in contiguous memory [consecutive
memory locations].
Since arrays are objects in Java, we can find their length using
the object property length. This is different from C/C++, where
we find length using size of.
A Java array variable can also be declared like other variables
with [] after the data type.
The variables in the array are ordered, and each has an index
beginning with 0.
Java array can also be used as a static field, a local variable, or a
method parameter.
An array can contain primitives (int, char, etc.) and object (or
non-primitive) references of a class, depending on the definition
of the array. In the case of primitive data types, the actual values
might be stored in contiguous memory locations (JVM does not
guarantee this behavior). In the case of class objects, the actual
objects are stored in a heap segment. To learn more about Java
Array, go through Java programming course here.

Java Arrays
Note: This storage of arrays helps us randomly access the
elements of an array [Support Random Access].

Creating, Initializing, and Accessing an Arrays


One-Dimensional Arrays
The general form of a one-dimensional array declaration is

-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type and the name.
type declares the element type of the array. The element type
determines the data type of each element that comprises the
array. Like an array of integers, we can also create an array of
other primitive data types like char, float, double, etc., or user-
defined data types (objects of a class). Thus, the element type
for the array determines what type of data the array will hold.

Example:

// both are valid declarations


int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
Although the first declaration establishes that int Array is an
array variable, no actual array exists. It merely tells the compiler
that this variable (int Array) will hold an array of the integer
type. To link int Array with an actual, physical array of integers,
you must allocate one using new and assign it to int Array.

Instantiating an Array in Java


When an array is declared, only a reference of an array is
created. To create or give memory to the array, you create an
array like this: The general form of new as it applies to one-
dimensional arrays appears as follows:

var-name = new type [size];


Here, type specifies the type of data being allocated, size
determines the number of elements in the array, and var-name is
the name of the array variable that is linked to the array. To use
new to allocate an array, you must specify the type and number
of elements to allocate.

Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will
automatically be initialized to zero (for numeric types), false
(for boolean), or null (for reference types). Do refer to default
array values in Java.

Obtaining an array is a two-step process. First, you must declare


a variable of the desired array type. Second, you must allocate
the memory to hold the array, using new, and assign it to the
array variable. Thus, in Java, all arrays are dynamically
allocated.

Array Literal in Java


In a situation where the size of the array and variables of the
array are already known, array literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
The length of this array determines the length of the created
array.
There is no need to write the new int[] part in the latest versions
of Java.
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index
begins with 0 and ends at (total array size)-1. All the elements of
array can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+
arr[i]);
Implementation:

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;
// initialize the second elements of the array
arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)

You can also access java arrays using for each loops.

Arrays-in-Java

Arrays of Objects in Java


An array of objects is created like an array of primitive-type
data items in the following way.

Student[] arr = new Student[5]; //Student is a user-defined class


Syntax:

-- data type[] arrName;


-- datatype arrName[];
-- datatype [] arrName;
Example of Arrays of Objects
Example 1:
Below is the implementation of the above mentioned topic:

import java.io.*;

class GFG {
public static void main (String[] args) {

int [] arr=new int [4];


// 4 is the size of arr

System.out.println("Array Size:"+arr.length);
}
}

Output
Array Size:4
The Student Array contains five memory spaces each of the size
of Student class in which the address of five Student objects can
be stored. The Student objects have to be instantiated using the
constructor of the Student class, and their references should be
assigned to the array elements in the following way.

Example 2:
Below is the implementation of the above mentioned topic:

// Java program to illustrate creating


// an array of objects

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}

// Elements of the array are objects of a class Student.


public class GFG {
public static void main(String[] args)
{
// declares an Array of Student
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");

// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Example 3
An array of objects is also created like :

// Java program to illustrate creating


// an array of objects

class Student
{

public String name;


Student(String name)
{
this.name = name;
}
@Override
public String toString(){
return name;
}
}

// Elements of the array are objects of a class Student.


public class GFG
{
public static void main (String[] args)
{
// declares an Array and initializing the elements of the
array
Student[] myStudents = new Student[]{new
Student("Dharma"),new Student("sanvi"),new
Student("Rupa"),new Student("Ajay")};

// accessing the elements of the specified array


for(Student m:myStudents){
System.out.println(m);
}
}
}

Output
Dharma
sanvi
Rupa
Ajay
What happens if we try to access elements outside the array size?
JVM throws ArrayIndexOutOfBoundsException to indicate that
the array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of an array.

Below code shows what happens if we try to access elements


outside the array size:

// Code for showing error "ArrayIndexOutOfBoundsException"

public class GFG {


public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;

System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output

Trying to access element outside the size of array


Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of
bounds for length 4
at GFG.main(GFG.java:13)
Example (Iterating the array):

public class GFG {


public static void main(String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

for (int i = 0; i < arr.length; i++)


System.out.println(arr[i]);
}
}

Output
10
20
Complexity of the above method:
Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space required.

Multidimensional Arrays in Java


Multidimensional arrays are arrays of arrays with each element
of the array holding the reference of other arrays. These are also
known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.
Syntax of Java Multidimensional Array
There are 2 methods to declare Java Multidimensional Arrays as
mentioned below:

-- datatype [][] arrayrefvariable;


-- datatype arrayrefvariable[][];
Example:

// Java Program to demonstrate


// Java Multidimensional Array
import java.io.*;

// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);

// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}

Output
Number of Rows:3
Number of Columns:3
MultiDimensional-Array

Multidimensional Array Declaration


int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Example of Muilti Dimensional Array in Java
Example 1:
Below is the implementation of the above method:

// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example,
the below program passes the array to method sum to calculate
the sum of the array’s values.

// Java program to demonstrate


// passing of array to method

public class Test {


// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum += arr[i];

System.out.println("sum of array values : " + sum);


}
}

Output
sum of array values : 15
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Returning Arrays from Methods


As usual, a method can also return an array. For example, the
below program returns an array from method m1.

// Java program to demonstrate


// return of array from method

class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}

Output
123
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Class Objects for Arrays


Every array has an associated Class object, shared with all other
arrays with the same component type.

// Java program to demonstrate


// Class Objects for Arrays
class Test {
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];

// array of Strings
String[] strArray = new String[3];

System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}

Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation of the above method:
The string “[I” is the run-time type signature for the class object
“array with component type int.”
The only direct superclass of an array type is java.lang.Object.
The string “[B” is the run-time type signature for the class
object “array with component type byte.”
The string “[S” is the run-time type signature for the class object
“array with component type short.”
The string “[L” is the run-time type signature for the class object
“array with component type of a Class.” The Class name is then
followed.
Java Array Members
Now, as you know that arrays are objects of a class, and a direct
superclass of arrays is a class Object. The members of an array
type are all of the following:

The public final field length contains the number of components


of the array. Length may be positive or zero.
All the members are inherited from class Object; the only
method of Object that is not inherited is its clone method.
The public method clone() overrides the clone method in class
Object and throws no checked exceptions.
Arrays Types and Their Allowed Element Types
Array Types Allowed Element Types
Primitive Type ArraysAny type which can be implicitly
promoted to declared type.
Object Type Arrays Either declared type objects or it’s child
class objects.
Abstract Class Type Arrays Its child-class objects are allowed.
Interface Type Arrays Its implementation class objects are
allowed.
Cloning of Single-Dimensional Array in Java
When you clone a single-dimensional array, such as Object[], a
shallow copy is performed. This means that the new array
contains references to the original array’s elements rather than
copies of the objects themselves. A deep copy occurs only with
arrays containing primitive data types, where the actual values
are copied.

Below is the implementation of the above method:

// Java program to demonstrate


// cloning of one-dimensional arrays

class Test {
public static void main(String args[])
{
int intArray[] = { 1, 2, 3 };
int cloneArray[] = intArray.clone();

// will print false as shallow copy is created


System.out.println(intArray == cloneArray);

for (int i = 0; i < cloneArray.length; i++) {


System.out.print(cloneArray[i] + " ");
}
}
}

Output
false
123
Explanation of the above Program:
In this example, intArray and cloneArray are not the same
object (intArray == cloneArray is false), but they share the same
contents because primitive values are deeply copied.
For arrays containing objects, the references are copied, so the
objects themselves are not duplicated.
Clone-of-Array

Cloning Multidimensional Array in Java


A clone of a multi-dimensional array (like Object[][]) is a
“shallow copy,” however, which is to say that it creates only a
single new array with each element array a reference to an
original element array, but subarrays are shared.

// Java program to demonstrate


// cloning of multi-dimensional arrays

class Test {
public static void main(String args[])
{
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };
int cloneArray[][] = intArray.clone();

// will print false


System.out.println(intArray == cloneArray);

// will print true as shallow copy is created


// i.e. sub-arrays are shared
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}

Output
false
true
True
PRACTICE SET ON ARRAYS

CREATING AN ARRAY OF 5 FLOATS AND SUMMING


THEM

public class HELLOWORLD{


public static void main(String[] args) {
float []arr = {2.5f,23.25f,45.23f,21.32f,52.36f};
float sum = 0;
for(int i=0;i<arr.length;i++){
sum = sum + arr[i] ;
}
System.out.println(sum);
}
}

FINDING AN ELEMENT IN AN ARRAY

public class HELLOWORLD{


public static void main(String[] args) {
int arr[] = {2,3,4,5,6,7,8};
int element = 8;
for (int i : arr) {
if(arr[i] == element){
System.out.println("Present");
}
else{
System.out.println("Absent");
}
}
}
}
CALCULATING AVERAGE OF ARRAY

public class HELLOWORLD{


public static void main(String[] args) {
int arr[] = {2,3,4,5,6,7,8};
int sum = 0;
for (int i : arr) {
sum = sum + arr[i] ;
}
int avg = sum / arr.length;
System.out.println(avg);
}
}

ADDING TWO MATRICES OF SIZE 2 x 3

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][] = new int[3][3] ;
int arr1[][] = new int[3][3] ;
int sum[][] = new int [3][3];
//INPUT OF ARRAY 1
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr[i][j] = sc.nextInt();
}
}
//INPUT OF ARRAY 2
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr1[i][j] = sc.nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
sum[i][j] = arr[i][j] + arr1[i][j] ;
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}

REVERSE AN ARRAY

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = {3,4,5};
for (int i =0;i<arr.length/2 ; i++) {
int temp = arr[i] ;
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}

FINDING MAXIMUM ELEMENT IN AN ARRAY

// Java Program to find maximum in arr[]

// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};

// Method to find maximum in arr[]


static int largest()
{
int i;

// Initialize maximum element


int max = arr[0];

// Traverse array elements from second and


// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];

return max;
}

// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}

FINDING MINIMUM ELEMENT IN AN ARRAY

import java.util.*;
class Array {
public static void main(String[] args) {
int a[]={1,423,6,46,34,23,13,53,4};

//Implemented inbuilt function to sort array


Arrays.sort(a);

// after sorting the value at 0th position will minimum and


//nth position will be maximum
System.out.println("min-"+a[0]+" max-"+a[a.length-1]);
}
}

SORTING AN ARRAY

import java.util.Arrays;

class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

**********END OF PRACTICE SET ON


ARRAYS*************

You might also like