0% found this document useful (0 votes)
5 views

Unit-1 Programming Structures

Unit-1 of Programming Structures in Java covers the fundamental concepts of classes and objects, including class definitions, properties, components, and the syntax for class declarations. It also discusses Java's basic program structure, comments, identifiers, reserved words, data types, and variables. The unit emphasizes the importance of strong typing, memory efficiency, and the immutability of strings in Java.

Uploaded by

Ayush Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit-1 Programming Structures

Unit-1 of Programming Structures in Java covers the fundamental concepts of classes and objects, including class definitions, properties, components, and the syntax for class declarations. It also discusses Java's basic program structure, comments, identifiers, reserved words, data types, and variables. The unit emphasizes the importance of strong typing, memory efficiency, and the immutability of strings in Java.

Uploaded by

Ayush Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Programming Structures in Java (Unit-1)

UNIT-1
PROGRAMMING STRUCTURES IN JAVA

Defining Classes in Java


A class is a basic building block. It can be defined as template that describes the data and behaviour
associated with the class instantiation. Instantiating is a class is to create an object (variable) of that class
that can be used to access the member variables and methods of the class.

A class in Java is a set of objects which shares common characteristics and common properties. It is a
user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Ravi is an object

Properties of Java Classes


 Class is not a real-world entity. It is just a template or blueprint or prototype from which objects
are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of methods.
 A Class in Java can contain:
o Data member
o Method
o Constructor
o Nested Class
o Interface

Components of Java Classes

In general, class declarations can include these components, in order:


 Modifiers: A class can be public or has default access (Refer this for details).
 Class keyword: Class keyword is used to create a class.
 Class name: The name should begin with an initial letter (capitalized by convention).
 Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
 Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
 Body: The class body is surrounded by braces, { }.

Class Declaration in Java

access_modifier class <class_name>


{
//data member / member variables;
//class methods;
//constructor;

1|Page
Programming Structures in Java (Unit-1)

//nested class;
//interface;
}

Java Objects

An object in Java are the instances of a class that are created to use the attributes and methods of a
class. A typical Java program creates many objects, which as you know, interact by invoking methods.

An object consists of:


 State: It is represented by attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an object
with other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other objects.

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, and “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.

Note: When we create an object which is a non-primitive data type, it’s always allocated on the heap
memory.

Using the new keyword is the most popular way to create an object or instance of the class. When we
create an instance of the class by using the new keyword, it allocates memory (heap) for the newly
created object and also returns the reference of that object to that memory. The new keyword is also
used to create an array.

The syntax for creating an object is:


ClassName object = new ClassName();

2|Page
Programming Structures in Java (Unit-1)

Java Basics

 Structure of Java Program


A basic Java program consists of several components that create a functional application:
1
// FileName : "GFG.java".
public class GFG {
// Program begins with a call to main() method
public static void main(String args[])
{
// Prints "Hello World"
System.out.println("Hello World");
}
}

Output
Hello World

Example: Steps to compile and run a java program in a console


To compile: javac GFG.java
to execute: java GFG

Parameters used in First Java Program

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it does not require creating an object to
invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it does not return any value.
o The main() method represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in coming
section.
o System.out.println() is used to print statement on the console. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will discuss
the internal working of System.out.println() statement in the coming section.

3|Page
Programming Structures in Java (Unit-1)

 Java Comments
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Why do we use comments in a code?
o Comments are used to make the program more readable by adding the details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative code.

Types of Java Comments


There are three types of comments in Java.

1) Java Single Line Comment


The single-line comment is used to comment only one line of the code. It is the widely used and easiest
way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.
Syntax:
1. //This is single line comment

2) Java Multi Line Comment


The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex
code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */

3) Java Documentation Comment


Documentation comments are usually used to write large programs for a project or software application
as it helps to create documentation API. These APIs are needed for reference, i.e., which classes,
methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.
Syntax:
1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *

4|Page
Programming Structures in Java (Unit-1)

