Java Module-1
Java Module-1
OOPS FUNDAMENTALS
Introduction: History of Java, Byte code, JVM, Java buzzwords, OOP principles, Data types,
Variables, Scope and life time of variables, Operators, Control statements, Type conversion
and casting, Arrays.
Concepts Of Classes And Objects: Introducing methods, Method overloading,
Constructors, Constructor overloading, Usage of static with data and method, Access control,
this key word, Garbage collection, String class, StringTokenizer.
Introduction:
Java is a powerful, high-level object-oriented programming (OOP) language that is
used for developing wide range of applications, from mobile apps (particularly Android) to
enterprise-level solutions, web applications, and more. Java is known for its simplicity,
scalability, and robustness, making it an ideal choice for beginners and experienced developers
alike.
History of Java:
Java was developed in the mid-1990s by James Gosling and his team at Sun
Microsystems. The language was designed to be small, secure, and portable, and it quickly
became popular among developers for its ease of use and versatility. In 2009, Sun
Microsystems was acquired by Oracle, which has since continued to maintain and develop the
Java platform.
Bytecode in Java
In java when you compile a program, the java compiler(javac) converts/rewrite your
program in another form (.class file) is called as bytecode.
At runtime Java virtual machine(JVM) takes bytecode(.class) as an input and convert
this into machine(windows, linux, macos etc) specific code for further execution.
platform independent because you can run the bytecode generated on one machine on
any other machine without the need of original .java file
Bytecode also makes java secure because it can be run by java virtual machine only.
How does java bytecode works:
The image below shows the execution flow of a program in java.
.
JRE (Java Runtime Environment):
It provides the environment necessary to run Java programs.
JRE contains the JVM (Java Virtual Machine), libraries, and other components needed
to run Java applications.
End-users who only want to run Java applications, not develop them.
JRE = JVM + runtime libraries(contains packages like util, math, lang etc.)+ runtime files
Object:
An object is an instance of a class. It is created using the new keyword and represents
a specific entity with its own state (values of fields) and behaviors (methods).
Encapsulation: Bundling the data (variables) and methods that operate on the data into
a single unit called a class.
Inheritance: A mechanism where one class can inherit fields and methods from another
class, promoting code reuse.
Polymorphism: The ability of different classes to respond to the same method in
different ways, typically through method overriding or overloading.
Abstraction: Hiding the implementation details and showing only the functionality to
the user.
Data types:
Data types in Java define the type of data a variable can store. Each variable in Java must
be declared with a specific data type, which determines the size and format of the data it can
hold.
Example:
int myNum = 5; // Integer (whole number)
2. String
Strings in Java are immutable objects that represent sequences of characters. Even
though they seem like a primitive type, strings are actually objects of the String class.
String greeting = "Hello, World!";
3. Array
Arrays are objects that hold multiple values of the same type in a single variable. Arrays
can store both primitive and reference data types.
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
Type Casting in Java
In Java, type casting is the process of converting a variable from one data type to another.
There are two types of casting:
1. Implicit Casting (Widening): Automatic conversion from a smaller to a larger data type.
int num = 100;
long bigNum = num; // Implicit casting from int to long
2. Explicit Casting (Narrowing): Manual conversion from a larger to a smaller data type.
double decimal = 9.8;
int wholeNumber = (int) decimal; // Explicit casting from double to int
Default Values for Data Types:
When variables are declared but not initialized, Java provides default
values based on their data type. For primitive data types, these default values ensure the
program doesn’t crash due to uninitialized variables.
byte, short, int, long: 0
float, double: 0.0
char: ‘\u0000’
boolean: false
Reference types (like objects and arrays): null
Variable:
A variable is a named memory location which holds some value.
The value stored in a variable can vary during the execution of the program.
Every variable has a data type that defines the kind of data it can store, such as integers,
floating-point numbers, characters, or boolean values.
1. Local Variables
Definition: A local variable is declared within a function or a block of code. It is
accessible only within that specific function or block.
Scope: Limited to the function or block where it is declared.
Lifetime: Exists only while the function or block is executing.
Example:
import java.util.*;
public class FirstProgram {
public static void main(String[] args) {
String name = "Pradeesh"; // Local variable
int age = 22; // Local variable
char initial = 'T'; // Local variable
System.out.println("Name: " + name + ", Age: " + age + ", Initial: " + initial); /strings
}
}
Output: Name: Pradeesh, Age: 22, Initial: T
2. Instance Variables:
Definition: Instance variables are variables declared inside a class but outside any method.
They are specific to an instance of the class (an object). Each object of the class gets its
own copy of the instance variable.
Scope: Available to all methods within the class (once an object is instantiated).
Lifetime: Instance variables exist as long as the object they belong to exists.
Example:
import java.util.*;
public class FirstProgram {
String CR = "Sai Teja"; // Instance variable (not static)
public static void main(String[] args) {
String name = "Pradeesh"; // Local variable
int age = 22; // Local variable
char initial = 'T'; // Local variable
FirstProgram obj = new FirstProgram(); // Create an instance of FirstProgram
System.out.println(obj.CR); // Accessing the instance variable
}
}
Output: Sai Teja
Definition: A class variable is declared with the static keyword. It belongs to the class
itself rather than to instances of the class. Class variables are shared across all instances of
the class.
Scope: Available to all methods and blocks in the class.
Lifetime: Exists for the entire lifetime of the program and is initialized only once,
regardless of how many objects of the class are created.
Example:
import java.util.*;
public class FirstProgram {
static String CR = "Sai Teja"; // Class variable (static variable)
public static void main(String[] args) {
String name = "Pradeesh"; // Local variable
int age = 22; // Local variable
char initial = 'T'; // Local variable
System.out.println(CR); // Accessing class variable
}
}
Output: Sai Teja
Static variable:
A static variable is a class-level variable.
A static variable is declared using the static keyword.
A static variable can be accessed directly by the class name no need to creating an
object of the class.
It is initialized when the class is loaded into memory and remains in memory for the
entire program's lifetime.
Non-Static variable:
A non-static variable is called an instance variable. Each object has its own copy of
these variables.
It is initialized when the object is created and exists as long as the object exists.
A non-static variable can only be accessed through an object of the class.
Differences between Static and Non-Static Variables:
Feature Static Variable Non-Static Variable (Instance
Variable)
Declaration Declared using the static keyword Declared without the static keyword
Memory Shared by all objects; allocated Allocated separately for each object
Allocation once per class
Access Accessed via class name or object Accessed via object reference
Initialization Initialized when class is loaded Initialized when object is created
Lifetime Exists as long as the class is loaded Exists as long as the object exists
in memory
Usage Used for values common to all Used for values specific to each
objects object
Operators in Java:
Operator Operator Description Example Real-Time Example
Type
Arithmetic + (Addition) Adds two int result = Calculating total price:
Operators operands. 5 + 3; totalPrice = itemPrice +
Relational tax;
Operators - (Subtraction) Subtracts the int result = Calculating change:
second operand 5 - 3; change = amountPaid -
from the first. totalPrice;
* Multiplies two int result = Calculating area: area =
(Multiplication) operands. 5 * 3; length * width;
/ (Division) Divides the int result = Computing average:
first operand by 6 / 3; average = totalMarks /
the second. totalSubjects;
% (Modulus) Returns the int result = Checking even/odd: if
remainder of 5 % 3; (num % 2 == 0) (even
division. number check)
== (Equal to) Checks if two if (a == b) Verifying user
operands are credentials: if
equal. (username ==
inputUsername)
!= (Not equal Checks if two if (a != b) Verifying password
to) operands are mismatch: if (password
not equal. != enteredPassword)
> (Greater than) Checks if the if (a > b) Comparing prices: if
left operand is (item1Price >
greater than the item2Price)
right.
< (Less than) Checks if the if (a < b) Age check for
left operand is eligibility: if (age < 18)
less than the
right.
>= (Greater Checks if the if (a >= b) Checking discount
than or equal to) left operand is eligibility: if
greater than or (purchaseAmount >=
equal to the 1000)
right.
<= (Less than or Checks if the if (a <= b) Checking if a student is
equal to) left operand is passing: if (marks <=
less than or passingMarks)
equal to the
right.
Logical && (Logical Returns true if if (a > 0 Verifying eligibility: if
Operators AND) both operands && b < 10) (age >= 18 &&
are true. citizenship == "USA")
|| (logical OR) Returns true if if (a > 0 || b if (isMember ||
any one < 10) isFirstTimeCustomer)
operands are
true.
! (Logical NOT) Reverses the if If the user is not older
logical state of (!(userAge than 65, they may be
its operand. > 65)) eligible to continue
service.
Assignment = (Simple Assigns the int result = Assigning a value: int
Operators assignment) right operand's 5; age = 25;
value to the left
operand.
+= (Add and Adds the right a += 5; Increasing count:
assign) operand to the (equivalent totalSales += newSales;
left operand to a = a + 5)
and assigns the
result.
-= (Subtract and Subtracts the a -= 3; Reducing balance:
assign) right operand (equivalent balance -=
from the left to a = a - 3) withdrawalAmount;
operand and
assigns the
result.
*= (Multiply Multiplies the a *= 2; Doubling value: price
and assign) left operand by (equivalent *= discountFactor;
the right to a = a * 2)
operand and
assigns the
result.
/= (Divide and Divides the left a /= 2; Dividing profit: profit
assign) operand by the (equivalent /= numberOfShares;
right operand to a = a / 2)
and assigns the
result.
Unary ++ (Increment) Increases the a++; (or Increasing stock:
Operators value of the ++a) itemsInStock++;
operand by 1.
-- (Decrement) Decreases the a--; (or --a) Decreasing score:
value of the playerScore--;
operand by 1.
Bitwise & (AND) Bitwise AND 12 & 10 = 8 1100 & 1010 = 1000
Operators ^ (XOR) Bitwise XOR 12 ^ 10 = 6 1100 ^ 1010 = 0110
|(OR) Bitwise OR 12 | 10 = 14 1100 | 1010 = 1110
~ (NOT) Bitwise NOT ~12 = -13 ~1100 = -1101
<< (left shift) Bitwise left 12 << 2 =
1100 << 2 =110000
shift 48
>> (Right shift) Bitwise Right
12 >> 2 = 3 1100 >> 2 = 0011
shift
Ternary ?: A shorthand for int result = Determining maximum:
Operator if-else (a > b) ? a : int max = (a > b) ? a : b;
statement. b; // Using the ternary
Evaluates a operator to determine
condition and the maximum of a and b
returns one of
two values.
Instanceof instanceof Checks whether if (obj Type checking: if (x
Operator an object is an instanceof instanceof Car)
instance of a String)
particular class
or interface.
Example:
Write a Java program that calculates a student's grade using all major Java operators
(Arithmetic, Relational, Logical, Assignment, Unary, Bitwise, Ternary, and Instanceof):
import java.util.*;
public class StudentGrade {
// Instance variables for student marks
int marks1 = 80, marks2 = 90, marks3 = 85;
static int totalMarksPossible = 300; // Total possible marks
public static void main(String[] args) {
StudentGrade student = new StudentGrade(); // Creating an object of the class
// 1. Arithmetic Operators: Calculate total marks and average
int totalMarks = student.marks1 + student.marks2 + student.marks3; // Adding marks
double averageMarks = totalMarks / 3.0; // Division to get average
Explanation:
Arithmetic Operators: Used for calculating the total marks and average.
Relational Operators: Used to check if the student has passed based on the average
marks.
Logical Operators: Used to check if the student is eligible for a scholarship.
Assignment Operators: Used to update the marks when bonus marks are added.
Unary Operators: Used to increment marks (for example, when adding bonus
points).
Bitwise Operators: Used to check if the marks are even (used in some applications
for bit-level operations).
Ternary Operator: Used to assign grades based on the average marks.
Instanceof Operator: Used to check the type of the object.
Control Statements:
Control Description Real-Time Example Code
Statement Example
if Executes a Login if (username.equals("admin") &&
block of code if Authentication: password.equals("1234")) {
the specified Checking if a user System.out.println("Login
condition is enters the correct Sucessfully"); }
true. username and
password.
if-else Executes one Eligibility Check: if (age >= 18) {
block of code if Checking if a System.out.println("Eligible to
the condition is person is eligible to vote"); } else {
true, and vote based on age. System.out.println("Not eligible to
another block if vote"); }
it is false.
else-if Checks multiple Grading System: if (marks >= 90) { grade = "A"; }
conditions, Assigning grades else if (marks >= 70) { grade = "B";
executing the based on a student's } else { grade = "C"; }
first true marks.
condition's
block of code.
switch Executes one Day of the Week: switch (day) { case 1:
out of many Displaying the System.out.println("Monday");
blocks of code name of the day break; case 2:
based on the based on an integer System.out.println("Tuesday");
value of a input. break; default:
variable. System.out.println("Invalid day"); }
while Repeats a block Counting: while (count > 0) {
of code while Counting down System.out.println(count); count--; }
the condition is from a given
true. number until it
reaches zero.
do-while Executes a Menu System: do { System.out.println("Menu: 1.
block of code at Displaying a menu Option A 2. Option B 3. Exit");
least once and until the user choice = sc.nextInt(); } while
then repeats it chooses to exit. (choice != 3);
as long as the
condition is
true.
for Loops through a Summing for (int i = 1; i <= 10; i++) { sum +=
block of code a Numbers: Adding i; }
specified the first n natural
number of numbers.
times.
break Exits the loop or Search in List: for (int i = 0; i < list.length; i++) { if
switch Exiting the loop (list[i] == target) { break; } }
statement once the target item
immediately. is found.
continue Skips the Skipping Negative for (int i = 0; i < numbers.length;
current iteration Numbers: i++) { if (numbers[i] < 0) continue;
of the loop and Skipping negative sum += numbers[i]; }
proceeds to the numbers while
next iteration. summing a list of
integers.
if Statement
The if statement is used to execute a block of code only if a specific condition is true.
Syntax:
if (condition) {
// code block to be executed if condition is true
}
Example:
Login Authentication: Checking if the user enters the correct username and
password.
Simple Program:
import java.util.Scanner;
public class LoginExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Username:");
String username = sc.nextLine();
System.out.println("Enter Password:");
String password = sc.nextLine();
// If statement checking login credentials
if (username.equals("admin") && password.equals("1234")) {
System.out.println("Login Successful!");
}
}
}
Output:
Enter Username:
admin
Enter Password:
1234
Login Successful!
2. if-else Statement
The if-else statement allows you to execute one block of code if a condition is true
and another block if the condition is false.
Syntax:
if (condition) {
// code block to be executed if condition is true
} else {
// code block to be executed if condition is false
}
Example:
Eligibility to Vote: Check if a person is eligible to vote based on their age.
Simple Program:
import java.util.Scanner;
public class VotingEligibility {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
// If-else statement checking voting eligibility
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Output:
Enter your age:
20
You are eligible to vote.
3. else-if Ladder
The else-if ladder allows you to check multiple conditions. It’s useful when you need
to check several different conditions.
Syntax:
if (condition1) {
// code block if condition1 is true
} else if (condition2) {
// code block if condition2 is true
} else {
// code block if all conditions are false
}
Example:
Student Grading System: Assign a grade based on the student's marks.
Simple Program:
import java.util.Scanner;
public class GradingSystem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks (0-100):");
int marks = sc.nextInt();
String grade;
// Else-if ladder to assign grades
if (marks >= 90) {
grade = "A";
} else if (marks >= 75) {
grade = "B";
} else if (marks >= 50) {
grade = "C";
} else {
grade = "D";
}
System.out.println("Your grade is: " + grade);
}
}
Output:
Enter marks (0-100):
65
Your grade is: C
4. switch Statement
The switch statement is used when there are multiple possible conditions. It works by
comparing a variable’s value to a series of case values. It's often used when there are multiple
possible values to check for.
Syntax:
switch (expression) {
case value1:
// code block if expression equals value1
break;
case value2:
// code block if expression equals value2
break;
// more cases as needed
default:
// code block if expression does not match any case
}
Rules:
Expression in a switch must be a variable of a primitive type, String, or enum.
Case labels must be constants, and they cannot be duplicated.
break is used to prevent fall-through.
The default case is optional but recommended for handling unexpected values.
Example:
Day of the Week: Display the day name based on the number (1 for Monday, 2 for Tuesday,
etc.).
Simple Program:
import java.util.Scanner;
public class DayOfWeek {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number (1-7):");
int day = sc.nextInt();
While Loop
The while loop is used to execute a block of code repeatedly as long as the condition
evaluates to true.
Syntax:
while (condition) {
// Code to be executed as long as condition is true
}
Rules:
The condition is checked before entering the loop.
If the condition is false initially, the loop will not execute.
Example:
public class WhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) { // Condition is true as long as i <= 5
System.out.println(i);
i++; // Increment the counter
}
}
}
Output:
1
2
3
4
5
do-while Loop
The do-while loop is similar to the while loop, but the condition is checked after the
loop is executed. This ensures that the loop will run at least once.
Syntax:
do {
// Code to be executed
} while (condition);
Rules:
The block of code inside the do will always execute at least once, even if the
condition is false initially.
After the first execution, the condition is checked.
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++; // Increment the counter
} while (i <= 5);
}
}
Output:
1
2
3
4
5
for Loop
The for loop is used when the number of iterations is known beforehand. It’s a more
compact way to write loops that have a counter.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
Rules:
Initialization: A counter variable is initialized.
Condition: The loop runs as long as this condition is true.
Update: The counter is updated after each iteration (usually incremented or
decremented).
Example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
4. break Statement
The break statement is used to exit a loop or switch statement prematurely, even if the
condition hasn’t been met.
Syntax:
// Inside any loop or switch
break;
Rules:
The break statement immediately exits the loop or switch.
It is often used to terminate loops when a certain condition is met.
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Breaks the loop when i is 6
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
5. continue Statement
The continue statement skips the current iteration of a loop and moves directly to the
next iteration.
Syntax:
// Inside any loop
continue;
Rules:
The continue statement only affects the current iteration of the loop.
It is useful when you want to skip certain parts of the loop based on a condition.
Example:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the iteration when i is 3
}
System.out.println(i);
}
}
}
Output:
1
2
4
5
These control statements are crucial for implementing logic that requires repeating tasks or
Array:
An array in Java is a data structure that allows you to store multiple values of the same
datatype in a single variable. Arrays are useful for managing collections of data efficiently.
They are index-based, meaning each element in the array can be accessed using its index,
starting from 0.
Key points about arrays:
Arrays are zero-indexed (i.e., the first element is at index 0).
The size of an array is fixed once it is created and cannot be changed.
Arrays can hold primitive types or objects.
1. Declaration an array
To declare an array in Java, you specify the data type followed by square brackets.
Syntax:
datatype[] arrayName;
Example:
int[] numbers; // Declaring an integer array
2. Creating an Array:
After declaring an array, you need to allocate memory to the array with the new keyword.
Syntax:
datatype[] arrayName= new int[5];
Example:
numbers = new int[5]; // Creating an array of 5 integers
3. Initialization of an Array:
Array Operations:
1. Accessing Array Elements:
We can access array elements using their indices (starting from 0).
int firstElement = arr[0]; // Accessing the first element
int secondElement = arr[1]; // Accessing the second element
2. Modifying Array Elements
We can modify array elements by assigning a new value to a specific index.
arr[0] = 100; // Change the first element to 100
arr[4] = 500; // Change the fifth element to 500
3. Array Length
We can get the size of an array using the length property.
int arraySize = arr.length; // Returns the number of elements in the array
4. Iterating Over an Array (Looping)
(i) Using a for Loop to store each element to an array variable:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt(); // Store each input in the array
}
(ii) Using a for Loop to Print each element:
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); // Print each element
}
Using an Enhanced for Loop (For-each loop):
for (int num : arr) {
System.out.println(num); // Prints each element of the array
}
6. Searching for an Element in an Array
We can perform a linear search by iterating over the array to find the index and element.
System.out.print("Enter the element to search: ");
int target = scanner.nextInt(); // Read the element to search //
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
System.out.println("Element " + target + " found at index " + i);
break; // Exit the loop once the element is found
}
}
7. Sorting an Array
We can sort an array using the Arrays.sort() method from java.util.Arrays.
import java.util.Arrays;
Arrays.sort(arr); // Sorts the array in ascending order
Arrays.sort(arrDesc, Collections.reverseOrder());
2. Two-Dimensional Array
A two-dimensional array is an array of arrays. It is essentially a table with rows and
columns, where each element is accessed using two indices (row and column).
Key point:
An array of arrays, commonly used to represent matrices or grids.
Elements are accessed using two indices (row and column).
Syntax:
datatype[][] arrayName = new datatype[rows][columns];
or, you can initialize it with values directly:
datatype[][] arrayName = {{value1, value2}, {value3, value4}, ...};
Example:
Two Dimensional array is declared and initialized in Java:
int[][] arr = new int[3][4]; // 3 rows, 4 columns
Or you can initialize it with values directly:
int[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Example:
public class MethodExample {
// A simple method that returns the sum of two numbers
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 10);
System.out.println("Sum: " + result); // Output: Sum: 15
}
}
2. Method Overloading
Method overloading is the concept of defining multiple methods with the same name
but with different parameter lists (either in the number or type of parameters).
Syntax:
returnType methodName(parameter1, parameter2, ...) {
// Code
}
returnType methodName(parameter1, parameter2, ...) {
// Code
}
3. Constructors in Java
A constructor is a special method used to initialize objects. It is called automatically
when an object is created. Constructors do not have a return type and must have the same
name as the class.
Syntax:
class ClassName {
// Constructor
public ClassName() {
// Initialization code
}
}
Example:
public class Student {
int marks; // Instance variable to store marks
String name; // Instance variable to store name
// Constructor for the Student class
Student() {
System.out.println("Hello"); // Print "Hello" when an object is created
}
public static void main(String[] args) {
// Create two objects of the Student class
Student ob1 = new Student(); // Create first student object
Student ob2 = new Student(); // Create second student object
// Print the marks for both student objects (default value of marks is 0)
System.out.println(ob1.marks); // Output: 0 (default value of int)
System.out.println(ob2.marks); // Output: 0 (default value of int)
}
}
Output:
Hello
Hello
0
0
Constructor Overloading
Constructor overloading is the concept of defining multiple constructors with the
same name (the class name) but with different parameter lists.
Example:
public class Student {
int marks; // Instance variable to store marks
String name; // Instance variable to store name
// Empty constructor
Student() {
System.out.println("Empty Constructor");
}
Example 2:
public class Student {
int marks; // Instance variable for marks
String name; // Instance variable for name
Example:
class Student {
int mark = 80; // Instance variable for marks (each student has their own marks)
static String teacher = "Praveen"; // Static variable (shared by all students)
Example 2:
public class BankAccount {
// Private variable (cannot be accessed directly from outside the class)
private double balance;
7. this Keyword
The this keyword refers to the current instance of the class. It is often used to
distinguish between instance variables and parameters with the same name.
Example:
public class ThisKeywordExample {
int num;
public void setNum(int num) {
this.num = num; // 'this' differentiates between instance variable and parameter
}
public void display() {
System.out.println("Value: " + num);
}
public static void main(String[] args) {
ThisKeywordExample obj = new ThisKeywordExample();
obj.setNum(100);
obj.display(); // Output: Value: 100
}
}
StringTokenizer in Java
The StringTokenizer class is used to break a string into tokens (substrings). It helps in
parsing a string based on delimiters (such as spaces or commas).
Example:
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String str = "Java is fun";
StringTokenizer tokenizer = new StringTokenizer(str);
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Output:
Java
is
fun
Summary Table:
Topic Description
Methods Blocks of code to perform specific tasks.
Method Overloading Same method name with different parameters.
Constructors Special methods used to initialize objects.
Constructor Multiple constructors with different parameters.
Overloading
Static Class-level data and methods, shared across instances.
Access Control Modifiers (public, private, protected, default) to control
visibility.
this Keyword Refers to the current instance of the class.
Garbage Collection Automatic memory management that frees unused objects.
String Class Immutable sequence of characters.
StringTokenizer Breaks a string into tokens using specified delimiters.
These are the basic definitions, syntax, and examples to help you understand each c