0% found this document useful (0 votes)
151 views86 pages

Session 3 - Datatypes and Variables

The document provides an overview of data types in Java, categorizing them into primitive and non-primitive types. It details the eight primitive data types, their sizes, ranges, and examples, as well as non-primitive types like Strings, Arrays, Classes, Interfaces, and Enums. Additionally, it includes example programs demonstrating the use of various data types and exercises for further understanding.

Uploaded by

pavankumarvoore3
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)
151 views86 pages

Session 3 - Datatypes and Variables

The document provides an overview of data types in Java, categorizing them into primitive and non-primitive types. It details the eight primitive data types, their sizes, ranges, and examples, as well as non-primitive types like Strings, Arrays, Classes, Interfaces, and Enums. Additionally, it includes example programs demonstrating the use of various data types and exercises for further understanding.

Uploaded by

pavankumarvoore3
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/ 86

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA
Session 3 - Datatypes and Variables

1. Datatypes Introduction

Introduction to Datatypes
Java is both a statically typed and strongly typed language. This means that every type of
data, such as integers, characters, hexadecimal values, and packed decimals, must be declared
explicitly or inferred at the time of compilation, before the code is executed.. Consequently, all
constants and variables in Java must be explicitly declared with one of its predefined data types.
A. Primitive Data Types:
Primitive data types are the most basic types of data available in Java. They are
predefined by the Java language and named by reserved keywords. Primitive data types
serve as the building blocks of data manipulation in Java, and they are not objects; they
hold their values directly in memory. There are eight primitive data types in Java, each
with its own specific purpose, size, and range.

1. byte (8-bit signed integer)


2. short (16-bit signed integer)
3. int (32-bit signed integer)
4. long (64-bit signed integer)
5. boolean (true or false values)
6. char (single 16-bit Unicode character)
7. float (single-precision 32-bit floating point)
8. double (double-precision 64-bit floating point)

B. Non-primitive (Reference) Data Types: These refer to objects and arrays.


1. Strings (Objects that represent sequences of characters.)
2. Arrays (Collections of elements of the same type stored in contiguous memory
locations.)
3. Classes(Blueprints for creating objects.)
4. Interfaces (Abstract types that specify a set of method signatures without
implementations.)
5. Enums (Special data types that define a set of named constants.)

1.1. Primitive Datatypes

a type
Primitive Datatypes
Java provides eight primitive data types, each designed to store a specific type of data. These
data types are predefined by the Java language and serve as the building blocks for data
manipulation.

Integer Datatypes
Default
Datatype Default Size Range Example
Value

Byte 1 Byte 0 -128 to 127 byte num1;

Short 2 Byte 0 -32,768 and 32767 short num1;

-2147483648 to
Int 4 Byte 0 int num1;
2147483647

Long 8 Byte 0 -263 to 263-1 long num1 = ___L;

1. Byte:
Description: An 8-bit signed integer.
Size: 1 byte (8 bits).
Range: -128 to 127.
Characteristics:
Useful for saving memory in large arrays.
Can be used in place of an int where the range of values is known to be within
-128 to 127.
Syntax:

byte variable_name = value;

Example Program: The ByteExample program is a demonstration of using the


byte primitive data type in Java. Here's a brief explanation of the code:
Explanation:
Program analysis: The program demonstrates how to declare and use byte
variables in Java.
● Variables:
○ age: A byte variable initialized with the value 25. This is within the
valid range for a byte (-128 to 127).

○ sensorReading: Another byte variable initialized with the value -


120, also within the byte range.
● Output:
○ The program prints the values of both byte variables to the console.
Code:

public class ByteExample {


public static void main(String[] args) {
byte age = 25; // Assuming age is within the byte range
byte sensorReading = -120; // Example of a sensor value

System.out.println("Age: " + age);


System.out.println("Sensor reading: " + sensorReading);
}
}

Output:
Age: 25
Sensor reading: -120

2. short
Description: A 16-bit signed integer.
Size: 2 bytes (16 bits).
Range: -32,768 to 32,767.
Characteristics:
Can be used to save memory in large arrays when memory savings are
important.
Less commonly used compared to int.
Syntax:

short s = 10000;

Example Program:

This program demonstrates the use of the short data type in Java, which is a 16-bit
signed integer.
Variable:
● s: A short variable initialized with the value 30000. The short data type
can store values in the range from -32,768 to 32,767, so 30000 is well within
this range.
Output:
● The program prints the value of the short variable to the console.

public class ShortExample {


public static void main(String[] args) {
short s = 30000;
System.out.println("Short value: " + s);
}
}

Output:
Short value: 30000
3. int
Description: A 32-bit signed integer.
Size: 4 bytes (32 bits).
Range: -2^31 to 2^31 - 1.
Characteristics:
The most commonly used integer type in Java.
Suitable for representing whole numbers within a wide range.
Syntax:

int i = 100000;

Example Program:

Problem analysis: This program showcases how to use the int data type, which is a
32-bit signed integer.

Variable:
● i: An int variable initialized with the value 150000. The int type can store
values from -2^31 to 2^31 - 1, so 150000 is well within this range.
Output:
● The program prints the value of the int variable to the console.
Code:

public class IntExample {


public static void main(String[] args) {
int i = 150000;
System.out.println("Int value: " + i);
}
}

Output:
Int value: 150000

4. long
Description: A 64-bit signed integer.
Size: 8 bytes (64 bits).
Range: -2^63 to 2^63 - 1.
Characteristics:
Used when a wider range than int is needed.
Useful for large numerical values that exceed the int range.
Syntax:

long variable_name = valueL;

Example:

Program Analysis: This program illustrates how to use the long data type, which is a
64-bit signed integer.
Variable:
l: A long variable initialized with the value 10000000000L. The long type
can store values from -2^63 to 2^63 - 1, so 10000000000L is well
within this range. The L suffix specifies that the literal is of type long.
Output:
The program prints the value of the long variable to the console.
Code:

public class LongExample {


public static void main(String[] args) {
long l = 10000000000L; // Declaring and initializing a long
variable
System.out.println("Long value: " + l); // Printing the long
value to the console
}
}

Output:
Long value: 10000000000

Other data types (Non-Integer)


Default
Datatype Default Size Range Example
Value

Float 4 Byte 0f 3.4e−038 to 3.4e+038 float num1 = 67.02f;

Double 8 Byte 0d 1.7e−308 to 1.7e+308 double num1 = 79.678d;

Char 2 Byte u0000 \u0000’ to ‘\uffff char name = ‘B’;

Boolean 1 Bit false true’ or ‘false boolean myFlag = true;

5. float
Description: A single-precision 32-bit IEEE 754 floating point.
Size: 4 bytes (32 bits).
Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits).
Characteristics:
Used to save memory in large arrays of floating-point numbers.
Less precise than double.
Syntax:
float f = 5.75f;

Example Program:
Program analysis: This program showcases how to use the float data type, which
is a single-precision 32-bit IEEE 754 floating-point.
- Variable:
- f: A float variable initialized with the value 5.75f. The f suffix specifies that
the literal is of type float rather than double. This suffix is necessary to
indicate that the literal should be treated as a float because by default,
floating-point literals are treated as double.
- Output:
- The program prints the value of the float variable to the console.

public class FloatExample {


public static void main(String[] args) {
float f = 5.75f;
System.out.println("Float value: " + f);
}
}

Output:
Float value: 5.75

6. double
Description: A double-precision 64-bit IEEE 754 floating point.
Size: 8 bytes (64 bits).
Range: Approximately ±1.79769313486231570E+308 (15-16 significant decimal digits).
Characteristics:
The default data type for decimal values.
Provides greater precision than float.
Syntax:

double variable_name = value;

Example Program:
Program analysis: The below program DoubleExample program demonstrates the use of
the double primitive data type in Java. Here’s a detailed explanation:

Explanation:
Purpose: The program showcases the use of the double data type, which is a
double-precision 64-bit IEEE 754 floating-point.
Variable:
d: A double variable initialized with the value 19.99. By default, floating-
point literals are treated as double, so no suffix is needed in this case.
Output:
- The program prints the value of the double variable to the console.

Code:

public class DoubleExample {


public static void main(String[] args) {
double d = 19.99; // Declaring and initializing a double
variable
System.out.println("Double value: " + d); // Printing the
double value to the console
}
}

Output:
Double value: 19.99
7. char
Description: A single 16-bit Unicode character.
Size: 2 bytes (16 bits).
Range: '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
Characteristics:
Used to store any character.
Can store Unicode characters, allowing for a wide range of symbols.
Syntax:
char c = 'A';

