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

Java Module-1

The document provides an overview of Java programming, covering its history, key features, and fundamental concepts of object-oriented programming (OOP). It explains Java's architecture, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with data types, variables, and type casting. Additionally, it highlights OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, while also detailing the syntax for declaring classes and objects.

Uploaded by

p38981094
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Module-1

The document provides an overview of Java programming, covering its history, key features, and fundamental concepts of object-oriented programming (OOP). It explains Java's architecture, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with data types, variables, and type casting. Additionally, it highlights OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, while also detailing the syntax for declaring classes and objects.

Uploaded by

p38981094
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

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.

Key Features of Java:


 Object-oriented programming
 Platform independence
 Simple and easy to learn
 Automatic Memory Management
 Multithread Support
 Security
 Rich Standard Library (API)
 High Performance
 Exception Handling
 Distributed Computing Support
 Object-Oriented Programming
Java supports all core OOP principles: Encapsulation, Inheritance, Polymorphism, and
Abstraction.
 Platform Independence
Java is platform-independent (Write Once, Run Anywhere), as compiled code runs on
any device with a JVM.
 Simple and Easy to Learn
Java has a simple syntax, derived from C, and is easy to understand for new developers.
 Automatic Memory Management (Garbage Collection)
Java automatically manages memory, freeing up unused objects through garbage
collection.
 Multithreading Support
Java has built-in support for multithreading, allowing simultaneous execution of
multiple tasks.
 Security
Java has a robust security model with features like bytecode verification and
sandboxing.
 Rich Standard Library (API)
Java includes a vast collection of built-in libraries for tasks like I/O, networking, and
database access.
 High Performance
Java uses Just-In-Time (JIT) compilation for faster execution of bytecode.
 Exception Handling
Java provides a powerful exception-handling mechanism to deal with runtime errors.
 Distributed Computing Support
Java supports network-based applications using APIs like RMI and JNDI for building
distributed systems.

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.

 In java a program(.java file) is compiled first using java compiler(javac).


 After successful compilation the bytecode(.class file) the java virtual
machine(JVM) loads the .class file inside memory and then converts(by java
interpreter) the instructions of .class file into machine executable code.
 The .class files are usually smaller in size than source code that means it also gets
compressed.
 As bytecode doesn't allow any external editing, it's also secure to transport them over
the network.
Java Programming Terminology:
Let’s try to understand the various terms frequently used in Java and how the code in Java is
executed. The flow chart given below shows how a Java program is executed.

Components of Java Architecture:


Java architecture comprises three main components:
 Java Development Kit (JDK)
 Java Runtime Environment (JRE)
 Java Virtual Machine (JVM)

JDK (Java Development Kit):


 It is a software development kit used to develop Java applications.
 JDK contains both JRE (Java Runtime Environment) and development tools like
compilers (javac) and debuggers.
 Java developers who need to write, compile, and debug Java programs.
JDK = JRE + Development tools(eg. javac, javap, java, javadoc etc)
 There are many popular IDEs for Java development, including Eclipse and IntelliJ
IDEA.

.
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

JVM (Java Virtual Machine):


 It is a virtual machine that runs Java bytecode, converting it into machine code for
execution on a specific platform.
 The JVM is part of the JRE and is responsible for interpreting or just-in-time compiling
the bytecode into native code.
 Both developers and users, as it allows Java programs to be platform-independent.
Functions of JVM:
 It converts the required part if the bytecode into its equivalent executable code.
 It loads the executable code into the RAM.
 Executes this code through the local operating system.
 Deletes the executable code from the RAM.
Java Buzzwords:
Java has several defining features often referred to as "buzzwords." These emphasize its key
principles:
 Simple: Java was designed to be easy to use and accessible for programmers.
 Object-Oriented: Java is based on the principles of Object-Oriented Programming
(OOP), focusing on the manipulation of objects.
 Distributed: Java provides powerful libraries for distributed computing.
 Secure: Java includes strong security features like bytecode verification and
sandboxing.
 Portable: Java code can run on any platform with a JVM.
 Robust: Java has strong error handling and memory management, making programs
