JAVA PROGRAMMING | UNIT I NOTES | B.
Tech 1st Year
UNIT I
Introduction to Java Programming
[Link] 1st Year • Detailed College Exam Notes
Topic Sub-topics
Data Types, Variables & Arrays Primitive types, type casting, 1D/2D
arrays
Operators Arithmetic, relational, logical,
bitwise, ternary
Control Statements if/else, switch, for, while, do-
while, nested loops
Classes & Objects Creating classes, objects, access
control
Constructors & Methods Overloading, parameters, recursion,
static, final
Nested & Inner Classes Static nested, inner, local,
anonymous
String Handling String class, StringBuilder, common
methods
I/O & Command Line Scanner, BufferedReader, command-
line arguments
1. Introduction to Java
Java is a high-level, object-oriented, platform-independent programming language developed by James
Gosling at Sun Microsystems in 1995. It follows the principle: Write Once, Run Anywhere (WORA).
Key Features of Java
• Platform Independent: Java code compiles to bytecode which runs on JVM on any OS.
• Object-Oriented: Everything is based on classes and objects.
• Robust: Strong type checking, exception handling, garbage collection.
• Secure: No pointer arithmetic; sandboxed execution via JVM.
• Multithreaded: Built-in support for concurrent programming.
• Simple: Syntax similar to C++ but without pointers and complex features.
Unit I – Introduction to Java Programming | Page 1
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
Java Program Structure
// [Link]
public class MyFirstProgram {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
• public class MyFirstProgram – class name must match filename
• public static void main(String[] args) – entry point of every Java program
• [Link]() – prints output to console with newline
📝 Exam Tip
Java is both compiled and interpreted. javac compiles source code (.java) to bytecode (.class),
and JVM interprets/executes the bytecode.
2. Data Types, Variables & Arrays
2.1 Data Types
Java has two categories of data types:
A) Primitive Data Types (8 types)
Type Size Range / Default Example
byte 1 byte -128 to 127 / 0 byte b = 100;
short 2 bytes -32768 to 32767 short s = 5000;
/ 0
int 4 bytes -2^31 to 2^31-1 int i = 100000;
/ 0
long 8 bytes -2^63 to 2^63-1 long l =
/ 0L 9999999L;
float 4 bytes 6-7 decimal float f = 3.14f;
digits / 0.0f
double 8 bytes 15-16 decimal double d =
digits / 0.0 3.14159;
char 2 bytes 0 to 65535 char c = 'A';
(Unicode) /
'\u0000'
boolean ~1 bit true / false / boolean flag =
false true;
B) Non-Primitive (Reference) Data Types
Unit I – Introduction to Java Programming | Page 2
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
• String, Arrays, Classes, Interfaces
• They store references (memory addresses) to objects, not values directly.
Type Casting
Converting one data type to another.
// Implicit (Widening) – automatic, no data loss
int i = 100;
long l = i; // int → long (widening)
double d = i; // int → double
// Explicit (Narrowing) – manual, may lose data
double pi = 3.14;
int x = (int) pi; // x = 3 (decimal part lost)
2.2 Variables
A variable is a named memory location used to store data. Syntax: datatype variableName = value;
int age = 20; // declaration + initialization
double salary; // declaration only (default: 0.0)
String name = "Rahul"; // String variable
final double PI = 3.14159; // constant variable (cannot be changed)
Types of Variables
• Local Variable: Declared inside a method; must be initialized before use; accessible only in
that method.
• Instance Variable: Declared inside a class but outside any method; belongs to object; gets
default value.
• Static Variable: Declared with static keyword; shared among all objects of the class;
belongs to class.
public class Demo {
int instanceVar = 10; // instance variable
static int staticVar = 20; // static variable
void show() {
int localVar = 30; // local variable
[Link](localVar + instanceVar + staticVar);
}
}
2.3 Arrays
An array is a collection of elements of the same data type stored in contiguous memory. In Java, arrays
are objects.
1D Array (Single Dimensional)
// Declaration
Unit I – Introduction to Java Programming | Page 3
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
int[] arr;
// Instantiation
arr = new int[5]; // creates array of 5 integers
// Declaration + Instantiation
int[] marks = new int[5];
// Declaration + Initialization
int[] scores = {85, 90, 78, 92, 88};
// Accessing elements (index starts from 0)
[Link](scores[0]); // Output: 85
[Link]([Link]); // Output: 5
// Traversing an array using for loop
for (int i = 0; i < [Link]; i++) {
[Link](scores[i]);
}
// Enhanced for-each loop
for (int s : scores) {
[Link](s);
}
2D Array (Multi-Dimensional)
// Declaration and instantiation
int[][] matrix = new int[3][3];
// Declaration + Initialization
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing element at row 1, col 2
[Link](grid[1][2]); // Output: 6
// Traversing 2D array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < grid[i].length; j++) {
[Link](grid[i][j] + " ");
}
[Link]();
}
📝 Important
Array indices start from 0. Accessing an invalid index throws ArrayIndexOutOfBoundsException
at runtime.
3. Operators
Unit I – Introduction to Java Programming | Page 4
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
Operators are special symbols that perform operations on operands.
Operator Type Operators Description / Example
Arithmetic + - * / % int a=10, b=3; a/b=3,
a%b=1
Relational == != > < >= <= a>b → true (returns
boolean)
Logical && || ! true && false → false
Bitwise & | ^ ~ << >> Operates on binary bits
Assignment = += -= *= /= %= a += 5 same as a = a +
5
Unary ++ -- + - ! a++ (post-increment),
++a (pre)
Ternary condition ? val1 : val2 int max = (a>b) ? a :
b;
instanceof obj instanceof Class Checks object type at
runtime
Operator Precedence (High to Low)
1. () [] . (postfix)
2. ++ -- ~ ! (unary)
3. * / % (multiplicative)
4. + - (additive)
5. << >> >>> (shift)
6. < > <= >= (relational)
7. == != (equality)
8. & (bitwise AND)
9. ^ (bitwise XOR)
10. | (bitwise OR)
11. && (logical AND)
12. || (logical OR)
13. ? : (ternary)
14. = += -= ... (assignment)
4. Control Statements
4.1 Selection Statements
if / else if / else
int marks = 75;
if (marks >= 90) {
[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
Unit I – Introduction to Java Programming | Page 5
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
} else if (marks >= 60) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}
// Output: Grade: B
switch Statement
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
default: [Link]("Weekend");
}
// Output: Wednesday
📝 Exam Tip
Without the break statement, execution 'falls through' to the next case. switch works with int,
char, String (Java 7+), and enum.
4.2 Iterative Structures (Loops)
for Loop
// Syntax: for(initialization; condition; update)
for (int i = 1; i <= 5; i++) {
[Link](i + " ");
}
// Output: 1 2 3 4 5
while Loop
// Checks condition BEFORE execution
int i = 1;
while (i <= 5) {
[Link](i + " ");
i++;
}
// Output: 1 2 3 4 5
do-while Loop
// Executes AT LEAST ONCE – checks condition AFTER
int i = 1;
do {
[Link](i + " ");
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
Unit I – Introduction to Java Programming | Page 6
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
Nested Loops
A loop inside another loop. Commonly used for patterns and 2D structures.
// Printing a multiplication table (nested loop example)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link](i * j + "\t");
}
[Link]();
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
// Star Pattern using nested loops
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
5. Classes and Objects
A class is a blueprint/template for creating objects. An object is an instance of a class with its own state
and behavior.
5.1 Creating a Class
public class Student {
// Instance Variables (attributes/fields)
String name;
int rollNo;
double marks;
// Method (behavior)
void display() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNo);
[Link]("Marks: " + marks);
}
}
Unit I – Introduction to Java Programming | Page 7
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
5.2 Creating Objects
public class Main {
public static void main(String[] args) {
// Creating object using 'new' keyword
Student s1 = new Student();
// Accessing and setting fields
[Link] = "Rahul";
[Link] = 101;
[Link] = 88.5;
// Calling method on object
[Link]();
// Creating another object
Student s2 = new Student();
[Link] = "Priya";
[Link] = 102;
[Link] = 92.0;
[Link]();
}
}
5.3 Access Control (Access Modifiers)
Access modifiers control the visibility/accessibility of class members.
Modifier Same Class Same Package Subclass Other
Packages
public ✓ Yes ✓ Yes ✓ Yes ✓ Yes
protected ✓ Yes ✓ Yes ✓ Yes ✗ No
default (no ✓ Yes ✓ Yes ✗ No ✗ No
modifier)
private ✓ Yes ✗ No ✗ No ✗ No
public class BankAccount {
public String holderName; // accessible everywhere
protected String branch; // accessible in subclass
double balance; // default – same package only
private String pin; // only within this class
private void validatePin(String p) { // private method
if ([Link](pin)) [Link]("Valid!");
}
}
6. Constructors
Unit I – Introduction to Java Programming | Page 8
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
A constructor is a special method used to initialize objects. It has the same name as the class and no
return type.
6.1 Types of Constructors
Default Constructor (No-Arg Constructor)
class Car {
String brand;
int year;
// Default Constructor
Car() {
brand = "Unknown";
year = 2024;
}
void show() {
[Link](brand + " - " + year);
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car(); // calls default constructor
[Link](); // Output: Unknown - 2024
}
}
Parameterized Constructor
class Car {
String brand;
int year;
// Parameterized Constructor
Car(String b, int y) {
brand = b;
year = y;
}
void show() {
[Link](brand + " - " + year);
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("Toyota", 2022);
Car c2 = new Car("Honda", 2023);
[Link](); // Output: Toyota - 2022
[Link](); // Output: Honda - 2023
}
}
Unit I – Introduction to Java Programming | Page 9
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
📝 Exam Tip
If you don't define any constructor, Java provides a default constructor automatically. But if you
define a parameterized constructor, Java does NOT provide a default one.
7. Methods
7.1 Method Parameters & Return Types
class Calculator {
// Method with parameters returning int
int add(int a, int b) {
return a + b;
}
// Method with no return (void)
void greet(String name) {
[Link]("Hello, " + name + "!");
}
// Method returning double
double average(int[] nums) {
int sum = 0;
for (int n : nums) sum += n;
return (double) sum / [Link];
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 3)); // 8
[Link]("Anjali"); // Hello, Anjali!
int[] arr = {10, 20, 30, 40};
[Link]([Link](arr)); // 25.0
}
}
7.2 Method Overloading
When a class has multiple methods with the same name but different parameter lists (different number
or types of parameters).
class MathOps {
// Overloaded methods – same name, different parameters
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
Unit I – Introduction to Java Programming | Page 10
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
int multiply(int a, int b, int c) {
return a * b * c;
}
}
public class Main {
public static void main(String[] args) {
MathOps m = new MathOps();
[Link]([Link](3, 4)); // 12
[Link]([Link](2.5, 3.0)); // 7.5
[Link]([Link](2, 3, 4)); // 24
}
}
📝 Exam Tip
Method overloading is resolved at COMPILE TIME (static polymorphism). You cannot overload
by changing only the return type.
7.3 Recursive Methods
A method that calls itself to solve a problem by breaking it into smaller subproblems.
class Recursion {
// Factorial using recursion: n! = n * (n-1)!
int factorial(int n) {
if (n == 0 || n == 1) // base case
return 1;
return n * factorial(n - 1); // recursive call
}
// Fibonacci using recursion
int fibonacci(int n) {
if (n <= 1) return n; // base case
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
public class Main {
public static void main(String[] args) {
Recursion r = new Recursion();
[Link]([Link](5)); // 120
[Link]([Link](7)); // 13
}
}
// factorial(5) = 5 * factorial(4)
// = 5 * 4 * factorial(3)
// = 5 * 4 * 3 * factorial(2)
// = 5 * 4 * 3 * 2 * factorial(1)
// = 5 * 4 * 3 * 2 * 1 = 120
7.4 Returning Objects from Methods
class Point {
int x, y;
Unit I – Introduction to Java Programming | Page 11
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
Point(int x, int y) {
this.x = x;
this.y = y;
}
// Method that returns an object
Point add(Point p) {
return new Point(this.x + p.x, this.y + p.y);
}
void display() {
[Link]("(" + x + ", " + y + ")");
}
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point p3 = [Link](p2); // returns a new Point object
[Link](); // Output: (4, 6)
}
}
8. Static and Final Qualifiers
8.1 static Keyword
The static keyword means the member belongs to the class itself rather than to any specific object.
class Counter {
static int count = 0; // shared among ALL objects
int id;
Counter() {
count++;
id = count;
}
static void showCount() { // static method
[Link]("Total objects: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link](); // called on class, not object
// Output: Total objects: 3
}
}
Unit I – Introduction to Java Programming | Page 12
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
📝 Rules for static
Static methods can only access static variables/methods. 'this' keyword cannot be used in static
methods. Static blocks execute when class is loaded.
8.2 final Keyword
final can be applied to variables, methods, and classes.
// final variable – value cannot be changed (constant)
final double PI = 3.14159;
// PI = 3.0; // ERROR: cannot assign a value to final variable
// final method – cannot be overridden in subclass
class Animal {
final void breathe() {
[Link]("Breathing...");
}
}
// final class – cannot be extended (inherited)
final class Singleton { }
// class Sub extends Singleton { } // ERROR
// Example: Java's String class is final
9. Nested and Inner Classes
A class defined inside another class is called a nested class. It helps logically group classes that are
used together.
Type Declaration Key Feature
Static Nested Class static class Inside { } Cannot access non-
static members of outer
class
Inner Class (Non- class Inside { } Can access all members
static) of outer class
Local Inner Class Inside a method Scope limited to that
method
Anonymous Inner Class new Interface() { } Used for one-time
implementations
Inner Class Example
class Outer {
int x = 100;
class Inner {
void display() {
// Inner class can access outer class members
Unit I – Introduction to Java Programming | Page 13
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
[Link]("Outer x = " + x);
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
[Link] inner = [Link] Inner(); // creating inner object
[Link](); // Output: Outer x = 100
}
}
Static Nested Class Example
class University {
String name = "IIT";
static class Department {
void show() {
[Link]("CS Department");
// Cannot access 'name' (non-static) here
}
}
}
public class Main {
public static void main(String[] args) {
// No outer object needed for static nested class
[Link] dept = new [Link]();
[Link](); // Output: CS Department
}
}
10. String Handling in Java
String is one of the most used classes in Java. Strings are immutable (once created, cannot be
changed). Java provides the String class and StringBuilder/StringBuffer for string operations.
10.1 Creating Strings
// Using string literal (stored in String Pool)
String s1 = "Hello";
String s2 = "Hello"; // both s1 and s2 point to SAME object in pool
// Using new keyword (creates new object in heap)
String s3 = new String("Hello");
// s1 == s2 → true (same reference in pool)
// s1 == s3 → false (different heap object)
// [Link](s3) → true (same content)
Unit I – Introduction to Java Programming | Page 14
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
10.2 Important String Methods
Method Description Example Output
length() Returns length of "Hello".length() → 5
string
charAt(i) Returns char at index "Hello".charAt(1) → 'e'
i
substring(i,j) Returns substring from "Hello".substring(1,4) →
i to j-1 "ell"
toUpperCase() Converts to uppercase "hello".toUpperCase() →
"HELLO"
toLowerCase() Converts to lowercase "HELLO".toLowerCase() →
"hello"
equals(s) Compares content "Hi".equals("Hi") → true
equalsIgnoreCase(s) Case-insensitive "hi".equalsIgnoreCase("HI")
compare → true
indexOf(s) First occurrence index "Hello".indexOf('l') → 2
replace(old,new) Replaces characters "Hello".replace('l','r') →
"Herro"
trim() Removes " Hi ".trim() → "Hi"
leading/trailing
spaces
contains(s) Checks if substring "Hello".contains("ell") →
exists true
concat(s) Appends string "Hi".concat(" Java") → "Hi
Java"
split(delim) Splits string into "a,b,c".split(",") →
array ["a","b","c"]
toCharArray() Converts to char array "Hi" → ['H','i']
isEmpty() Checks if string is "".isEmpty() → true
empty
10.3 StringBuilder (Mutable Strings)
StringBuilder is preferred for frequent string modifications as it does not create new objects each time.
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Hello World
[Link](5, ","); // Hello, World
[Link](5, 6); // Hello World
[Link](); // dlroW olleH
[Link](0, 5, "Hi"); // Hi olleH
[Link]([Link]());
// StringBuilder vs String
// String: immutable, creates new object on each change
// StringBuilder: mutable, modifies same object (NOT thread-safe)
// StringBuffer: mutable, thread-safe (synchronized) but slower
Unit I – Introduction to Java Programming | Page 15
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
11. I/O Mechanism in Java
11.1 Output
[Link]("Hello"); // prints with newline
[Link]("Hello"); // prints WITHOUT newline
[Link]("%s is %d years old", "Raj", 20); // formatted output
// Output: Raj is 20 years old
11.2 Input using Scanner
Scanner class ([Link]) is the most common way to take input in Java.
import [Link];
public class InputDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link](); // reads full line
[Link]("Enter your age: ");
int age = [Link](); // reads integer
[Link]("Enter your GPA: ");
double gpa = [Link](); // reads double
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("GPA: " + gpa);
[Link](); // good practice to close scanner
}
}
Scanner Method Reads
nextInt() Integer value
nextDouble() Double value
nextFloat() Float value
nextLong() Long value
next() Single word (till whitespace)
nextLine() Entire line (including spaces)
nextBoolean() Boolean value (true/false)
11.3 Input using BufferedReader
import [Link].*;
Unit I – Introduction to Java Programming | Page 16
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
public class BufferedDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter age: ");
int age = [Link]([Link]()); // must parse manually
[Link](name + " is " + age + " years old");
}
}
12. Command Line Arguments
Command-line arguments are values passed to the main() method when a Java program is run from
the terminal. They are received as an array of Strings (String[] args).
public class CmdArgs {
public static void main(String[] args) {
[Link]("Number of arguments: " + [Link]);
for (int i = 0; i < [Link]; i++) {
[Link]("Argument " + i + ": " + args[i]);
}
}
}
// Compile: javac [Link]
// Run: java CmdArgs Hello World 42
// Output:
// Number of arguments: 3
// Argument 0: Hello
// Argument 1: World
// Argument 2: 42
// Note: arguments are always received as String.
// To use as numbers, parse them:
int num = [Link](args[0]);
double d = [Link](args[1]);
Practical Example: Adding Two Numbers via Command Line
public class AddCmdArgs {
public static void main(String[] args) {
if ([Link] < 2) {
[Link]("Please provide 2 numbers");
return;
}
int a = [Link](args[0]);
int b = [Link](args[1]);
[Link]("Sum = " + (a + b));
Unit I – Introduction to Java Programming | Page 17
JAVA PROGRAMMING | UNIT I NOTES | [Link] 1st Year
}
}
// Run: java AddCmdArgs 15 25
// Output: Sum = 40
Quick Revision Summary
Topic Key Points to Remember
Data Types 8 primitive types: byte, short, int,
long, float, double, char, boolean
Arrays Index starts at 0; length property;
ArrayIndexOutOfBoundsException
Operators Ternary ?: ; Precedence: * before +;
&& before ||
Selection switch needs break; if-else chain
for ranges
Loops for (count-controlled), while
(condition), do-while (at least
once)
Access Modifiers public > protected > default >
private
Constructor Same name as class, no return type;
Java provides default if none
defined
Overloading Same name, different params;
resolved at compile time
Recursion Must have base case to avoid
StackOverflowError
static Belongs to class, not object; no
'this' inside static methods
final Variable=constant, method=cannot
override, class=cannot extend
String Immutable; use .equals() not == for
comparison; StringBuilder for
mutation
Scanner nextLine() reads full line;
nextInt() reads integer only
Command Line args[] always String; parse using
[Link]() for numbers
END OF UNIT I NOTES
[Link] 1st Year • Java Programming • All the best for your exams!
Unit I – Introduction to Java Programming | Page 18