Example Program:
Program analysis: This program shows how to use the char data type, which is a 16-
bit Unicode character.
Variable:
c: A char variable initialized with the character 'A'. The char type is used to store
single characters or symbols.
Output:
The program prints the value of the char variable to the console.
Code:

public class CharExample {


public static void main(String[] args) {
char c = 'A';
System.out.println("Char value: " + c);
}
}

Output:
Char value: A

8. boolean
Description: Represents one bit of information but its "size" isn't precisely defined.
Size: Typically 1 byte (but not standardized).
Range: true or false.
Characteristics:
Used for simple flags that track true/false conditions.
Not directly convertible to integers or other types.

Syntax:

boolean variable_name = booleanvalue;

Example Program:

Program analysis: This program illustrates how to use the boolean data type, which
represents true or false values.
Variable:
isJavaFun: A boolean variable initialized with the value true. The boolean
type is used to represent logical values and is commonly used in control flow
statements.
Output:
The program prints the value of the boolean variable to the console.
Code:

public class BooleanExample {


public static void main(String[] args) {
boolean isJavaFun = true;
System.out.println("Boolean value: " + isJavaFun);
}
}

Output

Boolean value: true


Do It Yourself
1. Explain the difference between float and double data types in Java. Provide examples of when
each might be used.
2. Write a Java program that declares variables of all eight primitive data types and assigns them
some initial values. Print these values to the console.
3. What is the default value of each primitive data type in Java if declared as instance variables?
List them all.
4. Explain why Java has both char and int data types. Provide an example where each is used
appropriately.
5. Describe the range of the byte data type in Java. Write a Java program that demonstrates an
overflow scenario with a byte variable.

Quiz
1. Which of the following is the smallest data type in Java?

A) int
B) short
C) byte
D) long

Correct Answer: C) byte

2. What is the default value of a boolean type in Java?

- A) true
- B) false
- C) 0
- D) null

Correct Answer: B) false


3. Which of the following data types is used to store a single Unicode character in
Java?

A) byte
B) char
C) int
D) float

Correct Answer: B) char

4. What is the range of values that a short data type can hold in Java?

- A) -128 to 127
- B) -32,768 to 32,767
- C) -2,147,483,648 to 2,147,483,647
- D) 0.0 to 1.0

Correct Answer: B) -32,768 to 32,767

5. Which of the following literals is valid for a float data type?

- A) 10.0
- B) 10.0d
- C) 10.0f
- D) 10L

Correct Answer: C) 10.0f

1.2. Non-Primitive (Referrance) Datatypes


Non-Primitive Data Types in Java
Non-primitive data types, also known as reference data types, are more complex and versatile
than primitive data types. They include classes, interfaces, arrays, strings, and enums. Here’s a
detailed look at each type:

1. Strings
Definition:
A String is an object that represents a sequence of characters. It is used to handle
and manipulate text. Strings in Java are immutable, meaning once a String object is
created, it cannot be modified. The String class is part of the java.lang package.

Syntax:

String variableName = "value";

Example:
String greeting = "Hello, World!";

Problem Analysis:

This program shows how to use the String data type to store and manipulate text.

Variables:
greeting: A String variable initialized with the value "Hello,
World!".
name: A String variable initialized with the value "Alice".
message: A String variable that concatenates greeting and name
along with additional text to form a complete sentence.
Output:
The program prints the concatenated message to the console.
Code:

public class StringExample {


public static void main(String[] args) {
String greeting = "Hello, World!";
String name = "Alice";
String message = greeting + " My name is " + name + ".";

System.out.println(message);
}
}

Output:

Hello, World! My name is Alice.

2. Arrays
Definition:
An Array is a collection of elements of the same type stored in contiguous memory locations.
It allows you to store multiple values in a single variable. Arrays can be single-dimensional or
multi-dimensional. The size of an array is fixed once it is created.

Syntax :

type[] arrayName = new type[size];

Example:
int[] numbers = new int[5];

Problem Analysis: This program illustrates how to use arrays to store multiple values of the
same data type in a single variable and how to access and display these values using a loop.

Variables:
numbers: An int array initialized with five integer elements {1, 2, 3, 4,
5}. The array allows us to store a fixed number of integers.
Loop:
A for loop iterates through each element of the array using the length
property of the array to determine its size. The loop index i is used to access
each element in the array.
Output:
The program prints each element of the array along with its index position.

Code

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Declaring and
initializing an int array

for (int i = 0; i < numbers.length; i++) { // Looping


through the array
System.out.println("Element at index " + i + ": " +
numbers[i]); // Printing each element with its index
}
}
}

Output
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

3. Classes
Definition:
A Class is a blueprint for creating objects. It defines data fields (attributes) and methods
(functions) that describe the behavior of objects. Classes are fundamental to object-oriented
programming (OOP) in Java. You can create multiple objects from a single class.

Syntax :

public class ClassName {


// Data fields
// Methods
}

Example:
public class Car {
String model;
int year;

void start() {
System.out.println("The car is starting.");
}
}

Problem Analysis:
This program illustrates how to define a class with attributes and methods, create an object from
that class, and manipulate the object's state using its attributes and methods.

● Class:

○ Car: A class representing a blueprint for car objects. It contains:


■ Attributes:
● model: A String representing the model of the car.
● year: An int representing the manufacturing year of the car.
■ Methods:
● start(): A method that prints a message indicating that the car
is starting. It uses the model attribute in its message.

● Main Method:

○ The main method is the entry point of the program. It performs the following
steps:
■ Object Creation: Car myCar = new Car(); — Creates a new
instance of the Car class.
■ Attribute Assignment:
● myCar.model = "Toyota"; — Sets the model attribute of
myCar to "Toyota".
● myCar.year = 2020; — Sets the year attribute of myCar
to 2020.
■ Method Call: myCar.start(); — Calls the start() method on the
myCar object, which prints a message to the console.

Code:

public class Car {


String model; // Attribute for the car's model
int year; // Attribute for the car's manufacturing year

// Method to simulate starting the car


void start() {
System.out.println("The " + model + " car is starting.");
}

public static void main(String[] args) {


Car myCar = new Car(); // Creating a new Car object
myCar.model = "Toyota"; // Assigning the model attribute
myCar.year = 2020; // Assigning the year attribute
myCar.start(); // Calling the start method to print a
message
}
}

Output
The Toyota car is starting.

4. Interfaces

Definition:
An Interface is an abstract type that defines a contract of methods without implementations.
Classes that implement an interface must provide implementations for all methods declared in
the interface. Interfaces support multiple inheritance in Java. Methods in interfaces are abstract
by default.

Syntax :

public interface InterfaceName {


void methodName();
}

Example:
public interface Drawable {
void draw();
}

Problem Analysis:
This program illustrates how to use an interface to define a contract for classes and then
implement this interface in a class. In this example, the Drawable interface represents a
drawable entity, and the Circle class implements this interface to provide a specific way to
"draw" a circle.

Interface:

Drawable: This interface with a single method, draw(). Any class that implements this
interface must provide an implementation for the draw() method.

Class:

Circle: This class implements the Drawable interface and provides its own
implementation of the draw() method. In this implementation, it prints "Drawing a
circle." to the console.

Main Method:

In the main method, a new instance of Circle is created, and its draw() method is
called. This demonstrates how an object of a class implementing an interface can be
used to perform actions defined by the interface.
Code

// Define the Drawable interface with a draw method


public interface Drawable {
void draw();
}

// Implement the Drawable interface in the Circle class


public class Circle implements Drawable {
// Provide the implementation of the draw method
public void draw() {
System.out.println("Drawing a circle.");
}
// Main method to run the program
public static void main(String[] args) {
Circle circle = new Circle(); // Create an instance of
Circle
circle.draw(); // Call the draw method
}
}

Output
Drawing a circle.

5. Enums
Definition:
An Enum (short for enumeration) is a special data type that defines a set of named constants.
It is used to represent a fixed set of related values. Enums are useful for representing a group of
constants, such as days of the week or states of an object. Enums are implicitly final and
cannot be subclassed.

Syntax:

public enum EnumName {


CONSTANT1, CONSTANT2, CONSTANT3;
}

Example:

public enum Day {


MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY
}
Problem Analysis:
This program demonstrates how to use enums in Java, including defining an enum, using it in a
switch statement, and handling different cases. Here’s a detailed breakdown:

Enum Definition:
● Day: This enum defines a set of constants representing the days of the week. Enums
are helpful in representing a fixed set of related values.
Main Method:
● Day today = Day.FRIDAY;: An instance of the Day enum is created and
initialized to FRIDAY.
● switch (today): The switch statement handles different values of the Day
enum and allows for specific actions based on today's value.
Switch-Case:
● case MONDAY: If today is MONDAY, it prints "Start of the work week."
● case FRIDAY: If today is FRIDAY, it prints "End of the work week."
● default: For any other day not explicitly handled, it prints "Midweek days."

