Class Notes
Programming in Java (CSE2006)
Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now owned by Oracle Corporation) in 1995. Designed to be platform-independent, Java
allows developers to write code that can run on any device with a Java Virtual Machine (JVM).
Java is known for its simplicity, portability, and robustness, making it a popular choice for
developing a wide range of applications, from web and mobile applications to large-scale
enterprise systems.
Key Features of Java
1. Platform Independence:
o Java code is compiled into bytecode, which can be executed on any platform that has a
JVM.
o The slogan "Write Once, Run Anywhere" (WORA) highlights this feature.
2. Object-Oriented:
o Java is built around the concept of objects, making it easier to manage and structure
programs.
o Key principles include encapsulation, inheritance, and polymorphism.
3. Simple:
o Java's syntax is clear and easy to understand, especially for those familiar with C++.
o It removes complex features like pointers and operator overloading.
4. Secure:
o Java provides a secure environment through its runtime environment and security
features.
o Features like bytecode verification, secure class loading, and a security manager help
protect against malicious code.
5. Robust:
o Java emphasizes reliability with strong memory management and error handling.
o It includes automatic garbage collection to manage memory efficiently.
6. Multithreaded:
o Java supports multithreading, allowing the execution of multiple threads
simultaneously.
o This is useful for developing interactive and high-performance applications.
7. Portable:
o Java programs are portable across different platforms without modification.
o This is achieved through the JVM and standard libraries.
8. High Performance:
o Java's performance is enhanced through Just-In-Time (JIT) compilation.
o JIT compiles bytecode into native machine code at runtime.
9. Distributed:
o Java provides built-in support for networked, distributed applications.
o It includes libraries like RMI (Remote Method Invocation) and support for web
technologies.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Java Development Kit (JDK)
To develop Java applications, you'll need the Java Development Kit (JDK), which includes:
Java Compiler (javac): Converts source code into bytecode.
Java Runtime Environment (JRE): Provides libraries and JVM needed to run Java
applications.
Java Documentation (javadoc): Tool for generating API documentation from Java source
code.
Java Debugger (jdb): Helps in debugging Java applications.
Demonstrated Installation of JDK and Eclipse IDE.
Basic Java Program
Here’s a simple example of a Java program to illustrate the structure and syntax:
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld: Declares a public class named HelloWorld.
public static void main(String[] args): Main method, the entry point of the program.
System.out.println("Hello, World!");: Prints "Hello, World!" to the console.
Steps to Compile and Run a Java Program
1. Write the code: Save your code in a file with a .java extension, e.g., HelloWorld.java.
2. Compile the code: Use the javac command to compile the code:
javac HelloWorld.java
This generates a HelloWorld.class file containing the bytecode.
Run the code: Use the java command to run the bytecode:
java HelloWorld
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
This executes the program and prints "Hello, World!" to the console.
Java's simplicity, portability, and robustness have made it a dominant programming language
in various domains. Whether you're building web applications, mobile apps, or enterprise
solutions, Java provides a reliable and efficient platform for development. With its strong
community support and continuous evolution, Java remains a top choice for developers
worldwide.
Java Variables
Variables are used to store data in a program. In Java, each variable must be declared with a
data type, which determines the type of data it can hold.
Declaration and Initialization
1. Declaration: Declaring a variable means specifying its data type and name.
int age;
Initialization: Assigning a value to a variable at the time of declaration or later in the program.
int age = 25;
Types of Variables
Local Variables: Declared inside a method or block and only accessible within that method or
block.
public void display() {
int count = 10; // Local variable
Instance Variables: Declared inside a class but outside any method, and are specific to an
instance of a class.
public class Employee {
int id; // Instance variable
String name;
Class/Static Variables: Declared with the static keyword and shared among all instances of a
class.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
public class Employee {
static String companyName = "TechCorp"; // Static variable
Java Data Types
Java data types are divided into two categories: primitive data types and reference data types.
Primitive Data Types
byte: 8-bit signed integer. Range: -128 to 127.
byte b = 100;
short: 16-bit signed integer. Range: -32,768 to 32,767.
short s = 1000;
int: 32-bit signed integer. Range: -2^31 to 2^31-1.
int i = 100000;
long: 64-bit signed integer. Range: -2^63 to 2^63-1.
long l = 100000L;
float: 32-bit floating-point. Used for single-precision decimal numbers.
float f = 10.5f;
double: 64-bit floating-point. Used for double-precision decimal numbers.
double d = 10.5;
char: 16-bit Unicode character.
char c = 'A';
boolean: Represents true or false.
boolean isTrue = true;
Reference Data Types
Reference data types are used to refer to objects and include classes, interfaces, and arrays.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
String str = "Hello, World!"; // String is a class
int[] arr = {1, 2, 3}; // Array of integers
Java Operators
Operators are special symbols that perform specific operations on one, two, or three operands
and return a result.
Types of Operators
Arithmetic Operators: Perform basic arithmetic operations.
Addition (+): int sum = a + b;
Subtraction (-): int diff = a - b;
Multiplication (*): int prod = a * b;
Division (/): int div = a / b;
Modulus (%): int mod = a % b;
Unary Operators: Operate on a single operand.
Unary plus (+): int pos = +a;
Unary minus (-): int neg = -a;
Increment (++): a++; ++a;
Decrement (--): a--; --a;
Logical complement (!): boolean not = !true;
Assignment Operators: Assign values to variables.
Simple assignment (=): int a = 10;
Compound assignment: a += 5; // a = a + 5;
Relational Operators: Compare two values and return a boolean result.
Equal to (==): a == b
Not equal to (!=): a != b
Greater than (>): a > b
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Less than (<): a < b
Greater than or equal to (>=): a >= b
Less than or equal to (<=): a <= b
Logical Operators: Perform logical operations on boolean values.
AND (&&): a && b
OR (||): a || b
NOT (!): !a
Bitwise Operators: Perform bit-level operations.
AND (&): a & b
OR (|): a | b
XOR (^): a ^ b
Complement (~): ~a
Left shift (<<): a << 2
Right shift (>>): a >> 2
Unsigned right shift (>>>): a >>> 2
Ternary Operator: A shorthand for the if-else statement.
condition ? expr1 : expr2
int result = (a > b) ? a : b;
Instanceof Operator: Checks if an object is an instance of a specific class or subclass.
boolean isString = str instanceof String;
Summary:
Variables: Containers for storing data values, which can be local, instance, or class
variables.
Data Types: Include primitive types (like int, char, boolean) and reference types (like
arrays, classes).
Operators: Special symbols used to perform operations on variables and values,
including arithmetic, logical, relational, and more.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Java Input and Output (I/O)
Java provides extensive support for input and output through its I/O package (java.io). This
package allows programs to read data from various input sources (such as files, keyboard, or
network connections) and write data to various output destinations (such as files, console, or
network connections).
Basic I/O Streams
Java I/O is based on streams, which are sequences of data. There are two types of streams:
Byte Streams: Handle input and output of raw binary data.
Character Streams: Handle input and output of characters (text data).
Byte Streams
InputStream: Abstract class representing input of bytes.
OutputStream: Abstract class representing output of bytes.
Common subclasses include:
FileInputStream and FileOutputStream: For file I/O operations.
Example of reading and writing bytes:
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt"))
{
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Character Streams
Reader: Abstract class for reading character streams.
Writer: Abstract class for writing character streams.
Common subclasses include:
FileReader and FileWriter: For file I/O operations with characters.
Example of reading and writing characters:
import java.io.*;
public class CharStreamExample {
public static void main(String[] args) {
try (FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt")) {
int charData;
while ((charData = fr.read()) != -1) {
fw.write(charData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Buffered Streams
Buffered streams provide efficient reading and writing by reducing the number of I/O
operations.
BufferedReader and BufferedWriter: For character streams.
BufferedInputStream and BufferedOutputStream: For byte streams.
Example of using buffered character streams:
import java.io.*;
public class BufferedStreamExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new
FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
} catch (IOException e) {
e.printStackTrace();
}
}
}
Standard I/O
Java provides System.in, System.out, and System.err for standard input, output, and error
streams.
Example of reading from console input and writing to console output:
import java.util.Scanner;
public class StandardIOExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Summary
Byte Streams: Used for reading and writing binary data (InputStream, OutputStream).
Character Streams: Used for reading and writing text data (Reader, Writer).
Buffered Streams: Provide efficient reading and writing by buffering data.
Standard I/O: Using System.in, System.out, and System.err for console operations.
NIO: Provides more capabilities and flexibility for file I/O operations.
Java’s I/O package offers a wide range of classes and methods to perform various input and
output operations, making it versatile and powerful for handling different types of data.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Java Expressions & Blocks
Expressions
In Java, an expression is a combination of variables, operators, and values that produces a
single value. Expressions are the building blocks of Java statements.
Examples of Expressions:
1. Arithmetic Expressions:
int result = 5 + 3; // result is 8
int total = 10 * 2; // total is 20
2. Relational Expressions:
boolean isEqual = (5 == 5); // isEqual is true
boolean isGreater = (10 > 5); // isGreater is true
3. Logical Expressions:
boolean andResult = (true && false); // andResult is false
boolean orResult = (true || false); // orResult is true
4. Assignment Expressions:
int x = 10; // Assigns 10 to x
x += 5; // x is now 15 (equivalent to x = x + 5)
Blocks
A block is a group of zero or more statements between balanced braces {}. Blocks can be used
wherever a single statement is allowed.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Example of a Block:
{
int x = 10;
int y = 20;
int sum = x + y;
System.out.println("Sum: " + sum);
}
Usage in Methods and Control Structures:
public class BlockExample {
public static void main(String[] args) {
int number = 5;
// Block used in an if statement
if (number > 0) {
System.out.println("Number is positive.");
} else {
System.out.println("Number is not positive.");
}
// Block used in a for loop
for (int i = 0; i < 5; i++) {
System.out.println("i: " + i);
}
}
}
Java Comments
Comments are used to explain the code and make it more readable. Comments are ignored by the
compiler.
Types of Comments
Single-Line Comments:
Start with // and extend to the end of the line.
// This is a single-line comment
int x = 10; // Variable declaration
Multi-Line Comments:
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Start with /* and end with */. Can span multiple lines.
/*
* This is a multi-line comment
* It can span multiple lines
*/
int y = 20;
Documentation Comments:
Start with /** and end with */. Used to generate API documentation using javadoc.
Summary
Expressions: Combinations of variables, operators, and values that produce a single value.
Blocks: Groups of zero or more statements enclosed in {}, used in methods and control
structures.
Comments: Used to explain the code and make it more readable, including single-line, multi-
line, and documentation comments.
Java Flow Control
Flow control statements in Java allow you to control the execution flow of your program.
These statements can make your program execute statements conditionally or repeatedly.
Java provides several types of flow control statements:
1. Decision-Making Statements
2. Looping Statements
3. Branching Statements
Decision-Making Statements
1. if statement
if statement evaluates a condition and executes a block of code if the condition is true.
if (condition) {
// Code to be executed if condition is true
}
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Example:
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}
2. if-else statement
The if-else statement evaluates a condition and executes one block of code if the condition
is true and another block if the condition is false.
if (condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
Example:
int age = 17;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
3. if-else-if ladder
The if-else-if ladder is used to test multiple conditions.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Example:
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
} else if (marks >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
4. switch statement
The switch statement is used to select one of many code blocks to be executed.
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// You can have any number of case statements.
default:
// Code to be executed if expression doesn't match any case
}
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
Looping Statements
1. while loop
The while loop repeatedly executes a block of code as long as the specified condition is true.
while (condition) {
// Code to be executed
}
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
2. do-while loop
The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once.
do {
// Code to be executed
} while (condition);
Example:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
3. for loop
The for loop is used to execute a block of code a specific number of times.
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
4. for-each loop
The for-each loop is used to iterate over elements in an array or a collection.
for (type variable : array/collection) {
// Code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Branching Statements
1. break statement
The break statement terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
// Output: 1 2
2. continue statement
The continue statement skips the current iteration of a loop and proceeds with the next
iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
// Output: 1 2 4 5
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)
3. return statement
The return statement exits from the current method and optionally returns a value.
public int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
Summary
Decision-Making Statements: if, if-else, if-else-if, and switch statements are
used to execute code based on conditions.
Looping Statements: while, do-while, for, and for-each loops are used to execute
code repeatedly.
Branching Statements: break, continue, and return statements are used to control the
flow of the program by breaking out of loops, skipping iterations, or returning from methods.
These flow control statements allow you to write flexible and dynamic programs in Java, making it
possible to execute code conditionally and repeatedly based on the program's logic.
Demonstration of All programs done in Class. Hands-on practice done in class.
Programming in Java NOTES by: Dr. Anand Motwani (Faculty, SCSE, VIT Bhopal University)