more reliable.
 Multithreaded: Java supports multithreading for concurrent tasks.
 Interpreted: Bytecode is interpreted by the JVM at runtime.
 High-performance: Java’s bytecode can be optimized at runtime for better
performance.
 Dynamic: Java can adapt to changes at runtime.

4. Object-Oriented Programming (OOP) Principles


In OOP, the focus is on how data is organized and how it interacts with methods
(functions that manipulate data), making programs more flexible, reusable, and maintainable.
Core Concepts of OOP:
Class:
A class is a blueprint or template for creating objects. It defines properties (fields) and
behaviors (methods) that the objects created from the class will have.
The basic syntax of declaring a class is
class ClassName {
dataType fieldName; // Fields (properties or attributes of the class)
}
returnType methodName(parameters) {// Methods (behaviors or actions of the class)
// Method body
}
}
Example:

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

The basic syntax for creating an object:


ClassName objectName = new ClassName(arguments);

Example program for understanding class, object and method:


import java.util.*;
public class Car {
String brand; // Instance variables
int year;
public void display() {// Method to display car details
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
Car car1 = new Car();// Creating an object of the Car class
car1.brand = "Toyota";// Assigning values to the object properties
car1.year = 2020;
car1.display();// Calling the method on the object
}
}
Output:
Brand: Toyota
Year: 2020

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

float myFloatNum = 5.99f; // Floating point number

char myLetter = 'D'; // Character

boolean myBool = true; // Boolean

String myText = "Hello"; // String

Java’s data types are categorized into two main groups:


1. Primitive Data Types: These are the basic types built into the language and include
integers, floating-point numbers, characters, and boolean values.
2. Reference Data Types: These types refer to objects and are created from classes. They
store references (or memory addresses) to actual data rather than the data itself.
Primitive Data Types in Java:
Java defines eight primitive data types, which are classified into four
categories: integer types, floating-point types, character type, and boolean type. These
types are built into the Java language and offer a way to handle basic data values.
1. Integer Data Types
The integer types in Java are used to store whole numbers, both positive and negative.
There are four integer types, each differing in the amount of memory it occupies and the range
of values it can hold.
a) byte
Suitable for saving memory in large arrays and for environments where memory
efficiency is crucial.
Example:
byte smallNumber = 100;
b) short
Often used in resource-constrained systems or when memory optimization is critical.
Example:
short mediumNumber = 30000;
c) int
This is the most commonly used data type for storing whole numbers.
Example:
int number = 150000;
d) long
Use long when int is not sufficient for storing very large numbers. Note: In
the long data type, the suffix L or l must be used to differentiate it from an integer literal.
Example:
long largeNumber = 15000000000L;
2. Floating-Point Data Types
Floating-point types are used to store numbers with decimal points. Java provides two
types of floating-point data types:
a) float
Used when fractional precision is needed, but with limited memory requirements. Note:
The suffix F or f is mandatory for float literals to avoid confusion with double literals.
Example:
float price = 19.99f;
b) double
Used for more precise fractional numbers, preferred when higher accuracy is required.
Example:
double preciseValue = 19.999999999;
3. Character Data Type
char
Used for storing a single character or Unicode symbol.
Example:
char letter = 'A';
4. Boolean Data Type
boolean
Used for simple true/false conditions, such as flags or logical operators.
Example:
boolean isJavaFun = true;
Primitive Data Type Summary Table
Data Size Default Range Example
Type Value
byte 1 byte 0 -128 to 127 byte b = 10;
short 2 bytes 0 -32,768 to 32,767 short s = 1000;
int 4 bytes 0 -2^31 to 2^31-1 int i = 100000;
long 8 bytes 0L -2^63 to 2^63-1 long l =
123456789L;
float 4 bytes 0.0f ±3.40282347E+38F float f = 3.14f;
double 8 bytes 0.0d ±1.79769313486231570E+308 double d = 3.14159;
char 2 bytes ‘\u0000’ 0 to 65,535 (Unicode chars) char c = 'A';
boolean 1 bit false true/false boolean b = true;

Reference Data Types in Java:


Reference data types store references (memory addresses) to objects or arrays instead
of actual values. They include:
 Objects
 Strings
 Arrays