Code:

public class EnumExample {


public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY
}

public static void main(String[] args) {


Day today = Day.FRIDAY;

switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("End of the work week.");
break;
default:
System.out.println("Midweek days.");
break;
}
}
}

Output:

End of the work week.

Do It Yourself
1. What are non-primitive (reference) data types in Java? Give three examples and explain their use
cases.
2. Write a Java program that demonstrates the use of an ArrayList. Add, remove, and retrieve
elements from the list.
3. How does a String in Java differ from a char array? Provide a Java code example that illustrates
the difference.
4. Explain how Java handles memory management for reference data types. Discuss the role of the
garbage collector.
5. Write a Java program to demonstrate the difference between shallow copy and deep copy of an
object.

Quiz
1. Which of the following is not a non-primitive data type in Java?

A) String
B) Array
C) Integer
D) char

Correct Answer: D) char

2. Which data type is used to represent a collection of elements of the


same type in Java?
A) Array
B) int
C) float
D) boolean
Correct Answer: A) Array

3. Which class in Java is used to represent a sequence of characters?

A) StringBuilder
B) String
C) Character
D) StringBuffer

Correct Answer: B) String

4. Which of the following is true about enums in Java?

A) Enums can be used to define constants with specific values.


B) Enums can have constructors and methods.
C) Enums cannot be used in switch-case statements.
D) Enums are automatically assigned numeric values.

Correct Answer: A) Enums can be used to define constants with specific values.

5. What is the output of the following code snippet?


String[] names = {"Alice", "Bob", "Charlie"};
System.out.println(names[1]);

A) Alice
B) Bob
C) Charlie
D) Index out of bounds

Correct answer: B) Bob

2. Variables

Variable Declaration and Initialization


Definition
In Java, a variable is a container that holds data that can be changed during the execution of a
program. Declaring a variable means defining its type and name, while initialization means
assigning it a value.
- Declaration: Specifies the type of the variable and its name. It tells the Java compiler
what kind of data the variable will hold.
- Initialization: Provides an initial value to the variable. This value can be changed later in
the program.
-

Syntax
The general syntax for declaring and initializing a variable is:

dataType variableName;
dataType variableName = value;

- dataType specifies the type of data the variable will store (e.g., int, double,
String).
- variableName is the name of the variable.
- value is the initial value assigned to the variable.

Example
Here’s a simple example:

int age = 30;

In this example:

- int is the data type.


- age is the variable name.
- 30 is the value assigned to the variable.

Example Program:
Program Analysis:
The below example demonstrates how to declare and initialize different types of
variables and how to output their values to the console.

Code:

public class VariableExample {


public static void main(String[] args) {
// Variable declaration and initialization
int number = 10; // Integer variable
double price = 99.99; // Double variable
String name = "Alice"; // String variable
// Output the values of the variables
System.out.println("Number: " + number);
System.out.println("Price: " + price);
System.out.println("Name: " + name);
}
}

- The main method is the entry point of the program.


- Three variables are declared and initialized:
- number is of type int and initialized with 10.
- price is of type double and initialized with 99.99.
- name is of type String and initialized with "Alice".
- The System.out.println statements are used to print the values of the variables
to the console.

Output:

Number: 10
Price: 99.99
Name: Alice

Variable Naming Rules and Conventions in Java


In Java, variable names must follow specific rules and conventions to ensure code readability
and avoid compilation errors. Understanding these rules and conventions is essential for writing
clear, maintainable, and standard-compliant code.

Variable Naming Rules


1. Start with a Letter or Underscore:

- A variable name must begin with a letter (a-z or A-Z), a dollar sign ($), or an
underscore (_).
- Java variable names cannot start with a digit (0-9).

2. No Spaces Allowed:
- Variable names cannot contain spaces. If a variable name is composed of
multiple words, use camelCase (e.g., myVariableName).

3. Case Sensitivity:

- Java is case-sensitive, meaning that myVariable and myvariable are


considered two different variables.

4. No Reserved Keywords:

- Variable names cannot be a Java keyword or reserved word (e.g., class,


public, void, int).

5. No Special Characters:

- Apart from $ and _, no other special characters (like @, #, !, etc.) are allowed
in variable names.

6. Unlimited Length:

- Variable names can be of any length, but they should be kept readable and
concise.

Variable Naming Conventions


1. Use Meaningful Names:

- Variable names should be descriptive and indicate the purpose or usage of the
variable. For example, use totalAmount instead of x.

2. Camel Case for Variables:

- Use camelCase for variable names, where the first letter is lowercase, and each
subsequent word starts with an uppercase letter (e.g., studentName,
totalScore).

3. Constants in Uppercase:

- Constants (variables marked as final that never change value) should be


named using all uppercase letters with words separated by underscores (e.g.,
MAX_HEIGHT, PI_VALUE).

4. Avoid Using One-Letter Variables:


- Avoid using single-character names, except for temporary variables used in
loops or very small scopes (i, j, k in loops are exceptions).

5. Use Abbreviations Sparingly:

- If you must use abbreviations, use them consistently and make sure they are
commonly understood. Avoid obscure abbreviations.

6. Avoid Confusing Names:

- Do not use variable names that are easily confused with each other (e.g., l
(lowercase L), O (uppercase o), and 0 (zero)).

7. Use Singular Names for Single Entities:

- If a variable represents a single entity, use a singular noun (e.g., student). If it


represents a collection, use a plural noun (e.g., students).

8. Follow Project or Team Standards:

- Adhere to any naming conventions set by your team or organization to maintain


consistency across the codebase.

Examples of Good and Bad Variable Names


Bad Variable Name Good Variable Name

x totalAmount

data studentData

temp temperature

var1 numberOfStudents

MAX MAX_HEIGHT

counter_1 studentCounter

By following these rules and conventions, you ensure that your code is not only syntactically
correct but also readable, maintainable, and consistent with Java programming best practices.
Do It Yourself
1. What is the difference between local variables and instance variables in Java?
Provide examples.
2. Write a Java program that demonstrates variable declaration and initialization in
different scopes (method level, class level, etc.).
3. Explain what happens when a variable is declared but not initialized in Java.
Provide a code example to support your explanation.
4. Describe the rules for naming variables in Java. List at least five valid and five
invalid variable names.
5. What is a static variable in Java? How does it differ from an instance variable?
Provide a code example.

Quiz

1. Which of the following is the correct way to declare and initialize an integer variable in
Java?
A) int num = 10;
B) integer num = 10;
C) int num := 10;
D) int num == 10;

Correct Answer: A) int num = 10;

2. What is the output of the following code snippet?

int x;
x = 5;
System.out.println(x);
A) 0
B) 5
C) null
D) Error: Variable x might not have been initialized

Correct Answer: B) 5

3. What will happen if you try to compile and run the following code snippet?

double price = 9.99;


int total = price;
System.out.println(total);

A) The code will compile and print 9


B) The code will compile and print 9.99
C) The code will compile but result in a runtime error
D) The code will not compile due to a type mismatch error

Correct Answer: D) The code will not compile due to a type mismatch error

4. Which of the following is a valid declaration of a String variable in Java?


A) String name = "John";
B) String name = 'John';
C) string name = "John";
D) String name = John;

Correct Answer: A) String name = "John";

5. What is the result of trying to compile and run the following code snippet?

int a = 5, b = 10;
int c;
c = a + b;
System.out.println(c);

A) The code will print 15


B) The code will print 5
C) The code will print 10
D) The code will not compile due to an initialization error

Correct Answer: A) The code will print 15

2.1 Variables Scope

Variable Scope
Definition
In Java, the scope of a variable refers to the region of the code where the variable can be
accessed or used. Variable scope is determined by where the variable is declared within the
code. Understanding variable scope is essential for writing effective and error-free programs.
Types of variables:
- Local Scope: Variables declared inside a method, constructor, or block are considered
local variables. They are only accessible within the specific block or method in which
they are declared and are not visible outside of it.

- Instance (Object) Scope: Variables declared inside a class but outside of any method
are called instance variables. They are also known as non-static fields and can be
accessed by any non-static method in the class. Each object of the class has its own
copy of the instance variables.

- Class (Static) Scope: Variables declared with the static keyword inside a class are
called static variables or class variables. They belong to the class rather than any
particular object and can be accessed by all instances of the class.

Syntax
The general syntax for declaring variables with different scopes is:

