0% found this document useful (0 votes)
4 views35 pages

Java Programming Basics and Features

The document provides an introduction to Java, covering its components, features, and program structure. It explains Java's characteristics such as being platform-independent, object-oriented, and robust, along with details on constants, variables, and data types. Additionally, it outlines the Java program implementation process, including the roles of the Java compiler and Java Virtual Machine.

Uploaded by

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

Java Programming Basics and Features

The document provides an introduction to Java, covering its components, features, and program structure. It explains Java's characteristics such as being platform-independent, object-oriented, and robust, along with details on constants, variables, and data types. Additionally, it outlines the Java program implementation process, including the roles of the Java compiler and Java Virtual Machine.

Uploaded by

akjha1423
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Chapter Name Page


No
1 Introduction to Java 1
2 Constants, Variables and Datatype 10
3 Operators in java 18
4 Control structures in java 24
5 Looping Structure in Java 30
6 Question Bank 34

1
Unit 1
Introduction to Java

1.1 Introduction to Java

Java is a high-level, object-oriented, platform-independent programming language developed by James


Gosling at Sun Microsystems in 1995. It is widely used to build applications ranging from desktop
software to mobile apps, web applications, and enterprise systems.

1.2 Components of Java

1. JDK (Java Development Kit)


Contains everything needed to develop Java programs
(compiler, debugger, libraries).

2. JRE (Java Runtime Environment)


Contains libraries and JVM needed to run Java programs.

3. JVM (Java Virtual Machine)


Executes Java bytecode and makes Java platform-independent.

1.3 Java Features

Java includes a wide range of powerful features that make it a reliable, secure, and easy-to-use
programming language. These features help developers build portable, efficient, and high-performance
applications for different platforms.

Java 2 features
1. Compiled and Interpreted

 Java uses both compilation and interpretation, making it a two-stage programming language.
 The compiler first converts the source code into platform-independent bytecode.
 The interpreter then converts the bytecode into machine code during program execution.

2. Platform-Independent and Portable


 Java programs can run on any computer system without needing any changes.
 The bytecode generated by Java can be executed on all Java-supported machines.
 Java ensures portability by using fixed sizes for all its primitive data types.

3. Object-Oriented
 Java is fully object-oriented because everything is written using objects and classes.
 It supports key OOP features such as inheritance, polymorphism, and encapsulation.
 Java provides a large set of built-in classes arranged in packages for easy reuse.

4. Robust and Secure


 Java is a robust language with strict compile-time and runtime error checking.

2
 It uses automatic garbage collection to prevent memory leaks and related issues.
 Java provides high security by avoiding pointers and controlling memory access.

5. Distributed
 Java is designed for building applications that work across networked environments.
 It allows programs to easily access data or objects located on remote systems.
 This distributed nature helps multiple programmers collaborate from different locations.

6. Simple, Small, and Familiar


 Java is simple because it removes complicated features like pointers and goto statements.
 It is small and easy to learn due to fewer keywords and a clean structure.
 The syntax of Java is familiar because it closely resembles C and C++.

7. Multithreaded and Interactive


 Java supports multithreading, allowing multiple tasks to run at the same time.
 This feature improves the performance of multimedia and interactive applications.
 Java provides tools for managing and synchronizing threads smoothly.

8. High Performance
 Java delivers high performance due to its efficient use of bytecode and JVM optimization.
 Its execution speed is often comparable to programs written in C or C++.
 Multithreading in Java further improves the speed and responsiveness of applications.

9. Dynamic and Extensible


 Java can dynamically load new classes, methods, and objects during program execution.
 It supports native methods written in languages like C and C++ for improved efficiency.
 Java can identify class types at runtime, allowing flexible and extensible program design.

Additional features of J2SE 5.0

1. Ease of Development

 J2SE 5.0 introduces features like Generics, Enhanced for Loop, Autoboxing, Enums, Varargs,
Static Import, and Annotations to simplify coding.
 These features shift repetitive and reusable code generation to the compiler, reducing manual
work for programmers.
 Since the compiler handles most repetitive tasks, the source code becomes more reliable and
less prone to human errors.

2. Scalability and Performance


 J2SE 5.0 improves startup time by sharing core class data through the HotSpot JVM’s class
data sharing mechanism.
 Memory usage is reduced because multiple JVMs share data from a common archive, instead
of storing duplicate copies.
 These improvements make Java applications more scalable and efficient on systems with
multiple JVM processes.

3
3. Monitoring and Manageability
 Java provides APIs such as JVM Monitoring & Management API, JMX, and Logging APIs
to manage and monitor applications.
 These APIs allow developers to track both application-level and JVM-level information in