1. Object
Objects in Java are instances of classes. When you create an object, you allocate
memory for it and create a reference to that memory. Objects can store complex data and are
used to model real-world entities.
class Dog {
String name;
int age;
}
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 5;

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.

Declaring Variables in Java:


To declare a variable you specify the data type followed by the variable name.
Example:
int a;
In this example, we’ve declared a variable named “a” of type integer (int).
Initializing Variables:
Initialization is the process of assigning a value to a variable
Example:
int a = 10;

Scope and life time of variables:


Scope and lifetime of variables refer to where and how long a variable can be accessed
during the execution of a program.
 Scope refers to where a variable can be accessed in the code (local, instance, or
static).
 Lifetime refers to how long a variable exists in memory during the execution of the
program (local, instance, or static).
Types of Variables in Java:

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

3. Class Variable (Static Variable)

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

Example program for understanding static and Non static variables:


import java.util.*;
public class School {
static String name = "St. Antony's HSS"; // Static variable
static int streetNo = 123; // Static variable
String teachername; // Instance variable
int standard; // Instance variable
public static void main(String[] args) {
School teacher1 = new School();// Creating objects of the School class
teacher1.teachername = "Raja"; // Assigning teacher name to teacher1
teacher1.standard = 8; // Assigning standard to teacher1
School teacher2 = new School();
teacher2.teachername = "Kumari"; // Assigning teacher name to teacher2
teacher2.standard = 10; // Assigning standard to teacher2
System.out.println(name); // Accessing static variable name
System.out.println(streetNo); // Accessing static variable streetNo
System.out.println(teacher1.teachername); // Accessing teachername of teacher1
System.out.println(teacher1.standard); // Accessing standard of teacher1
}
}
Output:
St. Antony's HSS
123
Raja
8
Kumari
10

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

System.out.println("Total Marks: " + totalMarks);


System.out.println("Average Marks: " + averageMarks);

// 2. Relational Operators: Checking if the student has passed


boolean hasPassed = averageMarks >= 50; // Greater than or equal to operator
System.out.println("Has Passed: " + hasPassed);

// 3. Logical Operators: Checking if the student is eligible for a scholarship


boolean isEligibleForScholarship = (averageMarks > 85) || (totalMarks > 250);
System.out.println("Eligible for Scholarship: " + isEligibleForScholarship);

// 4. Assignment Operators: Updating marks


student.marks1 += 5; // Adding 5 marks to marks1
System.out.println("Updated Marks1: " + student.marks1);
// 5. Unary Operators: Incrementing marks for bonus
student.marks2++; // Increment marks2 by 1
System.out.println("Incremented Marks2: " + student.marks2);

// 6. Bitwise Operators: Checking if marks1 is even


boolean isMarks1Even = (student.marks1 & 1) == 0;
System.out.println("Marks1 is even: " + isMarks1Even);

// 7. Ternary Operator: Determine the grade based on average marks


String grade = (averageMarks >= 90) ? "A" : (averageMarks >= 75) ? "B" : "C";
System.out.println("Grade: " + grade);

// 8. Instanceof Operator: Checking the type of the object


boolean isStudent = student instanceof StudentGrade;
System.out.println("Is the object an instance of StudentGrade? " + isStudent);

// 9. Relational Operators (continued): Compare marks for two students


int student2Marks = 90;
System.out.println("Marks1 and Marks2 are equal: " + (student.marks1 ==
student2Marks)); // Equal to operator
}
}
Output:
Total Marks: 255
Average Marks: 85.0
Has Passed: true
Eligible for Scholarship: true
Updated Marks1: 85
Incremented Marks2: 91
Marks1 is even: false
Grade: B
Is the object an instance of StudentGrade? true
Marks1 and Marks2 are equal: false

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

// Switch statement for days of the week


switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day number!");
}
}
}
Output:
Enter a number (1-7):
7
Sunday
Enter a number (1-7):
10
Invalid day number!

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

Summary of Control Statements:

Statement Definition Key Points