class ClassName {
// Instance variable (Object scope)
dataType instanceVariableName;

// Static variable (Class scope)


static dataType staticVariableName;

public void someMethod() {


// Local variable (Local scope)
dataType localVariableName;
}
}

Example

Here’s a simple example demonstrating different scopes:

public class ScopeExample {


// Instance variable (Object scope)
int instanceVar = 5;

// Static variable (Class scope)


static int staticVar = 10;

public void display() {


// Local variable (Local scope)
int localVar = 15;
System.out.println("Instance Variable: " +
instanceVar);
System.out.println("Static Variable: " + staticVar);
System.out.println("Local Variable: " + localVar);
}
}

Example Program:

Program analysis:
This example illustrates the scope and lifetime of different types of variables in Java.

Code:

public class VariableScopeExample {


// Instance variable (Object scope)
int instanceCounter = 0;

// Static variable (Class scope)


static int staticCounter = 0;

public void incrementCounters() {


// Local variable (Local scope)
int localCounter = 0;

// Incrementing all counters


instanceCounter++;
staticCounter++;
localCounter++;

// Displaying values of all counters


System.out.println("Instance Counter: " + instanceCounter);
System.out.println("Static Counter: " + staticCounter);
System.out.println("Local Counter: " + localCounter);
}

public static void main(String[] args) {


// Creating two objects of VariableScopeExample class
VariableScopeExample obj1 = new VariableScopeExample();
VariableScopeExample obj2 = new VariableScopeExample();

// Calling incrementCounters() method on both objects


System.out.println("First call on obj1:");
obj1.incrementCounters();

System.out.println("\nSecond call on obj1:");


obj1.incrementCounters();

System.out.println("\nFirst call on obj2:");


obj2.incrementCounters();
}
}

Explanation:
- Instance Variable (instanceCounter): Each object (obj1 and obj2) has its own
copy of the instance variable instanceCounter. Modifying instanceCounter in
one object does not affect the value in another object.

- Static Variable (staticCounter): There is only one copy of the static variable
staticCounter shared among all instances of the class. Incrementing
staticCounter in one object will affect the value seen by all objects.

- Local Variable (localCounter): This variable is defined within the


incrementCounters() method. It is created each time the method is called and
destroyed once the method completes. It is not accessible outside the method.

Output:
First call on obj1:
Instance Counter: 1
Static Counter: 1
Local Counter: 1

Second call on obj1:


Instance Counter: 2
Static Counter: 2
Local Counter: 1

First call on obj2:


Instance Counter: 1
Static Counter: 3
Local Counter: 1

Explanation of the Output:

When incrementCounters() is called on obj1 the first time:


instanceCounter is incremented to 1 for obj1.
staticCounter is incremented to 1 for the class.
localCounter is reset to 1 since it is local and created anew on each
method call.
On the second call on obj1:
instanceCounter for obj1 increments to 2.
staticCounter increments to 2.
localCounter is reset to 1 again.
On the first call on obj2:
instanceCounter for obj2 is initialized to 1.
staticCounter increments to 3 since it is shared across all objects.
localCounter is again initialized to 1.

This example illustrates the scope and lifetime of different types of variables in Java.

Do It Yourself
1. What is the scope of a local variable in Java? Write a Java program to
demonstrate the scope of a local variable.
2. How does the scope of an instance variable differ from that of a class variable?
Provide examples.
3. Write a Java program that declares a variable inside a loop and explain its scope.
What happens if you try to access it outside the loop?

Quiz

1. What is the scope of a local variable in Java?


A) Within the entire class
B) Within the method it is declared
C) Within the package
D) Within the block it is declared
Correct Answer: B) Within the method it is declared

2. What will be the output of the following code snippet?

public class Test {


public static void main(String[] args) {
int x = 5;
{
int y = 10;
System.out.println(x + y);
}
System.out.println(y); // Line A
}
}

A) 15
B) Compilation error at Line A
C) 10
D) 5

Correct Answer: B) Compilation error at Line A

3. Which of the following statements is true regarding the scope of instance variables in
Java?
A) Instance variables are accessible only within the method they are declared
B) Instance variables are accessible within the entire class and can be accessed by all
methods in the class
C) Instance variables are accessible only within the constructor
D) Instance variables are accessible only within the block they are declared

Answer: B) Instance variables are accessible within the entire class and can be
accessed by all methods in the class

4. What will happen if two variables with the same name are declared in a method, one
inside a block and one outside?
public class Test {
public static void main(String[] args) {
int x = 5;
{
int x = 10; // Line A
System.out.println(x);
}
System.out.println(x);
}
}

A) The code will compile and print 10 and 5


B) The code will compile and print 5 and 5
C) The code will result in a compilation error at Line A
D) The code will compile and print 10 and 10

Answer: C) The code will result in a compilation error at Line A

5. What is the scope of a static variable in Java?

A) Static variables are accessible only within the block they are declared
B) Static variables are accessible within the method they are declared
C) Static variables are accessible within the entire class and shared among all instances
D) Static variables are accessible only within the object they are declared

Correct Answer: C) Static variables are accessible within the entire class and shared
among all instances

2.2 Type Conversion and Casting


Type Conversion and Casting

Definition

In Java, type conversion is the process of converting a variable from one data type to another.
There are two types of type conversion:

1. Implicit Type Conversion (Widening Conversion): Automatically performed by the


Java compiler when converting a smaller data type to a larger data type. No data loss
occurs during this conversion.
2. Explicit Type Casting (Narrowing Conversion): Manually performed by the
programmer to convert a larger data type to a smaller data type. This may result in data
loss or precision loss.

Additional Details
- Implicit Type Conversion: This type of conversion happens when the data types are
compatible, and there is no possibility of data loss. For example, converting an int to a
long or a float to a double.
- Explicit Type Casting: This type of conversion is required when converting from a
larger data type to a smaller one (e.g., double to int). The programmer needs to
explicitly cast the value to the desired type, which may lead to loss of information or data
truncation.

General Syntax

1. Implicit Type Conversion:

largerDataType variableName = smallerDataTypeValue;

2. Explicit Type Casting:

smallerDataType variableName = (smallerDataType)


largerDataTypeValue;

Example
Here’s an example demonstrating both implicit type conversion and explicit type casting:

public class TypeConversionExample {


public static void main(String[] args) {
// Implicit Type Conversion (Widening)
int integerNum = 100;
double doubleNum = integerNum; // int to double
(Implicit)

// Explicit Type Casting (Narrowing)


double originalDouble = 9.78;
int castedInt = (int) originalDouble; // double to
int (Explicit)

System.out.println("Original integer: " +


integerNum);
System.out.println("Converted to double (Implicit):
" + doubleNum);
System.out.println("Original double: " +
originalDouble);
System.out.println("Casted to int (Explicit): " +
castedInt);
}
}

Example Program:

Program Analysis:
This example illustrates the differences between implicit type conversion and explicit type
casting in Java, demonstrating when each is used and what kind of data manipulation occurs.
Code:

ublic class TypeCastingExample {


public static void main(String[] args) {
// Implicit Type Conversion (Widening)
int intNum = 150;
long longNum = intNum; // int to long (Implicit)
float floatNum = longNum; // long to float (Implicit)

// Displaying results of Implicit Conversion


System.out.println("Integer value: " + intNum);
System.out.println("Long value (Implicit Conversion from int): " + longNum);
System.out.println("Float value (Implicit Conversion from long): " + floatNum);

// Explicit Type Casting (Narrowing)


double doubleValue = 45.67;
int intCasted = (int) doubleValue; // double to int (Explicit)
char charCasted = (char) intCasted; // int to char (Explicit)

// Displaying results of Explicit Casting


System.out.println("Double value: " + doubleValue);
System.out.println("Int value after Casting from double: " + intCasted);
System.out.println("Char value after Casting from int: " + charCasted);
}

Program Analysis:

- Implicit Type Conversion:

- The variable intNum is of type int and has a value of 150.


- This value is implicitly converted to a long type and stored in longNum.
- The longNum value is then implicitly converted to a float type and stored in
floatNum.
- No data loss occurs during these conversions as they are widening conversions.

- Explicit Type Casting:

- The variable doubleValue is of type double and has a value of 45.67.


- It is explicitly cast to an int, resulting in the loss of the decimal portion (45 is
stored in intCasted).
- The intCasted value is then explicitly cast to a char, where the integer
value 45 is converted to the character equivalent based on its ASCII value.

Output:

Integer value: 150


Long value (Implicit Conversion from int): 150
Float value (Implicit Conversion from long): 150.0
Double value: 45.67
Int value after Casting from double: 45
Char value after Casting from int: -

Explanation of the Output:

- Implicit Conversion:

- The integer value 150 is stored as a long without any change.


- The long value 150 is converted to a float, resulting in 150.0 due to the
floating-point format.

- Explicit Casting:

- The double value 45.67 is explicitly cast to int, which truncates the decimal
part, resulting in 45.
- The int value 45 is then cast to a char, resulting in the character - (which is
the ASCII character corresponding to the integer value 45).

Do It Yourself
1. Explain the difference between implicit and explicit type casting in Java with
examples.
2. Write a Java program that converts a double to an int and an int to a float.
Print the results before and after casting.
3. Identify and correct any errors in the following code snippet:

int a = 100;
byte b = a; // Line A
double c = 3.14;
int d = c; // Line B

4. Why is explicit casting required when converting from a double to an int?


What potential issues could arise from this conversion?
5. Write a Java program that reads a character input from the user and casts it to its
corresponding ASCII integer value.

Quiz
1. What is the result of the following code snippet?

int x = 10;
double y = x;
System.out.println(y);

A) 10.0
B) 10
C) Compilation error
D) 10.00