7. */
 Java Identifiers
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These
are the unique names and every Java Variables must be identified with unique names.

Rules For Naming Java Identifiers


There are certain rules for defining a valid Java identifier. These rules must be followed, otherwise, we
get a compile-time error. These rules are also valid for other languages like C, and C++.
 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]),
‘$‘(dollar sign) and ‘_‘ (underscore). For example “geek@” is not a valid Java identifier as it
contains a ‘@’ a special character.
 Identifiers should not start with digits([0-9]). For example “123geeks” is not a valid Java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15
letters only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as a while is a reserved word. There are 53 reserved words in Java.

Examples of Valid Identifiers:


MyVariable i $myvariable
MYVARIABLE x1 sum_of_array
myvariable i1 geeks123
x _myvariable

Examples of Invalid Identifiers:


My Variable 123geeks a+c variable-2 sum_&_difference

5|Page
Programming Structures in Java (Unit-1)

 Reserved Words and Keywords in Java

Any programming language reserves some words to represent functionalities defined by that
language. These words are called reserved words. They can be briefly categorized into two
parts: keywords (50) and literals (3). Keywords define functionalities and literals define value.
Identifiers are used by symbol tables in various analysing phases (like lexical, syntax, and semantic)
of a compiler architecture.

In Java, Keywords are the Reserved words in a programming language that are used for some internal
process or represent some predefined actions. These words are therefore not allowed to use
as variable names or objects. There are 67 Keywords in Java.

Java Keywords List


Java contains a list of keywords or reserved words which are also highlighted with different colors be
it an IDE or editor in order to segregate the differences between flexible words and reserved words.
They are listed below in the table:
abstract continue for protected transient
Assert Default Goto public Try
Boolean Do If Static throws
break double implements strictfp Package
byte else import super Private
case enum Interface Short switch
Catch Extends instanceof return void
Char Final Int synchronized volatile
class finally long throw Date
const float Native This while

Important Points:
 The keywords const and goto are reserved, even though they are not currently in use.
 Currently, they are no longer supported in Java.
 true, false, and null look like keywords, but in actuality they are literals. However, they still can’t
be used as identifiers in a program.

 Java Data Types