large deployments.
 Tools like jconsole, jps, jstat, and jdbstat help developers monitor JVM performance and
manage running applications.

4. Desktop Client
 J2SE 5.0 enhances desktop application development through an improved Swing “Ocean”
look and feel.
 This updated UI design helps in creating modern and visually appealing desktop applications.
 It also supports OpenGL-based hardware acceleration for building high-performance graphics
applications.

5. Miscellaneous Features
a. Core XML Support
 J2SE 5.0 includes built-in support for XML processing using SAX and DOM parsers.
 Developers can parse, transform, and validate XML documents directly within Java
applications.
 These XML tools enable easy data exchange between systems in a structured format.

b. Supplementary Character Support


 Java adds support for 32-bit supplementary characters through Unicode 4.0.
 These characters are encoded using UTF-16 surrogate pairs to represent additional symbols.
 This ensures Java applications can handle a wider range of international characters.

c. JDBC RowSet
 JDBC RowSet allows data to be transferred in tabular form between components of a
distributed application.
 CachedRowSet stores rows of data in memory and can be accessed without staying connected
to the database.
 WebRowSet reads and writes data in XML format and operates even when not connected to
any data source.

1.4 Main Line

Meaning of public static void main(String args[]) :


public static void main(String args[]) is the predefined method where program execution begins.
public lets JVM access it, static allows calling without objects, void means no return value, and String
args[] holds command-line input
public
 It is an access modifier.
 It allows the JVM to access the method from anywhere.
 So the JVM can start the program without restrictions.

4
static
 Means the method belongs to the class, not to an object.
 JVM can call main() without creating an object of the class.
void
 The method does not return any value to the JVM.
main
 It is the starting point of every Java program.
 JVM begins program execution from this method.
String args[]
 It is a String array.
 Used to receive command-line arguments.
 args is just a variable name—you can rename it (example: String myArgs[]).

1.5 Comments in Java

Comments are statements written in a program that the Java compiler ignores.
They are used to explain code, improve readability, and help other programmers understand the logic.

Java supports two types of comments:


1. Single-line Comment
Purpose: Used for short, one-line explanations or notes. Any text after // on the same line is considered
a comment

Syntax: // comment

Example:
int x = 10; // Declare and initialize variable x

2. Multi-line Comment
Purpose: Used for longer explanations that span multiple lines or to temporarily disable a block of
code. All text between /* and */ is treated as a comment.

Syntax: /* comment */

Example:
/*
* This method calculates the sum of two numbers.
* It takes two integer parameters and returns their sum.
*/
public int add(int a, int b) {
return a + b;
}

5
1.6 Java Program Structure
Suggested
Documentation section
Optional
Package statement
Optional
Import statements
Optional
Interface statements

Class definitions Optional

Main method class Essential


{
Main method Definition
}

A Java program has following key components:


1. Documentation Section (suggested)
 Contains comment lines with program name, author, and details.
 Helps the programmer refer back to information later.
 Comments should explain why and what of classes and how of algorithms.
 Useful for maintaining the program.
 Java includes a third style of comment /** … */ called documentation comment.

2. Package Declaration (Optional)


 A package groups related classes together.
 It should be the first line in the program.
Example:
package mypackage;

3. Import Statements(Optional)
 Used to include predefined classes from other packages.
 Helps to reuse existing functionality.
Example:
import [Link]; // Imports the Scanner class for input

4. Interface Statement(Optional)
 Interface is similar to a class. It contains only method declarations.
 It is an optional section in a program.
 It is used when we want to implement multiple inheritance in Java.

5. Class Declaration (Optional)


 Every Java program must have at least one class.
 The class name must match the file name if the class is public.
Example:
public class MyClass
{

6
// Fields and methods go here
}

6. Main Method (Essential)


 The starting point of program execution.
 It is always written as:
public static void main(String[] args)
{
// Program logic
}

Example Program

public class HelloWorld {


public static void main(String[] args) {

// This line prints a message on the screen


[Link]("Hello, World!");

}
}

1.7 Implementation of Java Program

Source code

Java Compiler

Byte code

Windows Interpreter ABC Interpreter Macintosh Interpreter

Machine code Machine code Machine code

Window Computer ABC Computer Macintosh Computer

1. You write a Java program


 Writing the program in a .java file (Source Code)

2. Java Compiler (javac)


 Takes the source code
 Checks for errors
 Converts it into bytecode
 Stores it in a .class file
7
3. Bytecode
 This is the output of the compiler
 It is platform-independent
 JVM can execute it on any system