while Repeats code as long as the condition Condition checked before execution
is true
do-while Similar to while but checks the Always executes at least once
condition after execution
for Used when the number of iterations is Contains initialization, condition, and
known beforehand update in one line
break Exits the loop or switch statement Exits the innermost loop or switch
prematurely
continue Skips the current iteration of a loop Moves to the next iteration of the
loop

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:

Alternatively, you can declare and initialize an array in one line:


Syntax:
datatype[] arrayName= {value1,value2, value3…valuen};
Example:
int[] numbers = {10, 20, 30, 40, 50}; // Initializing an array with values

Example: Array Declaration, Creation, and Initialization


import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
// Declaration and Initialization of an Array
int[] arr = {10, 20, 30, 40, 50};

// Accessing elements of the array


System.out.println("First element: " + arr[0]); // Output: 10
System.out.println("Second element: " + arr[1]); // Output: 20

// Loop through the array


System.out.println("Array elements:");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output:
First element: 10
Second element: 20
Array elements:
10
20
30
40
50

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

Example Program Using Multiple Array Operations


import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
System.out.println("First Element: " + arr[0]);
arr[2] = 100;
System.out.println("Modified Third Element: " + arr[2]);
System.out.println("Array Length: " + arr.length); // Array Length
Arrays.sort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr)); // Sorting the array
int target = 40; // Searching for an element
if (arr[]==target) {
System.out.println("Element " + target + " found ");
} else {
System.out.println("Element not found");
}
}
}
Output:
First Element: 10
Modified Third Element: 100
Array Length: 5
Sorted Array: [10, 20, 30, 40, 50]
Element 40 found

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}
};

public class TwoDimensionalArray {


public static void main(String[] args) {
int[][] matrix = { // Declaration and initialization
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing and printing elements
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
123
456
789

Introducing Methods in Java


A method is a block of code that performs a specific task. It is used to define the
behavior of an object or class. Methods can take parameters and return values.
Syntax:
returnType methodName(parameter1, parameter2, ...) {
// Code to execute
}

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
}

Example: Instance method approach


public class MethodOverloadingExample {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
MethodOverloadingExample example = new MethodOverloadingExample();
System.out.println(example.add(5, 10)); // Output: 15
System.out.println(example.add(5, 10, 15)); // Output: 30
}
}
Output:
15
30

Example 2 Static method approach


public class MethodOverloadingExample {
// Static method to add two integers (void return type)
static void add(int a, int b) {
System.out.println(a + b); // Print the sum of the integers
}
// Static method to add two doubles (void return type)
static void add(double a, double b) {
System.out.println(a + b); // Print the sum of the doubles
}
public static void main(String[] args) {
// Call the add method with integer arguments
add(5, 10); // Output: 15
// Call the add method with double arguments
add(5.5, 10.5); // Output: 16.0
}
}
Output:
15
16.0

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");
}

// Constructor with an integer parameter


Student(int a) {
System.out.println(a); // Print the passed argument
System.out.println("Hello"); // Print "Hello"
}

public static void main(String[] args) {


// Create Student objects using different constructors
Student ob1 = new Student(10); // Calls the constructor with an int argument
Student ob2 = new Student(); // Calls the empty constructor
}
}
Output:
10
Hello
Empty Constructor

Example 2:
public class Student {
int marks; // Instance variable for marks
String name; // Instance variable for name

// Constructor to initialize marks and name


Student(int a, String b) {
marks = a; // Initialize marks with the passed value 'a'
name = b; // Initialize name with the passed value 'b'

// Print the values of marks and name inside the constructor


System.out.println("Marks: " + marks);
System.out.println("Name: " + name);
}

public static void main(String[] args) {


// Create an object of Student class and pass 32 for marks and "John" for name
Student ob1 = new Student(32, "John");
}
}
Output:
Marks: 32
Name: John

Usage of static with Data and Methods:


The static keyword is used to define class-level variables and methods that can be
accessed without creating an instance of the class.
Syntax:
class ClassName {
static int variable; // Static variable

static void method() { // Static method


// Code
}
}

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)

// Static method: It can be called without an object


static void disp() {
System.out.println("Teacher's name: " + teacher);
}

// Instance method: Can access instance variables (like 'mark')


void displayMarks() {
System.out.println("Student's marks: " + mark);
}
}