Java is statically typed and also a strongly typed language because, in Java, each type of data (such as
integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming
language and all constants or variables defined for a given program must be described with one of the
Java data types.

Data types in Java


There are of different sizes and values that can be stored in the variable that is made as per convenience
and circumstances to cover up all test cases. Java has two categories in which data types are segregated

6|Page
Programming Structures in Java (Unit-1)

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The Boolean
with uppercase B is a wrapper class for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Data Types in JAVA


1. Primitive Data Types in Java
Primitive data are only single values and have no special capabilities.

There are 8 primitive data types. They are depicted below in tabular format below as follows:

Type Description Default Size Example Literals Range of values


boolean true or false false 8 bits true, false true, false
byte twos- 0 8 bits (none) -128 to 127
complement
integer
char Unicode \u0000 16 bits ‘a’, ‘\u0041’, ‘\101’, characters representation
character ‘\\’, ‘\’, ‘\n’, ‘β’ of ASCII values
0 to 255
short twos- 0 16 bits (none) -32,768 to 32,767
complement
integer
int twos- 0 32 bits -2,-1,0,1,2 -2,147,483,648

7|Page
Programming Structures in Java (Unit-1)

complement to
intger 2,147,483,647
long twos- 0 64 bits -2L,-1L,0L,1L,2L -
complement 9,223,372,036,854,775,808
integer to
9,223,372,036,854,775,807
float IEEE 754 0.0 32 bits 1.23e100f , -1.23e-100f upto 7 decimal digits
floating point , .3f ,3.14F
double IEEE 754 0.0 64 bits 1.23456e300d , - upto 16 decimal digits
floating point 123456e-300d , 1e1d

Why is the Size of char 2 bytes in Java?


Unlike languages such as C or C++ that use the ASCII character set, Java uses the Unicode character
set to support internationalization. Unicode requires more than 8 bits to represent a wide range of
characters from different languages, including Latin, Greek, Cyrillic, Chinese, Arabic, and more. As a
result, Java uses 2 bytes to store a char, ensuring it can represent any Unicode character.

2. Non-Primitive (Reference) Data Types

The Non-Primitive (Reference) Data Types will contain a memory address of variable values because
the reference types won’t store the variable value directly in memory. They are strings, objects, arrays,
etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a string in
Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a
character array is a collection of separate char-type entities. Unlike C/C++, Java strings are not
terminated with a null character.

2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type.

3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods.

4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an interface are
by default abstract (only method signature, no body).

5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++.

8|Page
Programming Structures in Java (Unit-1)

Key Points to Remember


 Strong Typing: Java enforces strict type checking at compile-time, reducing runtime errors.
 Memory Efficiency: Choosing the right data type based on the range and precision needed helps in
efficient memory management.
 Immutability of Strings: Strings in Java cannot be changed once created, ensuring safety in
multithreaded environments.
 Array Length: The length of arrays in Java is fixed once declared, and it can be accessed using
the length attribute

 Java Variables

Variables are the containers for storing the data values or you can also call it a memory location name
for the data. Every variable has a:
 Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
 Variable Name – To identify the variable uniquely within the scope.
 Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and Static.
Example:
int age = 27; // integer variable having value 27

String name = "gfg" // string variable

How to Declare Java Variables?


We can declare variables in Java as pictorially depicted below:

From the image, it can be easily perceived that while declaring a variable, we need to take care of two
things that are:
1. datatype: In Java, a data type define the type of data that a variable can hold.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
 Variable Initialization
 Assigning value by taking input

How to Initialize Java Variables?


It can be perceived with the help of 3 components explained above:

9|Page
Programming Structures in Java (Unit-1)

Example:
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';

Types of Java Variables


Now let us discuss different types of variables which are listed as follows:
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method, constructor,
or block.
3. Static Variables
Static variables are also known as class variables.

Syntax: Static and instance variables


class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

 Scope of Variables in Java

The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java,
all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be determined at compile
time and independent of the function call stack. In this article, we will learn about Java Scope Variables.

Java Scope Rules can be covered under the following categories.

1. Instance Variables – Class Level Scope


These variables must be declared inside class (outside any function). They can be directly accessed
anywhere in class.

2. Static Variables – Class Level Scope


Static Variable is a type of class variable shared across instances. Static Variables are the variables
which once declared can be used anywhere even outside the class without initializing the class. Unlike
Local variables it scope is not limited to the class or the block.

10 | P a g e
Programming Structures in Java (Unit-1)

3. Method Level Scope – Local Variable


Variables declared inside a method have method level scope and can’t be accessed outside the method.

4. Parameter Scope – Local Variable


Here’s another example of method scope, except this time the variable got passed in as a parameter to
the method:

5. Block Level Scope


A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only.

Important Points about Variable Scope in Java


 In general, a set of curly brackets { } defines a scope.
 In Java we can usually access a variable as long as it was defined within the same set of brackets as
the code we are writing or within any curly brackets inside of the curly brackets where the variable
was defined.
 Any variable defined in a class outside of any method can be used by all member methods.
 When a method has the same local variable as a member, “this” keyword can be used to reference
the current class variable.
 For a variable to be read after the termination of a loop, it must be declared before the body of the
loop.

 Java Operators
Java operators are special symbols that perform operations on variables or values. They can be classified
into several categories based on their functionality. These operators play a crucial role in performing
arithmetic, logical, relational, and bitwise operations etc.

Types of Operators in Java


Let’s see all these operators one by one with their proper examples.

1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-primitive
data types.
 * : Multiplication  % : Modulo  – : Subtraction
 / : Division  + : Addition

2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a value.
 - , Negates the value.
 + , Indicates a positive value (automatically converts byte, char, or short to int).
 ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
 -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
 ! , Inverts a boolean value.

11 | P a g e
Programming Structures in Java (Unit-1)

3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e.
value given on the right-hand side of the operator is assigned to the variable on the left, and therefore
right-hand side value must be declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create shorthand compound
statements. For example, a += 5 replaces a = a + 5. Common compound operators include:
 += , Add and assign.  *= , Multiply and assign.  %= , Modulo and assign.
 -= , Subtract and assign.  /= , Divide and assign.

4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is ,
variable relation_operator value
Relational operators compare values and return boolean results:
 == , Equal to.  <= , Less than or equal to.  >= , Greater than or equal
 != , Not equal to.  > , Greater than. to.
 < , Less than.

5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to AND gate
and OR gate in digital electronics. They have a short-circuiting effect, meaning the second condition is
not evaluated if the first is false.
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands and hence the
name Ternary. The general format is ,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the statements after the
‘?’ else execute the statements after the ‘:’.

7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and with any of
the integer types. They are used when performing update and query operations of the Binary indexed
trees.
 & (Bitwise AND) – returns bit-by-bit AND of input values.
 | (Bitwise OR) – returns bit-by-bit OR of input values.
 ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
 ~ (Bitwise Complement) – inverts all bits (one’s complement).

12 | P a g e
Programming Structures in Java (Unit-1)

8. 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.
The general format ,
number shift_op number_of_places_to_shift;
 << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
 >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with the leftmost
bit depending on the sign.
 >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always 0.

9. instanceof operator
The instance of operator is used for type checking. It can be used to test if an object is an instance of a
class, a subclass, or an interface. The general format ,
object instance of class/subclass/interface

Precedence and Associativity of Java Operators


Precedence and associative rules are used when dealing with hybrid equations involving more than one
type of operator. In such cases, these rules determine which part of the equation to consider first, as
there can be many different valuations for the same equation. The below table depicts the precedence of
operators in decreasing order as magnitude, with the top representing the highest precedence and the
bottom showing the lowest precedence.

Advantages of Operators
The advantages of using operators in Java are mentioned below:
1. Expressiveness: Operators in Java provide a concise and readable way to perform complex
calculations and logical operations.

13 | P a g e
Programming Structures in Java (Unit-1)

2. Time-Saving: Operators in Java save time by reducing the amount of code required to perform
certain tasks.
3. Improved Performance: Using operators can improve performance because they are often
implemented at the hardware level, making them faster than equivalent Java code.

Disadvantages of Operators
The disadvantages of Operators in Java are mentioned below:
1. Operator Precedence: Operators in Java have a defined precedence, which can lead to
unexpected results if not used properly.
2. Type Coercion: Java performs implicit type conversions when using operators, which can lead to
unexpected results or errors if not used properly.

 Java User Input

The most common way to take user input in Java is using Scanner class which is part of java.util
package. The scanner class can read input from various sources like console, files or streams. This class
was introduced in Java 5. Before that we use BufferedReader class(Introduced in Java 1.1). As a
beginner, we will suggest to use Scanner class.
Follow these steps to take user input using Scanner class:
 Import the Scanner class using import java.util.Scanner;
 Create the Scanner object and connect Scanner with System.in by passing it as an argument
i.e. Scanner scn = new Scanner(System.in);
 Print a message to prompt for user input and you can use the various methods of Scanner class like
nextInt(), nextLine(), next(), nextDouble etc according to your need.

Scanner class provides some methods to read different data types:


Method Description
nextBoolean() Used for reading Boolean value.
nextByte() Used for reading Byte value.
nextDouble() Used for reading Double value.
nextFloat() Used for reading Float value.
nextInt() Used for reading Int value.
nextLine() Used for reading Line value. (String)
nextLong() Used for reading Long value.
nextShort() Used for reading Short value.

14 | P a g e
Programming Structures in Java (Unit-1)

Java Flow Control


Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear. However, Java provides statements that can be used to control the
flow of Java code. Such statements are called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement

2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop

3. Jump statements
o break statement
o continue statement

 Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.

If Statement:
The Java if statement is the simplest decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is true then a
block of statements is executed otherwise not.

In Java, there are four types of if-statements given below. Let's understand the if-statements one by one.
1. Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }

2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }

15 | P a g e
Programming Structures in Java (Unit-1)

4. else{
5. statement 2; //executes when condition is false
6. }

3. if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words,
we can say that it is the chain of if-else statements that create a decision tree where the program may
enter in the block of code where the condition is true. We can also define an else statement at the end of
the chain.
Syntax of if-else-if statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

5. Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of
the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.

16 | P a g e
Programming Structures in Java (Unit-1)

o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type
as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }

 Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.

1. Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use for loop
only when we exactly know the number of times, we want to execute the block of
code.
1. for(initialization, condition, increment/
decrement) {
2. //block of statements
3. }

2. Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection. In for-each
loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given
below.

17 | P a g e
Programming Structures in Java (Unit-1)

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

3. Java while loop


The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at
the start of the loop. If the condition is true, then the loop body will be
executed; otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }

4. Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop
at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
5. do
1. {
2. //statements
3. } while (condition);

 Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.

1. Java break statement


As the name suggests, the break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside
the loop or switch statement.

The break statement example with for loop


Consider the following example in which we have used the break statement with the for loop.

18 | P a g e
Programming Structures in Java (Unit-1)

2. Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part
of the loop and jumps to the next iteration of the loop immediately.

19 | P a g e
Programming Structures in Java (Unit-1)

Java Methods
A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use
it many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.