4. Java Interpreter (inside JVM)


 Reads the bytecode
 Converts it into machine code
 Produces the final output

Detailed Explanation of Java Architecture/ Java Implementation:


Java Compiler

 The Java compiler is a program that converts Java source code (saved with .java extension)
into bytecode.
 It checks the program for syntax errors and reports them to the programmer.
 The compiler does not execute the program; it only translates code.
 After successful compilation, it creates a .class file containing the bytecode.

Bytecode

 Bytecode is the intermediate, platform-independent code generated by the compiler.


 It is not specific to any operating system or hardware.
 Bytecode makes Java a portable language, enabling the concept of
 “Write Once, Run Anywhere” (WORA).
 Stored in a .class file.
 Bytecode is executed by the Java Virtual Machine (JVM).

Java Compiler Java Bytecode Java Interpreter

Java Virtual Machine


 All compilers translate source code into machine code. Similarly ,Java compiler translates
source code into bytecode (intermediate code).
 Bytecode runs on the Java Virtual Machine (JVM) and it exists only in memory
 It simulates a real and does all major functions of a real computer.
Figure illustrates the process of compiling a Java program into bytecode which is also referred to
as virtual machine code.

8
The virtual machine code is not machine specific. The machine specific code (known as machine
code) is generated by the Java interpreter by acting as an intermediary between the virtual
machine and the real machine as shown in Fig

9
Chapter 2
Constants , Variables and Datatypes

2.1 Constants
In Java, constants are fixed values that do not change during program execution.
They are also known as literals.

2.1.1 Constant clasification


Java constants can be classified into the following types:
1. Integer Constant

2. Numeric Constant
1. Numeric Constants : Numeric constants represent numbers.
A. Integer Constants (int type):
 These constants represent whole numbers without a decimal point.

 They represent numeric values and can be written in different number systems.
 Java supports four types of integer constants based on number system:

1. Decimal Integer Constants (Base 10)

 It consists of any digits from 0 – 7


 The most commonly used Number form.
 Examples: 123 , -12, $90
 Embedded spaces,comas and non-digit characters are not permitted
between digits. Ex: 12 2 , 20.00 , $20
2. Octal Integer Constants (Base 8)

 It consists of any digits from 0 - 7


 Must start with 0
 Example:032, 0 , 043

3. Hexadecimal Integer Constants (Base 16)

 Digits used: 0–9 and A–F (or a–f)


 Must start with 0x or 0X
 Example: 0xpa, 0x2, 0Xb3
We rarely use octal and hexadecimal numbers in programming

B. Real Constants (floating-point constants):


 These represent numbers with decimal points.
 Must have a decimal point or be in exponential form.
 Can be positive or negative
 Example: 3.14 , -0.5 , 12.00 , 5.67e3 , -1.2E-1 // exponential form

2. Character Constants: These constants represent characters enclosed in single or double quotes.

10
They are of two types:
A. Character Constants (char) : These are single characters enclosed in single quotes.
 Must contain exactly one character
 Enclosed in single quotes ' '
 Example: ‘5’ , ‘;’ , ‘ ’, ‘a’
B. String Constants (String) : These represent a sequence of characters enclosed in double quotes.
 Can contain 0 or more characters
 Enclosed in double quotes " "
 Example: “Java class” ,”1900”, ”3+8”, “v”

Symbolic Constant in Java


A symbolic constant is a value that is declared once and cannot be changed during the execution of the
program.

 In Java, symbolic constants are created using the final keyword.


 A constant is usually written in uppercase letters to easily identify it as a fixed value.

Syntax: final dataType CONSTANT_NAME = value;


Example: public class ConstantExample {

public static void main(String[] args) {


final int MAX_STUDENTS = 60; // symbolic constant
[Link]("Maximum students allowed: " + MAX_STUDENTS);

}
}
Output:

Maximum students allowed: 60


Explanation:
MAX_STUDENTS is declared using final, so its value cannot be modified.

If you try to change it, Java will give a compile-time error.

2.2 Data Types


A data type is a classification that specifies which type of value a variable can store, how much memory
it requires, and what operations can be performed on that data. Java provides a rich set of data types,
categorized as primitive and non-primitive.

2.2.1 Primitive Data Types:


1. Integer Types:
 Used for whole numbers.
 Types: byte, short, int, long.
 Example:
int age = 22;
int marks = 95;
[Link](age);
11
[Link](marks);
 Memory size and range:
Type Size Minimum Value Maximum Value
(bytes)
byte 1 -128 127
short 2 -32,768 32,767
int 4 -2,147,483,648 2,147,483,647
long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

2. Floating-Point Types:

 For numbers with decimals.


 Types: float, double.
 Memory size and range

