Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/

11 mins· ·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Java Programming - Modifiers and String Handling

Java Programming Language

Chapter 5: Modifiers and String Handling

Access Control and Text Processing


Course: 4343203 - Java Programming

What We'll Cover

  • Access Modifiers (public, private, protected, default)
  • Non-Access Modifiers (final, static, abstract, etc.)
  • String Class and String Immutability
  • String Methods and Operations
  • Escape Sequences and Special Characters
  • Scanner Class for User Input
  • Command-line Arguments

Access Modifiers

Access modifiers control the visibility of classes, methods, and variables

Types of Access Modifiers

ModifierClassPackageSubclassOther Packages
public
protected
default
private

Remember: Scope decreases from public → protected → default → private

public Modifier

public: Accessible from anywhere

Example:


public class PublicExample {
    public int publicVar = 10;
    
    public void publicMethod() {
                            

Usage:


// From any class, any package
PublicExample obj = new PublicExample();
obj.publicVar = 20;        // Accessible
obj.publicMethod();        // Accessible

// Even from different packages
import com.example.PublicExample;
PublicExample obj2 = new PublicExample();
                            

private Modifier

private: Accessible only within the same class

Example:


public class PrivateExample {
    private int privateVar = 10;
    private String secret = "hidden";
    
    private void privateMethod() {
        System.out.println("Private method");
    }
    
    public void accessPrivate() {
        privateVar = 20;     // OK - same class
        privateMethod();     // OK - same class
    }
}
                            

Usage:


// From another class
PrivateExample obj = new PrivateExample();
// obj.privateVar = 30;     // ERROR!
// obj.privateMethod();     // ERROR!
obj.accessPrivate();        // OK - public method

// Encapsulation example
public class BankAccount {
    private double balance;  // Hidden
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public double getBalance() {
        return balance;
    }
}
                            

protected and default Modifiers

protected Modifier:

Accessible within package and by subclasses


// In package com.example
public class Parent {
    protected int protectedVar = 10;
    
    protected void protectedMethod() {
        System.out.println("Protected method");
    }
}

// In package com.example
class Child extends Parent {
    public void test() {
        protectedVar = 20;      // OK - subclass
        protectedMethod();      // OK - subclass
    }
}

// In different package
class AnotherChild extends Parent {
    public void test() {
        protectedVar = 30;      // OK - subclass
        protectedMethod();      // OK - subclass
    }
}
                            

default Modifier:

Accessible only within the same package


// In package com.example
class DefaultExample {
    int defaultVar = 10;        // default access
    
    void defaultMethod() {      // default access
        System.out.println("Default method");
    }
}

// In same package com.example
class SamePackageClass {
    public void test() {
        DefaultExample obj = new DefaultExample();
        obj.defaultVar = 20;    // OK - same package
        obj.defaultMethod();    // OK - same package
    }
}

// In different package
class DifferentPackageClass {
    public void test() {
        DefaultExample obj = new DefaultExample();
        // obj.defaultVar = 30;    // ERROR!
        // obj.defaultMethod();    // ERROR!
    }
}
                            

Non-Access Modifiers

Non-access modifiers provide additional functionality but don't control access

static Modifier

static: Belongs to the class rather than any instance

Static Variables:


class Counter {
    private static int count = 0;  // Shared by all objects
    private int id;
    
    public Counter() {
        count++;           // Increment shared counter
        id = count;        // Assign unique ID
    }
    
    public static int getCount() {
        return count;      // Static method
    }
    
    public int getId() {
        return id;
    }
}
                            

Usage:


// Static methods called on class
System.out.println(Counter.getCount()); // 0

Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println(Counter.getCount()); // 3
System.out.println(c1.getId());         // 1
System.out.println(c2.getId());         // 2
System.out.println(c3.getId());         // 3

// Static utility methods
class MathUtils {
    public static double square(double x) {
        return x * x;
    }
    
    public static int max(int a, int b) {
        return (a > b) ? a : b;
    }
}

double result = MathUtils.square(5);     // 25
                            

final Modifier

final: Cannot be modified, overridden, or extended

Final Variables:


class Constants {
    // Final variables (constants)
    public static final double PI = 3.14159;
    public static final int MAX_SIZE = 100;
    private final String name;
    
    public Constants(String name) {
        this.name = name;  // Can assign once
    }
    
    public void test() {
        // PI = 3.14;      // ERROR!
        // name = "New";   // ERROR!
    }
}
                            

Final Methods:


class Parent {
    public final void display() {
        System.out.println("Cannot override");
    }
    
    public void show() {
        System.out.println("Can override");
    }
}

class Child extends Parent {
    // public void display() { } // ERROR!
    
    @Override
    public void show() {         // OK
        System.out.println("Overridden");
    }
}
                            

Final Classes:


// Final class cannot be extended
public final class FinalClass {
    public void method() {
        System.out.println("Final class method");
    }
}

// class SubClass extends FinalClass { } // ERROR!

// Examples of final classes in Java
// String, Integer, Double, etc.
final class String { ... }
final class Integer { ... }
                            

abstract Modifier

abstract: Incomplete implementation, must be completed by subclasses

Abstract Classes:


abstract class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    // Abstract method - no implementation
    public abstract void makeSound();
    
    // Concrete method - has implementation
    public void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Cannot instantiate abstract class
// Animal animal = new Animal("Pet"); // ERROR!
                            

Implementing Abstract Classes:


class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    // Must implement abstract method
    @Override
    public void makeSound() {
        System.out.println(name + " says: Woof!");
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + " says: Meow!");
    }
}