All methods in Java must belong to a class. Methods are similar to functions and expose the behavior
of objects.

Syntax of a Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header, as we have shown in the
following figure.

Key Components of a Method Declaration


 Access Modifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
 Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.
 Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. It follows Java naming conventions; it should
start with a lowercase verb and use camel case for multiple words.

20 | P a g e
Programming Structures in Java (Unit-1)

 Parameters: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
 Exception List: The exceptions the method might throw (optional).
 Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

Method Signature
It consists of the method name and a parameter list.
 number of parameters
 type of the parameters
 order of the parameters

Method Signature of the above function:


max(int x, int y) Number of parameters is 2, Type of parameter is int.

Types of Methods in Java


1. Predefined Method
Predefined methods are the method that is already defined in the Java class libraries. It is also
known as the standard library method or built-in method.
Example:
Math.random() // returns random value
Math.PI() // return pi value
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Example:
sayHello // user define method created above in the article
Greet()
setName()

Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a
multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first word,
the first letter of each word should be capitalized.

Rules to Name a Method:


 While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
 If the method name has more than two words, the first name must be a verb followed by an
adjective or noun.
 In the multi-word method name, the first letter of each word must be in uppercase except the
first word. For example, findSum, computeMax, setX, and getX.

21 | P a g e
Programming Structures in Java (Unit-1)

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is simple.
When we call or invoke a user-defined method, the program control transfer to the called method.
ou can call a method by using its name followed by the parentheses and a semicolon.

Below is the syntax for calling a method:


<function-name>(args list);
Or
var = <function-name>(args list);

Arrays in Java
Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a
single variable. They are useful for storing and managing collections of data. Java array is an object
which contains elements of a similar data type. Additionally, the elements of an array are stored in a
contiguous memory location. It is a data structure where we store similar elements. We can store only a
fixed set of elements in a Java array.

 Array Properties
 In Java, all arrays are dynamically allocated .
 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.
 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. For primitive arrays, elements are stored in a contiguous
memory location. For non-primitive arrays, references are stored at contiguous locations, but the
actual objects may be at different locations in memory.

 Advantages and Disadvantages of Array


Advantages of Java Arrays
 Efficient Access: Accessing an element by its index is fast and has constant time complexity,
O(1).
 Memory Management: Arrays have fixed size, which makes memory management