Type Size (bytes) Minimum Value Maximum Value


float 4 3.4e-038 3.4e+038
double 8 1.7e-308 1.7e+308
 Example:
float price = 45.99f;
float weight = 12.5f;
[Link](price);

[Link](weight);
3. Character Type:
 The char data type is used to store a single character.
 Characters are stored using Unicode, so it can store letters, digits, symbols, etc.
 Size: 2 bytes.
 Example:

char letter = 'A';


char digit = '5';
char symbol = '$';
[Link](letter); // A

4. Boolean Type:
 The boolean data type in Java is used to store true/false values.
 It represents logical values and is commonly used in conditions, loops, and decision-making
statements
 Java boolean does not have a fixed size (depends on JVM implementation)
 boolean: Holds true or false.
 Example: boolean flag = true;
boolean isValid = false;

12
2.2.2 Non-Primitive Data Types:

Objects, arrays, strings, classes, and interfaces.


1. Objects
 An object is a real-world entity that has state (data) and behavior (methods).
 It is created from a class and represents one instance of that class.
 Example : Student s1 = new Student();
Here, s1 is an object of the Student class.
2. Arrays
 An array is a collection of similar data types stored under a single name.
 It stores elements in continuous memory locations and has a fixed size.
 Example: int marks[] = {75, 80, 90};
Here, marks is an integer array.
3. Strings
 A string is a sequence of characters enclosed in double quotes.
 In Java, strings are objects of the String class, and they are immutable (cannot be changed).
 Example: String uname = "Navya";
4. Classes
 A class is a blueprint or template from which objects are created.
 It contains variables (fields) and methods that define the behavior of its objects.
 Example:

class Student {
int age;
void display() {
[Link]("Student age: " + age);
}}

5. Interfaces
 An interface is a collection of abstract methods (methods without body).
 It is used to achieve 100% abstraction and multiple inheritance in Java.
 Example:

interface Animal {
void eat(); // abstract method
}

2.3 Variables
A variable is a name given to a memory location that stores data.

Its value can change during program execution.

2.3.1 Declaration of Variables


Declaring a variable means telling the compiler:
 the datatype
 the name of the variable
Syntax: dataType variableName;
Example: int x;
float mark;

13
You can also declare multiple variables of the same type:
Syntax: dataType variable1, variable2, variable3……..;
Example: int x, y, z;

2.3.2 Giving Values to Variables

Values can be given to variables after it has been declared in two ways:
A. By Assignment Statement:
An assignment statement stores a value into a variable using = operator.
Syntax: variableName = value;
Example: age = 20;
marks = 85.5f;
grade = 'A';
name = "Navya";
It is also possible to declare and assign a variable in a single line:
Syntax: type variableName = value;
Example: int age = 20;
float salary = 25000.50f;

C. By Reading Statement (Taking input from the user)


In Java, user input is taken using the Scanner class.

Step 1: Import Scanner


import [Link];
Step 2: Create Scanner object

Scanner sc = new Scanner([Link]);


Step 3: Read values into variables
Examples

1. Reading an integer
int age;
age = [Link]();
2. Reading a float
float salary;
salary = [Link]();

3. Reading a character
char grade;

grade = [Link]().charAt(0);
4. Reading a string
String name;

name = [Link]();

14
Example:
import [Link];

class VariableExample {
public static void main(String[] args) {
String name;

Scanner sc = new Scanner([Link]);


[Link]("Enter your name: ");
name = [Link]();
[Link]("Enter your age: ");

age = [Link]();

[Link]("Enter your marks: ");

marks = [Link]();

[Link]("Name: " + name);


[Link]("Age: " + age);
[Link]("Marks: " + marks);
}
}

2.4 Initializing Variables in Java


Initialization means assigning an initial value to a variable before it is used in a program.
In Java, every variable must be initialized either at the time of declaration or before it is used;
otherwise, it will cause a compilation error.

Java provides two ways to initialize variables:

1. Static Initialization (Compile-time Initialization)

Static initialization means assigning a value directly at the time of declaration.

Characteristics

 Value is known before program runs


 Happens at compile-time
 Simple and quick
 No input or runtime calculations involved

Example:
int a = 10;
double price = 99.5;
char grade = 'A';

15
2. Dynamic Initialization (Run-time Initialization)

Dynamic initialization means assigning a value during program execution, not at declaration time.

Characteristics
 Value is decided at runtime
 Usually depends on:
o user input
o method return value
o expressions and calculations
 More flexible than static initialization
Example:
int sum = a + b; // variable sum value calculated at runtime

2.5 Type Conversion


