JAVA PROGRAMMING
Mid-Term Examination Notes
Theory | Syntax | Programs
Topics Covered:
1. Java Platform & Architecture (JVM, JDK, JRE)
2. Java Program Structure, Compilation & Execution
3. Data Types (Primitive + Non-Primitive)
4. Variables, Keywords & Literals
5. Operators & Operator Precedence
6. Type Conversion & Casting
UNIT 1: Java Platform & Architecture
1.1 What is Java?
Java is a high-level, class-based, object-oriented programming language designed to have as few
implementation dependencies as possible. Java follows the principle: Write Once, Run Anywhere
(WORA).
1.2 Java Platform Components
JDK – Java Development Kit
The JDK is the full software development kit used to develop Java applications. It includes the compiler
(javac), libraries, tools, and the JRE.
• Contains: javac (compiler), java (runtime), javadoc, jar, debugger
• Used by: Developers to write, compile, and run Java programs
• Includes JRE + Development Tools
JRE – Java Runtime Environment
The JRE provides the libraries and JVM required to run Java programs. It does NOT include
development tools like a compiler.
• Contains: JVM + class libraries + runtime files
• Used by: End users to run Java applications
• Does NOT include javac compiler
JVM – Java Virtual Machine
The JVM is an abstract computing machine that enables a computer to run Java programs. It converts
bytecode (.class files) into machine-specific code at runtime.
• Platform independent (different JVM for each OS)
• Performs: Class loading, bytecode verification, execution
• Contains: Class Loader, Execution Engine, Garbage Collector, JIT Compiler
Component Full Form Role Includes
JDK Java Development Kit Develop + Compile + Run JRE + Compiler + Tools
JRE Java Runtime Run Java programs JVM + Libraries
Environment
JVM Java Virtual Machine Execute Bytecode Class Loader +
Execution Engine
1.3 How Java Works – Compilation & Execution Flow
Java source code goes through a two-step process before execution:
• Step 1: Source code (.java) → Compiled by javac → Bytecode (.class)
• Step 2: Bytecode (.class) → Interpreted/Compiled by JVM → Machine Code → Output
📝 Note: Bytecode is platform-independent. The JVM on each OS converts it to native machine code.
1.4 JIT Compiler (Just-In-Time Compiler)
The JIT compiler is part of the JVM. It compiles frequently used bytecode into native machine code at
runtime to improve performance. It bridges interpretation and compilation.
UNIT 2: Java Program Structure, Compilation & Execution
2.1 Structure of a Java Program
Every Java program must follow a specific structure. Here is the standard structure:
// 1. Package Declaration (optional)
package [Link];
// 2. Import Statements (optional)
import [Link];
// 3. Class Declaration (mandatory)
public class HelloWorld {
// 4. Main Method (entry point)
public static void main(String[] args) {
// 5. Statements
[Link]("Hello, World!");
}
}
Explanation of Each Part:
Part Keyword/Syntax Description
Package package mypack; Groups related classes together (like folders)
Import import [Link].*; Brings in classes from other packages
Class public class MyClass Blueprint for objects; filename
must match class name
Main Method public static void main(String[] Entry point of every Java program
args)
Statements [Link](...) Instructions to be executed
2.2 First Java Program – Detailed
public class FirstProgram {
public static void main(String[] args) {
// Print to console
[Link]("Welcome to Java!");
[Link]("No newline here. ");
[Link]("Formatted: %d %s%n", 42, "Java");
}
}
📝 Note: [Link] adds newline. [Link] does NOT. [Link] uses format
specifiers.
2.3 Compilation and Execution Commands
Step Command Description
Compile javac [Link] Generates [Link] (bytecode)
Run java FirstProgram JVM runs the bytecode (no .class extension)
Check version java -version Displays installed JDK version
2.4 Comments in Java
// Single-line comment
/* Multi-line comment
Spans multiple lines */
/** Javadoc comment
* Used to generate API documentation
* @param args command line arguments
*/
UNIT 3: Data Types in Java
3.1 Categories of Data Types
Java has two main categories of data types:
• Primitive Data Types: 8 built-in types (byte, short, int, long, float, double, char, boolean)
• Non-Primitive / Reference Types: String, Arrays, Classes, Interfaces
3.2 Primitive Data Types – Complete Reference
Type Size Range Default Example
byte 1 byte (8 bits) -128 to 127 0 byte b = 100;
short 2 bytes (16 bits) -32,768 to 32,767 0 short s = 1000;
int 4 bytes (32 bits) -2^31 to 2^31-1 0 int i = 42;
long 8 bytes (64 bits) -2^63 to 2^63-1 0L long l = 99L;
float 4 bytes (32 bits) ~3.4e-38 to 3.4e+38 0.0f float f = 3.14f;
double 8 bytes (64 bits) ~1.7e-308 to 1.7e+308 0.0d double d = 3.14;
char 2 bytes (16 bits) 0 to 65,535 (Unicode) '\u0000' char c = 'A';
boolean 1 bit (JVM- true or false false boolean b = true;
dependent)
3.3 Primitive Data Types – Programs
public class PrimitiveTypes {
public static void main(String[] args) {
byte age = 25;
short year = 2024;
int salary = 50000;
long population = 1400000000L;
float price = 99.99f;
double pi = 3.141592653589793;
char grade = 'A';
boolean isJavaFun = true;
[Link]("byte: " + age);
[Link]("short: " + year);
[Link]("int: " + salary);
[Link]("long: " + population);
[Link]("float: " + price);
[Link]("double: " + pi);
[Link]("char: " + grade);
[Link]("boolean: " + isJavaFun);
}
}
3.4 String – Non-Primitive Type
String is a class in Java ([Link]). It represents a sequence of characters and is immutable
(cannot be changed once created).
public class StringDemo {
public static void main(String[] args) {
String name = "Java Programming";
// Common String methods
[Link]([Link]()); // 16
[Link]([Link]()); // JAVA PROGRAMMING
[Link]([Link]()); // java programming
[Link]([Link](0)); // J
[Link]([Link](5)); // Programming
[Link]([Link]("Java"));// true
[Link]([Link]("Java","Python")); // Python Programming
[Link]([Link]("Pro")); // 5
[Link]([Link]()); // removes whitespace
}
}
3.5 Arrays
An array is a collection of elements of the same data type stored in contiguous memory. Arrays in Java
are objects.
Single-Dimensional Array:
public class ArrayDemo {
public static void main(String[] args) {
// Declaration and initialization
int[] numbers = {10, 20, 30, 40, 50};
// Access elements
[Link](numbers[0]); // 10
[Link]([Link]); // 5
// Traverse with loop
for (int i = 0; i < [Link]; i++) {
[Link]("numbers[" + i + "] = " + numbers[i]);
}
// Enhanced for-loop
for (int n : numbers) {
[Link](n + " ");
}
}
}
Multi-Dimensional (2D) Array:
public class TwoDArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print matrix
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + "\t");
}
[Link]();
}
}
}
UNIT 4: Variables, Keywords & Literals
4.1 Variables
A variable is a named memory location that stores a value. In Java, every variable must be declared
with a data type before use.
Syntax:
datatype variableName; // Declaration
datatype variableName = value; // Declaration + Initialization
Types of Variables:
Type Where Declared Scope Default Value
Local Variable Inside a method/block Within the method/block No default (must
only initialize)
Instance Variable Inside class, outside Entire class (object-level) Default (0, null, false)
method
Static/Class Variable With static keyword in class Shared across all objects Default (0, null, false)
public class VariableTypes {
// Instance variable
int instanceVar = 100;
// Static variable
static String className = "Java";
public void show() {
// Local variable
int localVar = 50;
[Link](localVar);
[Link](instanceVar);
[Link](className);
}
public static void main(String[] args) {
VariableTypes obj = new VariableTypes();
[Link]();
}
}
4.2 Java Keywords (Reserved Words)
Keywords are reserved words that have predefined meanings in Java. They cannot be used as variable
names, class names, or method names.
Category Keywords
Data Types byte short int long float double char boolean void
Access Modifiers public private protected
Class & OOP class interface extends implements new this super abstract final
Control Flow if else switch case default for while do break continue return
Exception Handling try catch finally throw throws
Others static synchronized volatile import package instanceof enum
📝 Note: Java has 53 reserved keywords. 'const' and 'goto' are reserved but not used.
4.3 Literals
A literal is a fixed constant value directly written in source code.
Literal Type Example Description
Integer Literal 42, 0b1010, 0xFF, 077 Decimal, Binary (0b), Hex (0x), Octal (0)
Long Literal 99L, 1234567890L Append L or l suffix
Float Literal 3.14f, 2.5F Append f or F suffix
Double Literal 3.14, 2.718d Default for decimals; d suffix
optional
Char Literal 'A', '\n', '\t', '\\' Single character in single quotes
String Literal "Hello", "Java" Text in double quotes
Boolean Literal true, false Only two values
Null Literal null Represents absence of reference
// Literal Examples
int decimal = 255;
int hex = 0xFF; // 255 in hexadecimal
int binary = 0b11111111; // 255 in binary
int octal = 0377; // 255 in octal
long big = 1_000_000L; // Underscore for readability (Java 7+)
float f = 3.14f;
double d = 3.14;
char c = 'Z';
char esc = '\n'; // newline escape
String s = "Hello";
boolean b = true;
UNIT 5: Operators, Precedence & Associativity
5.1 Arithmetic Operators
Operator Name Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/2 2 (integer division)
% Modulus 5%2 1 (remainder)
++ Increment a++ or ++a Increases by 1
-- Decrement a-- or --a Decreases by 1
public class ArithmeticOps {
public static void main(String[] args) {
int a = 10, b = 3;
[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3 (truncates)
[Link](a % b); // 1
// Pre vs Post Increment
int x = 5;
[Link](x++); // prints 5, then x=6
[Link](++x); // x=7, then prints 7
}
}
5.2 Relational (Comparison) Operators
Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5>3 true
< Less than 5<3 false
>= Greater than or equal 5 >= 5 true
<= Less than or equal 3 <= 5 true
5.3 Logical Operators
Operator Name Example Result
&& Logical AND true && false false (both must be true)
|| Logical OR true || false true (at least one true)
! Logical NOT !true false (inverts)
5.4 Assignment Operators
Operator Example Equivalent To
= a=5 a=5
+= a += 3 a=a+3
-= a -= 3 a=a-3
*= a *= 3 a=a*3
/= a /= 3 a=a/3
%= a %= 3 a=a%3
5.5 Bitwise Operators
Operator Name Example (a=5, b=3) Result
& Bitwise AND 5&3 1
| Bitwise OR 5|3 7
^ Bitwise XOR 5^3 6
~ Bitwise NOT ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2
>>> Unsigned Right Shift 5 >>> 1 2
5.6 Ternary Operator
The ternary operator is a shorthand for if-else. It takes three operands.
// Syntax: condition ? valueIfTrue : valueIfFalse
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Max = " + max); // Max = 20
String result = (a % 2 == 0) ? "Even" : "Odd";
[Link](result); // Even
5.7 Operator Precedence & Associativity
When an expression has multiple operators, precedence determines which operator is evaluated first.
Associativity determines the direction of evaluation when operators have equal precedence.
Level Operators Associativity
1 (Highest) () [] . Left to Right
2 ++ -- ~ ! (unary) + - Right to Left
3 */% Left to Right
4 +- Left to Right
5 << >> >>> Left to Right
6 < > <= >= instanceof Left to Right
7 == != Left to Right
8 & Left to Right
9 ^ Left to Right
10 | Left to Right
11 && Left to Right
12 || Left to Right
13 ?: Right to Left
14 (Lowest) = += -= *= /= %= etc. Right to Left
// Precedence Example
int result = 10 + 3 * 2; // = 10 + 6 = 16 (NOT 26)
int result2 = (10 + 3) * 2; // = 13 * 2 = 26
// Associativity Example (Right to Left for assignment)
int a, b, c;
a = b = c = 5; // c=5, then b=5, then a=5
// Complex expression
int x = 5 + 3 * 2 - 8 / 4;
// Step 1: 3*2=6, 8/4=2
// Step 2: 5+6-2 = 9
[Link](x); // 9
UNIT 6: Type Conversion & Type Casting
6.1 What is Type Conversion?
Type conversion is the process of converting a value from one data type to another. Java supports two
kinds:
• Implicit (Widening / Automatic) Conversion
• Explicit (Narrowing / Manual) Casting
6.2 Widening Conversion (Implicit)
Widening conversion happens automatically when converting a smaller data type to a larger one. No
data loss occurs.
Widening order: byte → short → int → long → float → double
public class WideningDemo {
public static void main(String[] args) {
byte b = 10;
short s = b; // byte to short (automatic)
int i = s; // short to int (automatic)
long l = i; // int to long (automatic)
float f = l; // long to float (automatic)
double d = f; // float to double (automatic)
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("int: " + i);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
}
}
📝 Note: Widening is safe because larger types can always hold values of smaller types.
6.3 Narrowing Conversion (Explicit Casting)
Narrowing conversion requires explicit casting. It converts a larger data type to a smaller one. Data loss
may occur.
Narrowing order: double → float → long → int → short → byte
public class NarrowingDemo {
public static void main(String[] args) {
double d = 9.99;
int i = (int) d; // explicit cast: 9.99 → 9 (decimal lost!)
[Link](i); // 9
int big = 300;
byte b = (byte) big; // 300 exceeds byte range (-128 to 127)
[Link](b); // 44 (data overflow!)
long l = 1234567890123L;
int x = (int) l; // may lose data
[Link](x);
}
}
6.4 String Conversions
public class StringConversion {
public static void main(String[] args) {
// int to String
int num = 42;
String s1 = [Link](num); // "42"
String s2 = [Link](num); // "42"
String s3 = "" + num; // "42" (concatenation)
// String to int
String str = "123";
int n1 = [Link](str); // 123
int n2 = [Link](str); // 123
// double to String
double d = 3.14;
String sd = [Link](d); // "3.14"
// String to double
String ds = "3.14";
double nd = [Link](ds); // 3.14
[Link](s1 + " " + n1 + " " + nd);
}
}
Conversion Method Example
int → String [Link](n) or String s = [Link](42);
[Link](n)
String → int [Link](s) int n =
[Link]("42");
double → String [Link](d) String s =
[Link](3.14);
String → double [Link](s) double d =
[Link]("3.14");
char → int Direct assignment (widening) int i = 'A'; // i = 65
int → char Explicit cast char c = (char)65; // c = 'A'
6.5 Promotion in Expressions
Java automatically promotes smaller types (byte, short, char) to int when used in expressions.
byte a = 10;
byte b = 20;
// byte result = a + b; // ERROR! a+b is int
int result = a + b; // Correct (auto-promoted to int)
// Fix with cast
byte result2 = (byte)(a + b); // Explicit cast back to byte
[Link](result2); // 30
📝 Note: In any arithmetic expression with mixed types, Java promotes to the widest type present.
6.6 Quick Summary Table
Concept Type Syntax Data Loss?
Widening Automatic int i = byteVar; No
Narrowing Explicit int i = (int) doubleVar; Possible
String to Number Explicit [Link](str) No (exception if
invalid)
Number to String Automatic [Link](num) No
QUICK REFERENCE CHEAT SHEET
Escape Sequences
Sequence Meaning
\n New line
\t Tab
\\ Backslash
\' Single quote
\" Double quote
\r Carriage return
\0 Null character
Naming Conventions
Element Convention Example
Class PascalCase HelloWorld, StudentData
Method camelCase getName(), calculateTotal()
Variable camelCase firstName, totalAmount
Constant UPPER_SNAKE_CASE MAX_SIZE, PI_VALUE
Package all lowercase [Link]
Best of luck in your exam! 🎯