straightforward and predictable.
 Data Organization: Arrays help organize data in a structured manner, making it easier to manage
related elements.

22 | P a g e
Programming Structures in Java (Unit-1)

Disadvantages of Java Arrays


 Fixed Size: Once an array is created, its size cannot be changed, which can lead to memory waste
if the size is overestimated or insufficient storage if underestimated.
 Type Homogeneity: Arrays can only store elements of the same data type, which may require
additional handling for mixed types of data.
 Insertion and Deletion: Inserting or deleting elements, especially in the middle of an array, can
be costly as it may require shifting elements.

 Basics of Arrays in Java


There are some basic operations we can start with as mentioned below:

1. Array Declaration or Creation


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). To declare an array in Java, use the following syntax:
Method 1:
type var-name[];
Method 2:
type[] var-name;
 type: The data type of the array elements (e.g., int, String).
 arrayName: The name of the array.
Note: The array is not yet initialized.

2. Initialization of an Array
When an array is declared, only a reference of an array is created. To create an array, you need to
allocate memory for it using the new keyword:
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.
// Creating an array of 5 integers
int[] numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value for each element is 0.

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.

3. Access an Element of an Array


Now, we have created an Array with or without the values stored in it. Access becomes an important
part to operate over the values mentioned within the array indexes using the points mentioned below:
 Each element in the array is accessed via its index.
 The index begins with 0 and ends at (total array size)-1.

23 | P a g e
Programming Structures in Java (Unit-1)

// Setting the first element of the array


numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the value of the first
element.

All the elements of array can be accessed using Java for Loop. We can access array elements using
their index, which starts from 0:
// Accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println(“Element at index ” + i + ” : “+ arr[i]);

4. Change an Array Element


To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;

5. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = numbers.length;

6. 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.

7. for-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array elements
one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of for-each loop is given below:


1. for(data_type variable:array){
2. //body of the loop
3. }

Let's see the example of printing the elements of the Java array using for-each loop.

 Types of Arrays in Java


Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in a linear order.

24 | P a g e
Programming Structures in Java (Unit-1)

// A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};

2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-
dimensional arrays (matrices).

// A 2D array (matrix)
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

 Arrays of Objects in Java


An array of objects is created like an array of primitive-type data items in the following way.
Syntax:
Method 1:
ObjectType[] arrName;
Method 2:
ObjectType arrName[];

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)

25 | P a g e
Programming Structures in Java (Unit-1)

 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:
There are 2 methods to declare Java Multidimensional Arrays as mentioned below:
// Method 1
datatype [][] arrayrefvariable;

// Method 2
datatype arrayrefvariable[][];

Declaration:
// 2D array or matrix
int[][] intArray = new int[10][20];
// 3D array
int[][][] intArray = new int[10][20][10];

 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

26 | P a g e
Programming Structures in Java (Unit-1)

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

 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

27 | P a g e
Programming Structures in Java (Unit-1)

Java Strings

In Java, String is the type of objects that can store the sequence of characters enclosed by double quotes
and every character is stored in 16 bits i.e using UTF 16-bit encoding. A string acts the same as an array
of characters. Java provides a robust and flexible API for handling strings, allowing for various
operations such as concatenation, comparison, and manipulation.
Example:

char[] ch={‘g’, ‘e’, ‘e’, ‘k’, ‘s’};


String s=new String(ch);
is same as:
String s="geeks";

 Ways of Creating a Java 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 (Static Memory)


To make Java more memory efficient (because no new objects are created if it exists already in the
string constant pool).
Example:
String demoString = “Welcome”;

2. Using new keyword (Heap Memory)


 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)

In the given example only one object will be created. Firstly JVM will not find any string object with
the value “Welcome” in the string constant pool, so it will create a new object. After that it will find
the string with the value “Welcome” in the pool, it will not create a new object but will return the
reference to the same instance.

Example:
String demoString = new String (“Welcome”);

 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.