Correct Answer: A) 10.0


Reason [10.0: Implicit casting occurs from int to double.]

2. What type of casting is demonstrated in the following code snippet?

double a = 9.78;
int b = (int) a;
System.out.println(b);

A) Implicit casting
B) Explicit casting
C) Auto-boxing
D) Unboxing

Correct Answer: B) Explicit casting


Reason [Explicit casting: The double value 9.78 is explicitly cast to int, resulting in 9.]

3. Which of the following is an example of implicit casting (widening conversion)?


A) byte b = (byte) 100;
B) int i = (int) 100.5;
C) long l = 100;
D) double d = (double) 100;

Correct Answer: C) long l = 100;


Reason [long l = 100;: Implicit casting occurs from int to long.]
4. What will be the output of the following code snippet?

short s = 10;
s = s + 1; // Line A
System.out.println(s);

A) 11
B) Compilation error at Line A
C) 10
D) 1

Correct Answer: B) Compilation error at Line A


Reason [ Compilation error at Line A: The expression s + 1 is promoted to int, so you
cannot assign it directly to short.]

5. What happens when the following code is executed?


int i = 257;
byte b = (byte) i;
System.out.println(b);


A) 257
B) Compilation error due to type mismatch
C) 1
D) -1

Correct Answer: D) 1
Reason [The int value 257 is outside the range of byte (-128 to 127), so it wraps around,
resulting in 1.]

3. Constants
Literal Constants in Java
Definition

Literal constants in Java are fixed values that are directly assigned in the code. They
represent raw values written exactly as they are meant to be interpreted by the compiler. These
constants are not variables; instead, they are the actual data values that are hardcoded into a
program. Literal constants cannot change during the execution of a program, making them
"constants."

Types of Literal Constants in Java


Java supports several types of literal constants, each corresponding to a specific data type:

1. Integer Literals: These represent whole numbers without any fractional or decimal part.

- Decimal (Base 10): 1, 100, -45


- Octal (Base 8): Prefixed with 0 (zero), e.g., 012 (which is 10 in decimal)
- Hexadecimal (Base 16): Prefixed with 0x or 0X, e.g., 0x1A (which is 26 in
decimal)
- Binary (Base 2): Prefixed with 0b or 0B, e.g., 0b1010 (which is 10 in
decimal)

2. Floating-Point Literals: These represent real numbers with fractional parts.

- Decimal Form: 3.14, -0.001, 2.0


- Exponential Form: 1.5e3 (which is 1500.0), 2.1E-4 (which is 0.00021)

3. Character Literals: These represent single characters enclosed in single quotes.

- Examples: 'A', '9', '$', '\n' (newline character), '\u0041'


(Unicode representation for 'A')

4. String Literals: These represent sequences of characters enclosed in double quotes.

- Examples: "Hello, World!", "Java Programming", "12345"


5. Boolean Literals: These represent the two truth values in Java.

- Examples: true, false

6. Null Literal: Represents a null reference (i.e., no object reference).

- Example: null

Example Usage of Literal Constants

Here is an example demonstrating various types of literal constants in Java:

public class LiteralConstantsExample {


public static void main(String[] args) {
// Integer Literals
int decimalLiteral = 100; // Decimal (base 10)
int octalLiteral = 012; // Octal (base 8)
int hexLiteral = 0x1A; // Hexadecimal (base 16)
int binaryLiteral = 0b1010; // Binary (base 2)

// Floating-Point Literals
double decimalFloat = 3.14; // Decimal floating-point
double exponentialFloat = 1.5e3; // Exponential floating-point

// Character Literals
char charLiteral = 'A';
char unicodeCharLiteral = '\u0041'; // Unicode for 'A'
char escapeCharLiteral = '\n'; // Newline character

// String Literals
String stringLiteral = "Hello, World!";

// Boolean Literals
boolean trueLiteral = true;
boolean falseLiteral = false;

// Null Literal
String nullLiteral = null;

// Output the literal values


System.out.println("Decimal Literal: " + decimalLiteral);
System.out.println("Octal Literal: " + octalLiteral);
System.out.println("Hexadecimal Literal: " + hexLiteral);
System.out.println("Binary Literal: " + binaryLiteral);
System.out.println("Decimal Floating-Point Literal: " + decimalFloat);
System.out.println("Exponential Floating-Point Literal: " +
exponentialFloat);
System.out.println("Character Literal: " + charLiteral);
System.out.println("Unicode Character Literal: " + unicodeCharLiteral);
System.out.println("Escape Character Literal: " + escapeCharLiteral);
System.out.println("String Literal: " + stringLiteral);
System.out.println("Boolean Literal (true): " + trueLiteral);
System.out.println("Boolean Literal (false): " + falseLiteral);
System.out.println("Null Literal: " + nullLiteral);
}
}

Explanation of the Output

- Decimal Literal (100): A standard integer.


- Octal Literal (012): Represents the decimal number 10.
- Hexadecimal Literal (0x1A): Represents the decimal number 26.
- Binary Literal (0b1010): Represents the decimal number 10.
- Decimal Floating-Point Literal (3.14): Represents the floating-point number 3.14.
- Exponential Floating-Point Literal (1.5e3): Represents the floating-point number
1500.0.
- Character Literal ('A'): Represents the character A.

- Unicode Character Literal ('\u0041'): Represents the Unicode character A.


- Escape Character Literal ('\n'): Represents a newline character.
- String Literal ("Hello, World!"): Represents a sequence of characters.
- Boolean Literals (true, false): Represent the truth values.
- Null Literal (null): Represents a null reference (no object).

Symbolic Constants in Java


Definition
Symbolic constants in Java, also known as named constants, are constants declared using
the final keyword and assigned a value that cannot change throughout the execution of a
program. Unlike literal constants, which are raw values, symbolic constants are given
meaningful names, which improves code readability and maintainability. They are commonly
used to represent values that are referenced multiple times in a program and should remain
unchanged to avoid magic numbers or strings.

Characteristics of Symbolic Constants


- Declared with the final Keyword: This keyword makes the variable immutable after
its initial assignment.
- Assigned a Value at Declaration: The value of a symbolic constant must be assigned
when it is declared.
- Cannot Be Modified: Any attempt to modify the value of a symbolic constant will result
in a compilation error.
- Typically Written in Uppercase: By convention, symbolic constants are written in
uppercase letters with underscores separating words. This helps distinguish them from
regular variables.
General Syntax

final dataType CONSTANT_NAME = value;

- final: The keyword that makes the variable a constant.


- dataType: Specifies the data type of the constant (e.g., int, double, String).
- CONSTANT_NAME: The name of the constant, typically in uppercase letters.
- value: The initial value assigned to the constant.

Example Usage of Symbolic Constants


Here’s an example demonstrating the use of symbolic constants in Java:

public class SymbolicConstantsExample {


// Declaring symbolic constants
public static final int MAX_SPEED = 120; // Maximum speed limit
public static final double PI = 3.14159; // Value of Pi
public static final String GREETING = "Hello"; // Greeting message
public static final char NEWLINE = '\n'; // Newline character

public static void main(String[] args) {


// Using symbolic constants
int speed = 80;

System.out.println(GREETING + ", welcome to the program!");


System.out.println("The maximum allowed speed is: " + MAX_SPEED + " km/h.");
System.out.println("The area of a circle with radius 2 is: " + (PI * 2 * 2));
System.out.println("Is the current speed (" + speed + " km/h) within the
limit? " + (speed <= MAX_SPEED));
System.out.println("Character representation of newline is:" + NEWLINE +
"This text is on a new line.");

// Uncommenting the line below will cause a compilation error


// MAX_SPEED = 150; // Error: cannot assign a value to final variable
MAX_SPEED
}
}

Example Program:

Program Analysis:

Code:

public class CircleAreaCalculator {


// Declaring symbolic constants
private static final double PI = 3.14159; // PI constant
private static final String SHAPE_NAME = "Circle"; // Name of the shape

public static void main(String[] args) {


// Radius of the circle
double radius = 5.0;

// Calculating the area of the circle using the symbolic constant PI


double area = PI * radius * radius;

// Displaying the results


System.out.println("Shape: " + SHAPE_NAME);
System.out.println("Radius: " + radius);
System.out.println("Area of the " + SHAPE_NAME + ": " + area);
}
}

Program Analysis:

- Symbolic Constants (PI and SHAPE_NAME):


- PI is a double constant representing the mathematical constant π (pi). It is
marked final to prevent modification.
- SHAPE_NAME is a String constant representing the name of the shape
("Circle"). It is also marked final.
- Both constants are declared static because they belong to the class rather
than any instance of the class.
- Usage of Constants:
- The program uses PI to calculate the area of a circle based on a given radius.
- SHAPE_NAME is used to make the output message more readable and
informative.
- Benefits of Symbolic Constants:
- By using symbolic constants, the code becomes more readable and
maintainable.
- The risk of accidental value changes is minimized since these constants cannot
be modified after declaration.

Output:

Shape: Circle
Radius: 5.0
Area of the Circle: 78.53975

Explanation of the Output:

- The shape is "Circle," which is printed using the SHAPE_NAME constant.


- The radius is 5.0, which is used in the calculation for the area.
- The calculated area is approximately 78.53975, computed using the symbolic
constant PI.

Advantages of Using Symbolic Constants

1. Improves Code Readability: By giving meaningful names to constant values, the code
becomes more understandable.
2. Enhances Maintainability: Constants can be easily updated in one place without the
need to modify multiple occurrences in the code.
3. Reduces Errors: The use of final prevents accidental changes to constants, which
can help avoid potential bugs.
4. Provides Consistency: Ensures that the same value is used consistently throughout
the program.

Do It Yourself
1. Define literal and symbolic constants in Java. Provide examples for each.
2. Write a Java program that demonstrates the use of symbolic constants using the
final keyword for a tax rate and computes the tax for a given income.
3. Identify the errors in the following code snippet and explain why they are
incorrect:

final int MAX_SIZE = 10;


MAX_SIZE = 20; // Line A

4. What are the benefits of using symbolic constants over literal constants in a Java
program?
5. Write a program that defines a constant PI using both a literal constant and a
symbolic constant, then calculates the circumference of a circle with a given
radius.
Quiz
1. Which of the following is a literal constant in Java?
A) 10
B) PI
C) final double PI = 3.14;
D) new Integer(10)

Correct Answer: A) 10

2. What will be the output of the following code snippet?

public class Test {


public static void main(String[] args) {
final int MAX_LIMIT = 100;
System.out.println(MAX_LIMIT);
}
}

A) 100
B) MAX_LIMIT
C) 0
D) Compilation error

Correct Answer: A) 100

3. Which of the following is NOT an example of a symbolic constant in Java?


A) final int MAX_SPEED = 120;
B) final double PI = 3.14159;
C) final String GREETING = "Hello!";
D) 120

Correct Answer: D) 120


4. What is the purpose of using symbolic constants in Java?
A) To define variables that can be changed later
B) To avoid magic numbers and make the code more readable
C) To perform implicit casting
D) To create new objects

Correct Answer: B) To avoid magic numbers and make the code more readable

5. What will happen if you try to change the value of a symbolic constant in Java?

public class Test {


public static void main(String[] args) {
final int MAX_USERS = 50;
MAX_USERS = 100; // Line A
System.out.println(MAX_USERS);
}
}

A) The code will compile and print 100


B) The code will compile and print 50
C) The code will not compile and will show an error at Line A
D) The code will result in a runtime error

Correct Answer: C) The code will not compile and will show an error at Line A

4. Formatted Output with printf() Method in


Java

Formatted Output with printf() Method in Java


Definition
The printf() method in Java is used to produce formatted output. It is part of the
java.io.PrintStream class and is similar to the printf function in C and C++. The
printf() method allows you to format strings, numbers, and other data types to present
them in a more readable and structured way.

Using printf(), you can control the width, precision, and alignment of the output, making it
particularly useful for creating tables, reports, or any output where alignment and formatting are
important.

General Syntax

System.out.printf(formatString, arguments...);

- formatString: A format string that specifies how the subsequent arguments should be
formatted.
- arguments...: A comma-separated list of variables or values to be formatted
according to the format string.

Common Format Specifiers


Here are some commonly used format specifiers in printf():

- %d: Decimal integer (base 10)


- %f: Floating-point number
- %c: Character
- %s: String
- %n: Platform-specific line separator
- %x: Hexadecimal integer
- %o: Octal integer
- %b: Boolean
- %e: Scientific notation (e.g., 1.23e+03)

Flags and Width Specifiers:


- -: Left-justifies the output within the specified width.
- +: Displays a plus sign (+) for positive numbers.
- 0: Pads the number with leading zeros.
- .: Specifies the precision for floating-point numbers.

Example Usage of printf() Method


Here is an example demonstrating the use of printf() to format various data types:

public class PrintfExample {


public static void main(String[] args) {
int integerExample = 42;
double doubleExample = 3.14159;
String stringExample = "Java";
char charExample = 'A';
boolean booleanExample = true;

// Using printf() for formatted output


System.out.printf("Integer: %d%n", integerExample);
System.out.printf("Double: %.2f%n", doubleExample); // Formats to 2
decimal places
System.out.printf("String: %s%n", stringExample);
System.out.printf("Character: %c%n", charExample);
System.out.printf("Boolean: %b%n", booleanExample);

// Formatting with width and flags


System.out.printf("Formatted integer with width 5: %5d%n",
integerExample);
System.out.printf("Formatted integer with width 5 and left-
justified: %-5d%n", integerExample);
System.out.printf("Formatted double with width 8 and 3 decimal
places: %8.3f%n", doubleExample);
System.out.printf("Hexadecimal representation of integer: %x%n",
integerExample);
}
}

Explanation of the Output


1. Integer: Displays the integer value 42.
2. Double: Formats the double 3.14159 to two decimal places, resulting in 3.14.

3. String: Displays the string "Java".


4. Character: Displays the character 'A'.
5. Boolean: Displays the boolean value true.
6. Formatted integer with width 5: Right-aligns the integer 42 within a width of 5 spaces.
7. Formatted integer with width 5 and left-justified: Left-aligns the integer 42 within a
width of 5 spaces.
8. Formatted double with width 8 and 3 decimal places: Right-aligns the double
3.14159 within a width of 8 spaces and formats it to three decimal places (3.142).
9. Hexadecimal representation of integer: Converts the integer 42 to its hexadecimal
representation (2a).

Output:

Integer: 42
Double: 3.14
String: Java
Character: A
Boolean: true
Formatted integer with width 5: 42
Formatted integer with width 5 and left-justified: 42
Formatted double with width 8 and 3 decimal places: 3.142
Hexadecimal representation of integer: 2a

Example Program with printf()

Code:

ublic class TableFormatter {


public static void main(String[] args) {
// Headers
System.out.printf("%-10s %-10s %-10s %-10s%n", "Name", "Age", "Height",
Weight");
System.out.printf("%-10s %-10s %-10s %-10s%n", "----------", "----------",
----------", "----------");

// Table Data
System.out.printf("%-10s %-10d %-10.1f %-10.1f%n", "Alice", 25, 5.5, 130.5);
System.out.printf("%-10s %-10d %-10.1f %-10.1f%n", "Bob", 30, 6.0, 180.0);
System.out.printf("%-10s %-10d %-10.1f %-10.1f%n", "Charlie", 22, 5.8, 150.3);
}

Program Analysis:

- The program uses printf() to format and print a table of data.


- %-10s: Left-aligns the string within a 10-character width.
- %-10d: Left-aligns the integer within a 10-character width.
- %-10.1f: Left-aligns the floating-point number within a 10-character width with 1
decimal place.

Output:

Name Age Height Weight


---------- ---------- ---------- ----------
Alice 25 5.5 130.5
Bob 30 6.0 180.0
Charlie 22 5.8 150.3

Do It Yourself
1. Explain how the printf() method works in Java and list three format specifiers
with examples.
2. Write a Java program that takes two integer inputs from the user and prints them
in a formatted table using the printf() method.
3. Identify and correct any errors in the following code snippet:

double price = 19.99;


System.out.printf("The price is %d dollars.\n", price); // Line A

4. How can you control the number of decimal places displayed for a floating-point
number using the printf() method?
5. Write a Java program that uses printf() to display a formatted output for a list
of students' names and their corresponding grades.

Quiz

1. What is the purpose of the printf() method in Java?

A) To read input from the console


B) To write formatted text to the console
C) To print objects to a file
D) To terminate the program

Correct Answer: B) To write formatted text to the console


