Unit-1 Programming Structures
Unit-1 Programming Structures
UNIT-1
PROGRAMMING STRUCTURES IN JAVA
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
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.
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.
2|Page
Programming Structures in Java (Unit-1)
Java Basics
Output
Hello World
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.
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.
5|Page
Programming Structures in Java (Unit-1)
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.
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 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.
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.
There are 8 primitive data types. They are depicted below in tabular format below as follows:
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
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)
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
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
9|Page
Programming Structures in Java (Unit-1)
Example:
// Declaring float variable
float simpleInterest;
// Instance variable
int b;
}
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.
10 | P a g e
Programming Structures in Java (Unit-1)
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.
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
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.
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.
14 | P a g e
Programming Structures in Java (Unit-1)
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.
17 | P a g e
Programming Structures in Java (Unit-1)
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.
18 | P a g e
Programming Structures in Java (Unit-1)
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.
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
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.
21 | P a g e
Programming Structures in Java (Unit-1)
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.
22 | P a g e
Programming Structures in Java (Unit-1)
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.
23 | P a g e
Programming Structures in Java (Unit-1)
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]);
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;
Let's see the example of printing the elements of the Java array using for-each loop.
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} };
25 | P a g e
Programming Structures in Java (Unit-1)
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];
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
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:
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”);
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.
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.
30 | P a g e
Programming Structures in Java (Unit-1)
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.
31 | P a g e
Programming Structures in Java (Unit-1)
32 | P a g e