Java provides various data types just like any other dynamic language such as boolean, char, int,
unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype acquires
different space while storing in memory. When you assign a value of one data type to another, the two
types might not be compatible with each other. If the data types are compatible, then Java will perform
the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast
or converted explicitly. For example, assigning an int value to a long variable.
2.5.1 Widening or Automatic Type Conversion
Automatic conversion takes place when two data types are automatically converted. This happens when:
 The two data types are compatible.
 When we assign a value of a smaller data type to a bigger data type.
For Example, in java, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
Widening order:
byte → short → int → long → float → double

Syntax: largerType variable2 = variable1;


Example: double b = a; // int a is automatically converted to double

Example:
public class ImplicitConversion {
public static void main(String[] args) {

int num = 25; // smaller data type


double result = num; // automatically converted to double

[Link]("Implicit Conversion (int to double): " + result);


}
}
Result:
Implicit Conversion (int to double): 25.0

16
2.5.2 Explicit Type Conversion (Narrowing)

Explicit type conversion in Java is the process of manually converting a larger data type into a smaller
data type using a cast operator.
It is called narrowing because the destination type has a smaller range than the source type.

 Syntax: (target_type) value


Characteristics:
 Done manually by the programmer
 Uses casting syntax: (type)
 May lead to loss of data (for example, decimal values are removed)
 Smaller range cannot hold some larger values. Therefore, overflow may occur

Example:
float b = 10.5;
int a = (int)b; // a becomes 10 (data loss)

Example:
public class ExplicitConversion {
public static void main(String[] args) {

double value = 49.87; // larger data type


int out = (int) value; // manually converted to int

[Link]("Explicit Conversion (double to int): " + out);


}
}
Result:
Explicit Conversion (double to int): 49

17
Chapter 3:
Operators in Java

Operators are symbols used to perform operations on variables and values.

Java operators are divided into the following types:


1. Arithmetic operator
Arithmetic operators in Java are used to perform basic mathematical operations on numeric data types
such as int, float, double, etc.
These operators operate on two operands and return a numerical result. They are commonly used in
calculations, expressions, and formula-based problems.

Operator Description Explanation


+ Addition Adds two operands.
- Subtraction Subtracts the right operand from the left.
* Multiplication Multiplies two operands.
/ Division Divides the left operand by the right operand
(returns quotient).
% Modulus Returns the remainder after division.
Example:
class ArithmeticDemo {

public static void main(String[] args) {


int a = 10, b = 3;
[Link]("Arithmetic Operators:");

[Link]("a + b = " + (a + b));


[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));

[Link]("a / b = " + (a / b));


[Link]("a % b = " + (a % b));
}

}
Output:

Arithmetic Operators:
a + b = 13
a-b=7

a * b = 30
a/b=3
a%b=1
18
2. Relational operators
Relational operators in Java are used to compare two values or expressions. They always return a
boolean result: true or false.

These operators check relationships such as equality, inequality, greater than, or less than. They are
mainly used in conditional statements (if, loops).

Operator Description Explanation


== Equal to Checks if both operands are equal.
!= Not equal to Checks if operands are not equal.
> Greater than True if left operand is greater.
< Less than True if left operand is smaller.
>= Greater than or equal to Checks if left operand ≥ right.
<= Less than or equal to Checks if left operand ≤ right.
class RelationalDemo {

public static void main(String[] args) {


int a = 10, b = 20;
[Link]("Relational Operators:");

[Link]("a == b: " + (a == b));


[Link]("a != b: " + (a != b));
[Link]("a > b: " + (a > b));

[Link]("a < b: " + (a < b));


[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));

}
}

Output:
Relational Operators:
a == b: false
a != b: true

a > b: false
a < b: true
a >= b: false

a <= b: true

3. Logical operators
Logical operators in Java are used to combine multiple boolean expressions or conditions and return a
boolean result.
They are mainly used in decision-making (if, else-if), loops, and complex condition checks. These
operators work only on boolean values.
19
Operator Description Explanation
&& Logical AND Returns true only if both conditions are true.
|| Logical OR Returns true if any one of the condition is true.
! Logical NOT Reverses the boolean value (true → false, false →
true).
Example:
class LogicalDemo {

public static void main(String[] args) {


int a = 10, b = 20;
[Link]("Logical Operators:");

// AND (&&)
[Link]("(a > 5) && (b > 15): " + ((a > 5) && (b > 15)));
// OR (||)

[Link]("(a > 15) || (b > 15): " + ((a > 15) || (b > 15)));
// NOT (!)
[Link]("!(a == b): " + !(a == b));

}
}
Output:

Logical Operators:
(a > 5) && (b > 15): true
(a > 15) || (b > 15): true

!(a == b): true

[Link] operators
Assignment operators in Java are used to assign values to variables. They can also combine assignment
with arithmetic operations.
The basic assignment operator (=) sets the variable value. Compound assignment operators reduce the
writing of long expressions like a = a + b.

Operator Description Explanation


= Simple assignment Assigns the right value to the left variable.
+= Add and assign a += b → adds b to a and stores in a.
-= Subtract and assign a -= b → subtracts b from a and stores in a.
*= Multiply and assign a *= b → multiplies a by b.
/= Divide and assign a /= b → divides a by b.
%= Modulus and assign a %= b → stores remainder in a.

20
5. Increment and Decrement operators

Operator Meaning Example


++ Increment by 1 a++ or ++a
-- Decrement by 1 a-- or --a

6. Conditional (ternary) operator

 The ternary operator in Java is a shorthand way of writing an if-else statement.


 It evaluates a condition and returns one of two values.

Syntax:
condition ? value_if_true : value_if_false;

 If the condition is true, the expression returns value_if_true.


 If the condition is false, it returns value_if_false.

Example:
class TernaryDemo {

public static void main(String[] args) {


int a = 10, b = 20;
String result = (a > b) ? "a is greater" : "b is greater";

[Link]("Result: " + result);


}
}

Result: b is greater

7. Bitwise operator

Operator Meaning Example


& Bitwise AND a&b
! Bitwise OR a!b
^ Bitwise XOR a^b
~ Bitwise NOT(one’s complement) ~a
<< Left shift a << 1
>> Right shift a >> 1
>>> Unsigned right shift a >>> 1

Difference Between == Operator and = Operator in Java


1. = Operator (Assignment Operator)
 Used to assign a value to a variable.
 It places the value on the right side into the variable on the left side.
 It does not compare values.
 Example: int a = 10; // assigns 10 to variable a
2. == Operator (Equality Operator)

 Used to compare two values or expressions.

21
 Returns true if both values are equal; otherwise false.
 Used in conditions, loops, and comparisons.
 Example:

int a = 10, b = 10;

[Link](a == b); //output: true

8. Special operators
These include two commonly used special operators:

A. instanceof Operator
The instanceof 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. Checks whether an object belongs to a specific class.
Example:
public class InstanceExample{

public static void main(String[] args){


String str = "Hello";
[Link](str instanceof String);

Object obj = new Integer(10);


[Link](obj instanceof Integer);

[Link](obj instanceof String);


}
}

Output: true
true
false

B. Dot Operator .
The dot operator is used to access members of a class or an object. It allows us to:
2. Access fields (variables) of a class or an object.
3. Invoke methods of a class or an object.
4. Access inner classes and interfaces.
Example:

class Student {
int age = 20;
void display() {

[Link]("Age: " + age);


}

22
}
class DotOperatorDemo {
public static void main(String[] args) {

// Creating object
Student s = new Student();
// Using dot operator to access variable and method

[Link]("Student age is: " + [Link]);


[Link]();
}

23
Chapter 4
Control Structures in Java

Control structures are statements in Java that control the flow of execution based on conditions or
[Link] help the program decide, repeat, or choose actions.

3.1. If Statement

 The if statement is a powerful decision-making statement in Java.


 It is used to control the flow of program execution.
 It is basically a two-way decision statement.
 The computer evaluates the test expression first.
 If the condition is true, the statement inside the if block is executed.
 If the condition is false, the control skips the block and continues with the next statement.
 The if statement can be used in different forms depending on the complexity of conditions
 Types of if statements
o simple if
o if-else
o else-if ladder
o nested if

3.1.1 Simple If Statement


The simple if statement executes a block of code only when the condition is true.
Syntax:
if (test expression)
{
statements;
}

Example: Check if a number is positive


public class SimpleIf {
public static void main(String[] args) {
int num = 5;
if (num > 0) {
[Link]("Number is positive");
}
}
}
Output: Number is positive

3.1.2 The If...Else Statement