2. What will be the output of the following code snippet?

int x = 10;
System.out.printf("The value of x is: %d", x);

A) The value of x is: 10


B) The value of x is: x
C) The value of x is: %d
D) Compilation error

Correct Answer: A) The value of x is: 10

3. Which of the following format specifiers is used to print a floating-point


number with two decimal places in Java?
A) %d
B) %f
C) %.2f
D) %2f

Correct Answer: C) %.2f

4. What is the output of the following code snippet?

double value = 123.456789;


System.out.printf("%.3f", value);

A) 123.456789
B) 123.456
C) 123.457
D) 123

Correct Answer: C) 123.457

5. What will be the output of the following code snippet?


String name = "Alice";
int age = 25;
System.out.printf("Name: %s, Age: %d", name, age);

A) Name: Alice, Age: 25


B) Name: Alice Age: 25
C) Name: %s, Age: %d
D) Name: Alice, Age: Alice

Correct Answer: A) Name: Alice, Age: 25

5. Static Variables and Methods

Static Variables and Methods in Java


Static Variables
Definition
Static variables in Java, also known as class variables, are variables that are declared with
the static keyword within a class, but outside of any method, constructor, or block. Static
variables are shared among all instances of a class, meaning that they belong to the class itself
rather than to any particular object created from the class.
Characteristics of Static Variables
- Shared Across Instances: Static variables are shared by all instances of a class. If one
instance changes the value of a static variable, all other instances see the new value.
- Memory Allocation: Static variables are allocated memory only once when the class is
loaded into memory. This can lead to more efficient use of memory for constants or
variables that need to maintain a consistent value across instances.
- Access Without an Object: Static variables can be accessed directly using the class
name, without the need to create an instance of the class.
- Default Values: Like instance variables, static variables also have default values.
Numeric static variables are initialized to 0, boolean static variables are initialized to
false, and object references are initialized to null.
General Syntax

class ClassName {
static dataType variableName;
}

- static: The keyword that makes the variable shared among all instances of the class.
- dataType: The data type of the variable (e.g., int, double, String).
- variableName: The name of the static variable.
Example Usage of Static Variables

public class Counter {


// Static variable
private static int count = 0; // Keeps track of the number of
instances

// Constructor
public Counter() {
count++; // Increment static variable whenever a new instance
is created
}

// Static method to get the value of the static variable


public static int getCount() {
return count;
}

public static void main(String[] args) {


// Creating instances of the Counter class
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Accessing the static variable using the class name


System.out.println("Number of instances created: " +
Counter.getCount());
}
}

Output:
Number of instances created: 3

Explanation:

- Static Variable (count): The variable count is declared as static, meaning it is


shared among all instances of the Counter class.
- Constructor Increment: Every time a new instance of Counter is created, the
constructor increments the static count variable.
- Access via Class Name: The getCount() method is also static and is called
using the class name Counter, showing that three instances were created.

Static Methods
Definition
Static methods in Java are methods that belong to the class rather than any specific instance
of the class. These methods can be called without creating an instance of the class. Static
methods are declared using the static keyword and can only directly access other static
members (both methods and variables).
Characteristics of Static Methods
- Belong to the Class: Static methods are associated with the class itself, not with any
particular object.
- Access Without Object: Static methods can be called using the class name, without
the need for creating an object.
- Cannot Access Instance Variables: Static methods can only access static data
members and other static methods. They cannot directly access instance variables or
methods unless they have an object reference.
- Common Utility Functions: Static methods are often used to implement functions that
perform tasks not dependent on object state, such as mathematical calculations, utility
functions, or factory methods.
General Syntax

class ClassName {
static returnType methodName(parameters) {
// method body
}
}

- static: The keyword that makes the method callable on the class itself, not on
instances.
- returnType: The return type of the method (e.g., void, int, double).
- methodName: The name of the static method.
- parameters: The parameters passed to the method.
Example Usage of Static Methods

public class MathUtility {


// Static method to calculate the square of a number
public static int square(int number) {
return number * number;
}

// Static method to calculate the cube of a number


public static int cube(int number) {
return number * number * number;
}

public static void main(String[] args) {


int number = 5;
// Calling static methods using the class name
System.out.println("Square of " + number + " is: " +
MathUtility.square(number));
System.out.println("Cube of " + number + " is: " +
MathUtility.cube(number));
}
}

Output:
Square of 5 is: 25
Cube of 5 is: 125

Explanation:

- Static Methods (square and cube): Both methods are declared as static,
meaning they can be called without an instance of MathUtility.
- Calculations: The square() method returns the square of a number, and the
cube() method returns the cube.
- Access via Class Name: The static methods are called using the class name
MathUtility, which clearly indicates their static nature.
Example Program with Static Variables and Methods
Code:

public class BankAccount {


private static double interestRate = 3.5; // Static variable
shared among all instances
private double balance; // Instance variable

// Constructor
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}

// Static method to set the interest rate


public static void setInterestRate(double rate) {
interestRate = rate;
}

// Static method to get the interest rate


public static double getInterestRate() {
return interestRate;
}

// Instance method to calculate the interest


public double calculateInterest() {
return balance * (interestRate / 100);
}

public static void main(String[] args) {


// Creating instances of BankAccount
BankAccount account1 = new BankAccount(1000);
BankAccount account2 = new BankAccount(2000);

// Display initial interest rate


System.out.println("Initial Interest Rate: " +
BankAccount.getInterestRate() + "%");

// Calculate interest for both accounts


System.out.println("Interest for account1: " +
account1.calculateInterest());
System.out.println("Interest for account2: " +
account2.calculateInterest());
// Changing the interest rate using static method
BankAccount.setInterestRate(4.0);

// Display updated interest rate


System.out.println("Updated Interest Rate: " +
BankAccount.getInterestRate() + "%");

// Recalculate interest for both accounts with updated rate


System.out.println("Interest for account1 after rate change:
" + account1.calculateInterest());
System.out.println("Interest for account2 after rate change:
" + account2.calculateInterest());
}
}

Program Analysis:

- Static Variable (interestRate): The static variable interestRate is shared


among all instances of BankAccount and is used to calculate interest.
- Static Methods (setInterestRate and getInterestRate): These methods are
used to set and get the interest rate. They can be called without creating an instance of
BankAccount.
- Instance Variable (balance): The balance is an instance variable specific to each
BankAccount object.
- Instance Method (calculateInterest): This method calculates the interest for a
specific BankAccount object using the static interest rate.

Output:

Initial Interest Rate: 3.5%


Interest for account1: 35.0
Interest for account2: 70.0
Updated Interest Rate: 4.0%
Interest for account1 after rate change: 40.0
Interest for account2 after rate change: 80.0

Explanation of the Output:

- Initially, the interest rate is 3.5%, and the interest for account1 and account2 is
calculated based on this rate.
- After changing the interest rate to 4.0% using the static method
setInterestRate(), the new interest for both accounts is calculated using the
updated rate.

Do It Yourself
1. What is the difference between static variables and instance variables in Java?
2. Write a Java program that uses a static method to calculate the factorial of a
number.
3. Identify the errors in the following code snippet and explain the problems

class Example {
static int count = 0;
public void increment() {
count++;
}

public static void main(String[] args) {


Example obj1 = new Example();
Example obj2 = new Example();
obj1.increment();
obj2.increment();
System.out.println(Example.count);
}
}

4. How does the static keyword affect method and variable accessibility in Java?
5. Write a program that uses a static variable to count the number of objects
created for a class.

Quiz

1. Which of the following statements about static variables in Java is true?


A) Static variables are shared among all instances of a class.
B) Static variables can be accessed only by static methods.
C) Static variables are declared using the final keyword.
D) Static variables are instance-specific and not shared.

Correct Answer: A) Static variables are shared among all instances of a class.

2. What will be the output of the following code snippet?

public class Test {


static int count = 0;

public Test() {
count++;
}

public static void main(String[] args) {


Test obj1 = new Test();
Test obj2 = new Test();
Test obj3 = new Test();
System.out.println("Count is: " + count);
}
}

A) Count is: 0
B) Count is: 1
C) Count is: 3
D) Count is: 2

Correct Answer: C) Count is: 3

3. Which of the following code snippets correctly demonstrates the usage of a


static method?
A)