// Usage
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");
dog.makeSound();  // "Buddy says: Woof!"
cat.makeSound();  // "Whiskers says: Meow!"
                            

Other Non-Access Modifiers

ModifierDescriptionUsed With
synchronizedThread-safe method accessMethods, blocks
volatileVariable not cached thread-locallyVariables
transientSkip during serializationVariables
nativeImplemented in platform-specific codeMethods
strictfpStrict floating-point calculationsClasses, methods

// Examples
public synchronized void synchronizedMethod() { } // Thread-safe
private volatile boolean flag;                    // Not cached
private transient String password;               // Not serialized
public native void nativeMethod();               // Platform-specific
public strictfp double calculate(double x) { }   // Strict floating-point
                        

String Class

String is a reference type representing sequences of characters

String Characteristics

Key Properties:

  • Immutable: Cannot be changed once created
  • Reference Type: Stored in heap memory
  • Object: Has methods and properties
  • Thread-Safe: Due to immutability

String Creation:


// String literals (recommended)
String str1 = "Hello";
String str2 = "World";

// Using new keyword
String str3 = new String("Hello");
String str4 = new String("World");

// Immutability demonstration
String original = "Hello";
String modified = original.concat(" World");
System.out.println(original);  // Still "Hello"
System.out.println(modified);  // "Hello World"
                            

String Memory Management & Manipulation

String Memory Management and Manipulation

Escape Sequences

Escape sequences represent special characters in strings

Escape SequenceCharacterDescription
\""Double quote
\''Single quote
\\\Backslash
\nNew line
\tTab
\rCarriage return
\bBackspace

String quotes = "She said \"Hello World!\"";
String path = "C:\\Users\\John\\Documents";
String multiline = "First line\nSecond line\nThird line";
String tabbed = "Name:\tJohn\nAge:\t25";
                        

String Concatenation

Using + Operator:


String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // "John Doe"

// With other data types
String name = "Age: ";
int age = 25;
String info = name + age;     // "Age: 25"

// Multiple concatenations
String result = "The answer is " + (2 + 3) + "!";
System.out.println(result);   // "The answer is 5!"
                            

Using concat() Method:


String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);
System.out.println(result);   // "Hello World"

// Method chaining
String greeting = "Hello"
    .concat(" ")
    .concat("Beautiful")
    .concat(" World");
System.out.println(greeting); // "Hello Beautiful World"
                            

Common String Methods

Length and Character Access:


String str = "Hello World";

// Length
int len = str.length();        // 11

// Character at index
char ch = str.charAt(0);       // 'H'
char lastCh = str.charAt(len-1); // 'd'

// Index of character/substring
int index = str.indexOf('o');   // 4 (first occurrence)
int lastIndex = str.lastIndexOf('o'); // 7
int wordIndex = str.indexOf("World"); // 6
                            

Case Conversion:


String original = "Hello World";

String upper = original.toUpperCase();  // "HELLO WORLD"
String lower = original.toLowerCase();  // "hello world"

// Check case
boolean hasUpper = Character.isUpperCase(original.charAt(0)); // true
boolean hasLower = Character.isLowerCase(original.charAt(1)); // true
                            

String Comparison and Searching

Comparison Methods:


String str1 = "Hello";
String str2 = "hello";
String str3 = "Hello";

// Exact comparison
boolean equal1 = str1.equals(str3);       // true
boolean equal2 = str1.equals(str2);       // false

// Case-insensitive comparison
boolean equalIgnore = str1.equalsIgnoreCase(str2); // true

// Lexicographic comparison
int compare = str1.compareTo(str2);       // negative (H < h)
int compareIgnore = str1.compareToIgnoreCase(str2); // 0

// WARNING: Don't use == for string comparison
boolean wrong = (str1 == str3);           // May be true or false
                            

Searching Methods:


String text = "Java Programming Language";

// Contains
boolean hasJava = text.contains("Java");     // true
boolean hasPython = text.contains("Python"); // false

// Starts/Ends with
boolean startsWithJava = text.startsWith("Java");  // true
boolean endsWithLang = text.endsWith("Language");  // true