 The if...else statement is an extension of the simple if statement.
 Syntax:
if (test expression)
{
True-block statement(s);
}
24
else
{
False-block statement(s);
}
statement-x;
 In an if–else statement, the test expression is evaluated first.
 If the test expression is true, the statements inside the true-block (if) are executed.
 If the test expression is false, the statements inside the false-block (else) are executed.
 After completing either the true-block or false-block, the program continues to execute
the next statement outside the if–else structure, which is statement-x.
 This shows that statement-x executes regardless of the condition
 Example: Check if a number is even or odd
public class IfElseExample {
public static void main(String[] args) {
int num = 7;
if (num % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
}
}

Output: Odd number

3.1.3 The Else If Ladder

There is another way of putting if`s together when multipath decisions are involved. A multipath
decision is a chain of `if`s in which the statement associated with each `else is an if. It takes the
following general form:

if (condition1){

statement-1;

else if (condition2){

statement-2;

25
else if (condition3){

statement-3;

. . .}

else if (condition n){

statement-n;

else{

default-statement;

statement-x;

This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the rest of the ladder). When
all if conditions become false, then the final else containing the default-statement will be executed.

Example: Grade based on marks

public class ElseIfLadder {

public static void main(String[] args) {

int marks = 75;

if (marks >= 90) {

[Link]("Grade A");

} else if (marks >= 75) {

[Link]("Grade B");

} else if (marks >= 50) {

[Link]("Grade C");

} else {

[Link]("Fail");

Output: Grade B
26
3.1.4 Nesting of If...Else Statements

When a series of decisions are involved, we may have to use more than one if...else statement in
nested form as follows.

if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the
second test. If the condition-2 is true, the statement-1 will be executed, otherwise the statement-2
will be evaluated and then the control is transferred to the statement-x.

Example: Find the largest of two numbers

public class NestedIfElse {

public static void main(String[] args) {

int a = 10, b = 20, c = 15;

if (a > b) {

if (a > c) {

[Link]("a is the largest");

} else {

[Link]("c is the largest");

} else {

if (b > c) {

[Link]("b is the largest");

} else {

[Link]("c is the largest");

27
}

Output: b is the largest

3.2 Switch Statement

 The switch statement is a multi-way branch statement in Java.


 It is used when one value must be matched against many possible alternatives.
 It reduces complexity compared to multiple if-else statements
 The expression must be an integer or character type.
 case labels are constants or constant expressions, and each must be unique.
 When the switch executes, the expression is compared with each case label.
 If a match is found, the corresponding block of statements is executed.
 The break statement ends the case and transfers control outside the switch.
 If no match is found, the default case (if present) is executed.
 If default is not provided, control directly moves to the statement after the switch.
Syntax:
switch (expression)
{
case value-1: block-1
break;
case value-2: block-2
break;
...
default: default-block
break;
}
statement-x;

Example: Program to display the day of the week based on number (1–7)
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:[Link]("Sunday");
break;
case 2:[Link]("Monday");
break;
case 3:[Link]("Tuesday");
break;
case 4:[Link]("Wednesday");
break;

28
case 5:[Link]("Thursday");
break;
case 6: [Link]("Friday");
break;
case 7: [Link]("Saturday");
break;
default: [Link]("Invalid day number");
}
}
}
Output: Tuesday
3.3 Ternary Operator
 The ternary operator is a shortened form of the if–else statement.
 It evaluates a condition and returns one of two values:
 One value if the condition is true. Another value if the condition is false
 It is mainly used to write simple decisions in a compact form.

Syntax:
condition ? value_if_true : value_if_false;

Example:
public class TernaryExample {
public static void main(String[] args) {
int score = 75;
String result;
result = (score >= 50) ? "Pass" : "Fail";
[Link]("The result is: " + result);
}
}
In this example:
 We have a variable score set to 75.
 The ternary operator checks if score is greater than or equal to 50.
 If it is true, result is assigned "Pass".
 If it is false, result is assigned "Fail".
 The program then prints the result, which will be "Pass" in this case.
This concise form helps reduce the need for multiple lines of code and makes simple
conditional assignments more readable.

29
Chapter 5
Looping Structures
In Java, looping allows you to execute a block of code repeatedly based on a condition. The Java
language provides three constructs for performing loop operations.

5.1 Looping Types

 while loop
 do while loop
 for loop

5.1 .1 While Loop

The while loop is the simplest loop in Java.


Syntax:
Initialization;
while (test condition)
{
Body of the loop
}
 It is an entry-controlled loop, meaning the condition is checked first.

 If the condition is true, the body of the loop is executed.

 After execution, the condition is checked again.

 This process continues until the condition becomes false.

 When the condition is false, control moves out of the loop.

 The program then continues with the next statement after the loop.

 The loop body may have one or more statements.

 Braces { } are needed only if there are two or more statements in the body.

 Example: Print numbers from 1 to 5


public class WhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link](i + " ");
i++;
}}}
Output: 1 2 3 4 5

30
5.2 The Do While loop
 The do…while loop is used when the body of the loop must be executed at least once.
 Unlike the while loop, the condition is tested after the body is executed.
 On reaching the do statement, the loop body is executed first.
 After execution, the test condition is checked.
 If the condition is true, the loop body runs again.
 This process repeats until the condition becomes false.
 Since the condition is checked at the end, it is called an exit-controlled loop.
 Therefore, the body of a do…while loop is always executed at least once.
 Syntax:
do
{
body of the loop
} while (test condition);

Example: Print numbers from 10 down to 6

public class DoWhileExample {

public static void main(String[] args) {

int i = 10;

do {

[Link](i + " ");

i--;

} while (i >= 6);

}
Output: 10 9 8 7 6

5.2 The for loop

The for loop is another entry-controlled loop that provides a more concise loop control structure.
The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment.
 The general form of the for loop is:
for (initialization ; test condition ; increment)
{
body of the loop
}

 Example: Print even numbers from 2 to 10


public class ForExample {
public static void main(String[] args) {
for (int i = 2; i <= 10; i += 2) {

31
[Link](i + " ");
}
}
}

Output: 2 4 6 8 10

5.2 Jumps in loops


In Java, jump statements are used to control the flow of loops. They allow you
to skip iterations, exit loops, or return from methods.

The main jump statements are:


1. break Statement
When the break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the
loop. They can be used to terminate a loop, skip an iteration, or exit from a
method or block of code.

Syntax: break;
Example:
public class BreakExample {
public static void main(String[] args) {

for(int i = 1; i <= 10; i++) {


if(i == 5) {
break; // exits the loop when i becomes 5
}
[Link]("i = " + i);
}

}
}
Output:
i=1
i=2
i=3
i=4

5. Continue statement
During the loop operations, it may be necessary to skip a part of the body of the
loop under certain conditions. Like the break statement, Java supports another
similar statement called the continue statement. However, unlike the break which
causes the loop to be terminated, the continue, as the name implies, causes the loop
to be continued with the next iteration after skipping any statements in between. The
continue statement tells the compiler, "SKIP THE FOLLOWING STATEMENTS
AND CONTINUE WITH THE NEXT ITERATION".

Syntax: continue;

32
Example:
public class ContinueExample {
public static void main(String[] args) {

for(int i = 1; i <= 5; i++) {


if(i == 3) {
continue; // skip iteration when i is 3
}
[Link]("i = " + i);
}
}
}
Output:
i=1
i=2
i=4
i=5

33
Question Bank

Questions carrying 2 marks


1.
List any four features of Java.
2.
What is Java Virtual Machine (JVM)?
3.
Write the structure of a basic Java program.
4.
What are constants in Java? Give an example.
5.
Differentiate between int and float data types in Java.
6.
Define variables in Java with an example.
7.
What is the significance of main() method in Java?
8.
Write the syntax of declaring and initializing a variable.
9.
Write any four bitwise operators in java.
10.
List different types of operators available in Java.
11.
Write the difference between == operator and = operator.
12.
What is a ternary operator? Give an example.
13.
Define control structures with an example.
14.
Write the syntax for switch statement in java.
15.
Write the syntax for ‘for loop’ in Java.
16.
Mention the difference between while loop and do-while loop.
17.
What is the role of the break statement in Java loops?
18.
What is the role of the continue statement in Java loops?
Write the syntax for ‘nested..if’ statement in java
20.
What is Java Bytecode?
21.
Write the meaning of public static void main(String args[])
22.
Mention two ways of writing comments in Java
23.
List any 4 primitive data types available in Java.
24.
What are the two ways of initializing variables?
25.
What is dynamic initialization of variables? Give example.
26.
List different arithmetic operators available in Java
27.

34
What is automatic (implicit) type conversion? Give example
28.
What is the purpose of [Link] ().Give an example.
29.
Write the syntax of simple if statement with example.
30.
Give the syntax of declaring a symbolic constant with example.

Long answer questions


1.
Explain the main features of Java programming language.
2.
Describe the structure of a simple Java program with an example.
3.
What is Java Virtual Machine (JVM)? Explain its role in program execution.
4.
Explain different types of Constants in java.
5.
List and explain different primitive data types available in Java.
6.
Discuss the rules for declaring and assigning values to variables with example.
7.
Explain Arithmetic and Relational operators in java with suitable examples.
8.
Explain logical and special operators in java.
9.
Explain type conversion in java.
10.
Differentiate between if…else and Nesting of if…else statement with example.
11.
Explain else if… ladder with syntax and example.
12.
Explain switch statement with syntax and example.
13.
Explain the ternary operator with syntax and example program.
14.
Explain the difference between while, do-while, and for loops with example.
15.
Explain the use of break and continue statements with examples.

35

You might also like