public class Example {


public static void display() {
System.out.println("Static method called.");
}

public static void main(String[] args) {


Example obj = new Example();
obj.display();
}
}

B)

public class Example {


public static void display() {
System.out.println("Static method called.");
}

public static void main(String[] args) {


Example.display();
}
}

C)

public class Example {


public void display() {
System.out.println("Static method called.");
}

public static void main(String[] args) {


Example.display();
}
}

D)

public class Example {


public static void display() {
System.out.println("Static method called.");
}

public static void main(String[] args) {


display();
}
}

Correct Answer: B) and D)

4. What will happen if you try to compile and run the following code snippet?

public class Demo {


static int number = 5;

public static void main(String[] args) {


number++;
System.out.println("Number is: " + number);
}
}

A) The code will compile and print Number is: 5


B) The code will compile and print Number is: 6
C) The code will not compile because static variables cannot be incremented
D) The code will compile but result in a runtime error

Correct Answer: B) The code will compile and print Number is: 6

5. What is the output of the following code snippet?

public class StaticDemo {


static int x = 10;

static void updateX() {


x = 20;
}
public static void main(String[] args) {
System.out.println("Before update: " + x);
updateX();
System.out.println("After update: " + x);
}
}

A) Before update: 10 and After update: 20


B) Before update: 20 and After update: 10
C) Before update: 10 and After update: 10
D) Before update: 20 and After update: 20

Correct Answer: A) Before update: 10 and After update: 20

6. Attribute Final

Final Attribute in Java


Definition
The final attribute in Java is a keyword that can be applied to variables, methods, and
classes. When applied to variables, it makes them constants, meaning their values cannot be
changed once they are initialized. The final keyword is used to create immutable entities
that are constant throughout the execution of a program.

When an attribute (variable) is declared as final, it must be initialized either at the point of
declaration or within a constructor. After the initial assignment, attempting to modify the value of
a final variable will result in a compile-time error.
Characteristics of final Attribute (Variable)
- Immutable Value: A final variable, once initialized, cannot be changed. This makes
it a constant.
- Initialization: A final variable must be initialized when it is declared or in the
constructor if it is an instance variable.
- Compile-Time Constant: If a final variable is declared with a primitive data type and
assigned a constant value, it becomes a compile-time constant.
- Ensures Stability: The use of final ensures that a value is stable and does not
change inadvertently throughout the code, which helps in maintaining consistency and
avoiding errors.
General Syntax

final dataType variableName = value;

- final: Keyword that makes the variable immutable.


- dataType: The data type of the variable (e.g., int, double, String).
- variableName: The name of the final variable.
- value: The initial value assigned to the variable.
Example Usage of final Attribute
Here is an example demonstrating the use of final with different types of variables:

public class FinalExample {


// Final instance variable
final int MAX_ATTEMPTS = 5;

// Final static variable


static final double PI = 3.14159;

public static void main(String[] args) {


// Final local variable
final String GREETING = "Hello, World!";

System.out.println("Maximum Attempts: " + new


FinalExample().MAX_ATTEMPTS);
System.out.println("Value of PI: " + PI);
System.out.println(GREETING);

// Uncommenting any line below will cause a compilation error


// GREETING = "Hi!"; // Error: cannot assign a value to final
variable GREETING
// PI = 3.14; // Error: cannot assign a value to final
variable PI
// new FinalExample().MAX_ATTEMPTS = 10; // Error: cannot
assign a value to final variable MAX_ATTEMPTS
}
}

Output:
Maximum Attempts: 5
Value of PI: 3.14159
Hello, World!

Explanation:

- final Instance Variable (MAX_ATTEMPTS): Declared as final, this instance


variable must be initialized at the point of declaration. Once set to 5, it cannot be
changed.
- final Static Variable (PI): This is a class-level constant that is shared by all
instances of the class. The value 3.14159 is assigned at declaration and cannot be
modified.
- final Local Variable (GREETING): This local variable is declared and initialized
inside the main method. As a final variable, it cannot be reassigned a new value.
Use Cases for final Attribute
1. Constants: The most common use of final is to create constants (like PI or
MAX_ATTEMPTS) that should not change after being initialized.
2. Immutable Fields: Use final to make fields immutable, enhancing the security and
predictability of a class.
3. Design and Safety: When designing libraries or frameworks, final can be used to
protect internal fields from being modified externally.
4. Improved Performance: Since the value of a final variable cannot change, the Java
compiler can make certain optimizations.
Example Program Using final in Different Contexts
Code:

public class BankAccount {


private final String accountNumber; // Final instance variable
private double balance;

// Constructor
public BankAccount(String accountNumber, double initialBalance)
{
this.accountNumber = accountNumber; // Must initialize final
variable in the constructor
this.balance = initialBalance;
}

// Method to get account number


public String getAccountNumber() {
return accountNumber;
}

// Method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

// Method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
}
}

// Method to get balance


public double getBalance() {
return balance;
}

public static void main(String[] args) {


BankAccount account = new BankAccount("123456789", 1000.0);
System.out.println("Account Number: " +
account.getAccountNumber());
System.out.println("Initial Balance: " +
account.getBalance());

account.deposit(500.0);
System.out.println("Balance after deposit: " +
account.getBalance());

account.withdraw(200.0);
System.out.println("Balance after withdrawal: " +
account.getBalance());

// Uncommenting the line below will cause a compilation


error
// account.accountNumber = "987654321"; // Error: cannot
assign a value to final variable accountNumber
}
}
Output:
Account Number: 123456789
Initial Balance: 1000.0
Balance after deposit: 1500.0
Balance after withdrawal: 1300.0

Explanation of the Output:

- final Instance Variable (accountNumber): The account number is set once


during object creation and cannot be changed later, ensuring the integrity of the bank
account information.
- balance: This is a regular instance variable that can be modified, showing the
difference in flexibility between final and non-final variables.
- Error Prevention: Attempting to change accountNumber after initialization would
result in a compilation error, demonstrating the protection provided by final.

Do It Yourself
1. What does it mean for a variable to be declared as final in Java? Give an
example.
2. Write a Java program that demonstrates the use of a final method and a final
variable.
3. Identify and correct any errors in the following code snippet:

class FinalTest {
final int MAX_VALUE;
public FinalTest() {
MAX_VALUE = 100;
}

public void setMaxValue() {


MAX_VALUE = 200; // Line A
}
}

4. Can a final class be subclassed? Provide a rationale for your answer.


5. Write a program that attempts to change a final variable after it has been
initialized and observe the compiler's response.

Quiz

1. What is the primary purpose of using the final keyword with a variable in
Java?
A) To make the variable private
B) To allow the variable to be modified only once
C) To prevent the variable from being reassigned after initialization
D) To make the variable accessible only within its class

Correct Answer: C) To prevent the variable from being reassigned after


initialization

2. What will happen when the following code snippet is executed?

public class TestFinal {


public static void main(String[] args) {
final int x = 10;
x = 20; // Line A
System.out.println(x);
}
}
A) The code will compile and print 20
B) The code will compile and print 10
C) The code will not compile due to a reassignment error at Line A
D) The code will run but throw a runtime exception

Correct Answer: C) The code will not compile due to a reassignment error at Line
A

3. What is the output of the following code snippet?

class Test {
final int number;

Test() {
number = 5;
}

public static void main(String[] args) {


Test obj = new Test();
System.out.println(obj.number);
}
}

A) 0
B) 5
C) Compilation error due to final variable not initialized
D) null

Correct Answer: B) 5

4. Consider the following code snippet. Which statement is true about the code?

public class FinalTest {


final int x;

public FinalTest(int value) {


this.x = value;
}

public void changeX() {


x = 10; // Line A
}

public static void main(String[] args) {


FinalTest obj = new FinalTest(5);
obj.changeX();
}
}

A) The code will print 10


B) The code will not compile due to an error at Line A
C) The code will compile and run successfully
D) The code will throw a runtime exception

Answer: B) The code will not compile due to an error at Line A

5. Which of the following is a correct statement regarding final variables in


Java?
A) A final variable can be initialized multiple times
B) A final variable can be assigned a new value in a subclass
C) A final variable must be initialized either at the time of declaration or inside the
constructor
D) A final variable must be initialized inside a method
Answer: C) A final variable must be initialized either at the time of declaration
or inside the constructor

Assignment
Write aJava program that simulates a user profile management system for a social media platform.
Define variables and print the following
1. username (String):
2. age (int):
3. followers (int):
4. isVerified (boolean):
5. accountBalance (double):
6. gender (char):
7. bio (String): (Short description of the user)
8. posts (String[]): An array containing the user's recent posts.
9.accountCreationTime (long): (in milliseconds)

End of Session - 3

You might also like