28 | P a g e
Programming Structures in Java (Unit-1)

 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.
1. String
2. StringBuffer
3. 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
// Method 1
String str= “geeks”;

// Method 2
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.
Features of StringBuffer Class
Here are some important features and methods of the StringBuffer class:
 StringBuffer objects are mutable, meaning that you can change the contents of the buffer without
creating a new object.
 The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with
the ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the end of the buffer.
 The insert() method is used to insert characters, strings, or other objects at a specified position in
the buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in the buffer.

Syntax:
StringBuffer demoString = new StringBuffer(“GeeksforGeeks”);

29 | P a g e
Programming Structures in Java (Unit-1)

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”);

4. StringTokenizer
StringTokenizer class in Java is used to break a string into
tokens.

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

4. StringJoiner
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.

 String vs StringBuilder vs StringBuffer in Java

A string is a sequence of characters. In Java, objects of String are immutable which means a constant
and cannot be changed once created. In Java, String, StringBuilder, and StringBuffer are used for
handling strings. The main difference is:
 String: Immutable, meaning its value cannot be changed once created. It is thread-safe but less
memory-efficient.
 StringBuilder: Mutable, not thread-safe, and more memory-efficient compared to String. Best used
for single-threaded operations.
 StringBuffer: Mutable and thread-safe due to synchronization, but less efficient than StringBuilder
in terms of performance.

Difference Between String, StringBuilder, and StringBuffer

30 | P a g e
Programming Structures in Java (Unit-1)

Feature String StringBuilder StringBuffer


Introduction Introduced in JDK 1.0 Introduced in JDK 1.5 Introduced in JDK 1.0
Mutability Immutable Mutable Mutable
Thread Safety Thread Safe Not Thread Safe Thread Safe
Memory High Efficient Less Efficient
Efficiency
Performance High(No- High(No-Synchronization) Low(Due to
Synchronization) Synchronization)
Usage This is used when we This is used when Thread This is used when Thread
want immutability. safety is not required. safety is required.

 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.

Why Are Java Strings Immutable?


1. String Pool: Java stores string literals in a pool to save memory. Immutability ensures one
reference does not change the value for others pointing to the same string.
2. Security: Strings are used for sensitive data like usernames and passwords. Immutability prevents
attackers from altering the values.
3. Thread Safety: Since string values cannot be changed, they are automatically thread-safe, means
multiple threads can safely use the same string.
4. Efficiency: The JVM reuses strings in the String Pool by improving memory usage and
performance.

 Java String concat() Method with Examples

The string concat() method concatenates (appends) a string to the end of another string. It returns the
combined string. It is used for string concatenation in Java. It returns NullPointerException if any
one of the strings is Null.

Syntax of concat() Method


 public String concat (String s);
Parameters:
 A string to be concatenated at the end of the other string.
Return Value:
 Concatenated(combined) string.
Exception:
 NullPointerException: When either of the string is Null.

31 | P a g e
Programming Structures in Java (Unit-1)

 Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char
values.
No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
3 static String format(String format, It returns a formatted string.
Object... args)
5 String substring(int beginIndex) It returns substring for given begin index.
6 String substring(int beginIndex, int It returns substring for given begin index and
endIndex) end index.
7 boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.
10 boolean equals(Object another) It checks the equality of string with the given
object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the specified char
value.
14 String replace(CharSequence old, It replaces all occurrences of the specified
CharSequence new) CharSequence.
15 static String It compares another string. It doesn't check
equalsIgnoreCase(String another) case.
16 String[] split(String regex) It returns a split string matching regex.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting
with given index.
21 int indexOf(String substring) It returns the specified substring index.
22 int indexOf(String substring, int It returns the specified substring index starting
fromIndex) with given index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase using specified
locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase using specified
locale.
27 String trim() It removes beginning and ending spaces of this
string.
28 static String valueOf(int value) It converts given type into string. It is an
overloaded method.

32 | P a g e

You might also like