// Empty/Blank checks
String empty = "";
String spaces = "   ";
boolean isEmpty1 = empty.isEmpty();          // true
boolean isEmpty2 = spaces.isEmpty();         // false
boolean isBlank = spaces.trim().isEmpty();   // true
                            

String Manipulation Methods

Substring Operations:


String text = "Java Programming";

// Substring from index
String sub1 = text.substring(5);     // "Programming"

// Substring with start and end
String sub2 = text.substring(0, 4);  // "Java"
String sub3 = text.substring(5, 9);  // "Prog"

// Replace operations
String replaced = text.replace('a', 'A'); // "JAvA ProgrAmming"
String newText = text.replace("Java", "Python"); // "Python Programming"
                            

Trimming and Splitting:


String messy = "  Hello World  ";
String clean = messy.trim();         // "Hello World"

// Split string
String sentence = "Java,Python,C++,JavaScript";
String[] languages = sentence.split(",");
// ["Java", "Python", "C++", "JavaScript"]

for (String lang : languages) {
    System.out.println(lang.trim());
}

// Format strings
String formatted = String.format("Hello %s, you are %d years old", 
    "John", 25);
// "Hello John, you are 25 years old"
                            

Scanner Class for User Input

Scanner class reads input from various sources including keyboard

Scanner Basics

Import and Create Scanner:


import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        // Create Scanner for keyboard input
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        System.out.println("Hello " + name + 
            ", you are " + age + " years old");
        
        scanner.close(); // Important!
    }
}
                            

Scanner Methods:

MethodDescription
nextLine()Read complete line
next()Read single word
nextInt()Read integer
nextDouble()Read double
nextFloat()Read float
nextBoolean()Read boolean
hasNext()Check if input available
hasNextInt()Check if next is integer

Scanner Input Types and Examples

Reading Different Data Types:


import java.util.Scanner;

public class MultipleInputs {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter details:");
        
        System.out.print("Name: ");
        String name = input.nextLine();
        
        System.out.print("Age: ");
        int age = input.nextInt();
        
        System.out.print("Height (m): ");
        double height = input.nextDouble();
        
        System.out.print("Is student (true/false): ");
        boolean isStudent = input.nextBoolean();
        
        System.out.println("\nSummary:");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + "m");
        System.out.println("Student: " + isStudent);
        
        input.close();
    }
}
                            

Input Validation:


import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Validate integer input
        int number;
        while (true) {
            System.out.print("Enter a number: ");
            if (scanner.hasNextInt()) {
                number = scanner.nextInt();
                break;
            } else {
                System.out.println("Invalid! Please enter a number.");
                scanner.next(); // Clear invalid input
            }
        }
        
        // Validate positive number
        double amount;
        do {
            System.out.print("Enter positive amount: ");
            amount = scanner.nextDouble();
            if (amount <= 0) {
                System.out.println("Amount must be positive!");
            }
        } while (amount <= 0);
        
        System.out.println("Number: " + number);
        System.out.println("Amount: " + amount);
        
        scanner.close();
    }
}
                            

Command-line Arguments

Command-line arguments are passed to the main method when program starts

Using Command-line Arguments

Basic Usage:


public class CommandLineDemo {
    public static void main(String[] args) {
        System.out.println("Number of arguments: " + args.length);
        
        if (args.length > 0) {
            System.out.println("Arguments received:");
            for (int i = 0; i < args.length; i++) {
                System.out.println("args[" + i + "] = " + args[i]);
            }
        } else {
            System.out.println("No arguments provided");
        }
    }
}

// Run with: java CommandLineDemo hello world 123
// Output:
// Number of arguments: 3
// Arguments received:
// args[0] = hello
// args[1] = world
// args[2] = 123
                            

Processing Arguments:


public class Calculator {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java Calculator   ");
            System.out.println("Example: java Calculator 10 + 5");
            return;
        }
        
        try {
            double num1 = Double.parseDouble(args[0]);
            String operator = args[1];
            double num2 = Double.parseDouble(args[2]);
            double result = 0;
            
            switch (operator) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    if (num2 != 0) {
                        result = num1 / num2;
                    } else {
                        System.out.println("Error: Division by zero");
                        return;
                    }
                    break;
                default:
                    System.out.println("Unknown operator: " + operator);
                    return;
            }
            
            System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
            
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format");
        }
    }
}
                            

Chapter Summary

Access Control:

  • public, private, protected, default modifiers
  • Encapsulation and data hiding
  • Package-level access control

Non-Access Modifiers:

  • static: Class-level members
  • final: Immutable elements
  • abstract: Incomplete implementation

String Handling:

  • String immutability and characteristics
  • Common string methods and operations
  • Escape sequences and special characters

Input/Output:

  • Scanner class for user input
  • Command-line argument processing
  • Input validation techniques

Next: Inheritance and Polymorphism

Thank You!

Questions?


Ready to explore inheritance and polymorphism!