public class MainClass {


public static void main(String[] args) {
// Create two Student objects
Student student1 = new Student();
Student student2 = new Student();

// Calling the static method directly using the class name


Student.disp(); // Output: Teacher's name: Praveen

// Calling instance methods for both students


student1.displayMarks(); // Output: Student's marks: 80
student2.displayMarks(); // Output: Student's marks: 80

// Changing marks for student1


student1.mark = 90;
student1.displayMarks(); // Output: Student's marks: 90
student2.displayMarks(); // Output: Student's marks: 80 (student2's mark is still 80)

// Changing the static teacher name, which affects all students


Student.teacher = "Ravi"; // Static variable is changed for all students
student1.disp(); // Output: Teacher's name: Ravi
student2.disp(); // Output: Teacher's name: Ravi
}
}
Output:
Teacher's name: Praveen
Student's marks: 80
Student's marks: 80
Student's marks: 90
Student's marks: 80
Teacher's name: Ravi
Teacher's name: Ravi

Access Control in Java


Access control determines the visibility and accessibility of classes, methods, and
variables in Java. It is implemented using access modifiers: public, private, protected, and
default (no modifier).
Example 1:
public class AccessControlExample {
private int num; // Private variable
public String name; // Public variable
public void setNum(int num) {
this.num = num; // Accessing private variable within the class
}
public int getNum() {
return num; // Accessing private variable within the class
}
}

Example 2:
public class BankAccount {
// Private variable (cannot be accessed directly from outside the class)
private double balance;

// Public variable (can be accessed directly from outside the class)


public String accountHolderName;

// Constructor to initialize the account holder's name and initial balance


public BankAccount(String name, double initialBalance) {
this.accountHolderName = name;
this.balance = initialBalance;
}

// Public method to deposit money into the account


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited. New balance: " + balance);
} else {
System.out.println("Deposit amount must be positive.");
}
}

// Public method to withdraw money from the account


public void withdraw(double amount) {
if (amount <= balance && amount > 0) {
balance -= amount;
System.out.println(amount + " withdrawn. New balance: " + balance);
} else {
System.out.println("Invalid withdrawal amount.");
}
}

// Getter method for the balance (private variable)


public double getBalance() {
return balance;
}

// Setter method for the balance (if needed to modify balance)


public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
} else {
System.out.println("Balance cannot be negative.");
}
}

public static void main(String[] args) {


// Create a bank account object
BankAccount account1 = new BankAccount("John Doe", 1000.0);

// Access the public variable directly


System.out.println("Account Holder: " + account1.accountHolderName);

// Access private variable through getter method


System.out.println("Initial Balance: " + account1.getBalance());

// Perform deposit and withdrawal


account1.deposit(500.0);
account1.withdraw(200.0);

// Access updated balance through getter method


System.out.println("Updated Balance: " + account1.getBalance());

// Attempt to set an invalid balance using setter


account1.setBalance(-500.0); // This should not work
System.out.println("Balance after invalid set: " + account1.getBalance());

// Set a valid balance using setter


account1.setBalance(3000.0);
System.out.println("Balance after valid set: " + account1.getBalance());
}
}

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
}
}

Garbage Collection in Java


Garbage collection in Java is the process of automatically freeing up memory by
removing objects that are no longer in use (i.e., no longer referenced).
Example:
Java handles garbage collection automatically, and there’s no explicit syntax for
invoking garbage collection. You can request garbage collection using System.gc(), but it is
not guaranteed to run immediately.
public class GarbageCollectionExample {
public static void main(String[] args) {
// Creating object
GarbageCollectionExample obj = new GarbageCollectionExample();
obj = null; // Nullifying reference to allow garbage collection

// Requesting garbage collection (not guaranteed to run)


System.gc();
}

// Garbage collector may invoke this method for cleanup


@Override
protected void finalize() {
System.out.println("Object is garbage collected");
}
}

String Class in Java


The String class is used to represent a sequence of characters. In Java, strings are
immutable, meaning once created, their values cannot be changed.
Example:
public class StringExample {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.length()); // Output: 13
System.out.println(str.toUpperCase()); // Output: HELLO, WORLD!
}
}

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

You might also like