Introduction
● One ofthe most popular programming language
● Created in 1995 by james Goslin at sun microsystems
● Later it is owned by oracle corporation
● Initially called Oak, later renamed to Java
● JAVA is cross platform
● It is open source and free
● It is OOP language
3.
Where we canuse JAVA
1. Android application
2. Web based application
3. Games
4. Enterprise application
5. Desktop application
4.
Definition of JAVA
Javais a high-level, object-oriented programming language developed by
Sun Microsystems in 1995. It is platform-independent, which means we can
write code once and run it anywhere using the Java Virtual Machine (JVM).
Java is mostly used for building desktop applications, web applications,
Android apps, and enterprise systems.
5.
Features of JAVA
Simple,Small, and Familiar
● Java is easy to learn.
● Its syntax is clean and similar to C/C++.
● Unwanted features like pointers are removed.
Compiled and Interpreted
● Java code is compiled into bytecode using javac.
● That bytecode is then interpreted and run by the JVM.
6.
Object-Oriented
● Java usesobjects and classes to organize code.
● It supports OOP concepts like inheritance, encapsulation, polymorphism, and
abstraction.
Platform Independent and Portable
● Java code runs on any OS (Windows, Linux, macOS).
● This is possible because of the JVM.
● “Write once, run anywhere.”
7.
Robust and Secure
●Java handles errors well (strong error checking).
● No memory leaks due to automatic garbage collection.
● Built-in features make it secure (no pointer access, bytecode verification).
Multithreaded and Interactive
● Java supports multithreading — running multiple tasks at the same time.
● Useful for games, animations, and real-time apps.
Dynamic
● Java can load classes at runtime (while the program is running).
8.
● It supportsdynamic memory management and can adapt during execution.
High Performance
● Java is faster than many interpreted languages.
● The Just-In-Time (JIT) compiler makes execution quicker.
Distributed / Network Oriented
● Java makes it easy to build programs that communicate over networks.
● It has strong support for web applications, sockets, and RMI (Remote Method
Invocation).
9.
Note:
What make javaportable and secure?
Java is portable because the output of the Java compiler is not an executable file.
Instead, it produces bytecode, which is independent of any operating system. As
long as a Java Virtual Machine (JVM) is available on a platform, the same Java
program can run on it without any changes. This is what makes Java programs
platform-independent and portable.
Java is also secure because every Java program runs inside the JVM, which acts
as a protected environment. This environment prevents the Java program from
directly accessing the system’s files or memory, helping to avoid harmful actions.
As a result, Java applications are considered safe and secure to run.
10.
Phases in JavaProgram Execution
Edit Phase
● The programmer writes the Java program (.java file).
● The code is saved (stored) on the disk.
● Example: writing Hello.java in an editor like Eclipse or Notepad.
Compile Phase
● The Java compiler (javac) compiles the code.
● It converts the .java file into bytecode (.class file).
● Bytecode is a platform-independent format that the JVM understands.
11.
Load Phase
● Theclass loader loads the bytecode into memory.
● This prepares the bytecode for the JVM to process.
Verify Phase
● The bytecode verifier checks that the bytecode is safe.
Execute Phase
● The interpreter (or JIT compiler) executes the bytecode.
● It converts the bytecode into machine code that the OS and CPU understand.
● The program runs and gives the output.
13.
What is JavaInterpreter?
The Java Interpreter is a part of the Java system that reads and executes
Java bytecode line by line.
It helps in running Java programs without compiling them fully to
machine code in advance.
14.
What is JVM(Java virtual machine)?
The Java Virtual Machine (JVM) is a software-based engine that runs Java
bytecode by providing a runtime environment.
It includes components like the interpreter, memory manager, security
manager, and garbage collector to manage program execution.
Definition
JDK is asoftware development kit provided by Oracle. that is used to write, compile,
and run Java programs. It includes all the tools and libraries needed for Java
development.
JDK includes,
Javac (Java compiler): javac is the Java compiler that converts a .java source file
(human-readable code) into a .class file, which contains bytecode (platform-
independent code).
Java : java is the command-line Java launcher tool used to run the compiled .class
file. It passes the bytecode to the Java Virtual Machine (JVM) for execution.
17.
JRE (java runtimeenvironment) : JRE is a software package that provides
everything needed to run a Java program, including the JVM and core Java
libraries — but it does not include the compiler.
JVM (Java virtual machine): JVM is a part of the JRE that executes the
bytecode (.class file) and converts it into machine-level code specific to the
operating system. It ensures Java's portability and security.
18.
Basic Structure ofJava Program
A Java program is made up of classes and methods. It follows a specific
structure that the Java compiler expects in order to compile and run the
program successfully.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
19.
Explanation
public: Access modifier(optional).
class: Keyword used to declare a class.
HelloWorld: Name of the class
static: The static keyword in Java is used to indicate that a method, variable, or
block belongs to the class itself, not to any specific object of the class.
This means it can be accessed without creating an object of the class.
20.
void: Does notreturn any value.
main: The starting point of the program.
String[] args: Command-line arguments.
System.out.println() is a built-in Java method used to display text or
values
21.
OOPS Concept inJAVA
OOP is a programming paradigm which uses objects in programming.
Major concepts of OOP are:
● Class
● Object
● Encapsulation
● Abstraction
● Inheritance
● polymorphism
22.
Basic Concept ofObject Oriented programming
Class
● Class is a template used to create objects and to define object data
types and methods
● Class is a logical entity
● Class is a group of similar objects
● Class is declared by using class keyword
Eg: class Student {}
23.
Object
● Object isa instance of a class
● Object is real world entity
● Object is created by using new keyword
● Objects will have attributes and methods
24.
Note
While creating theobject
Eg: Student s1=new Student();
Here Student() defines the “constructor” is a special method in Java that is
automatically called when an object of a class is created.
Its main job is to initialize (set) the values of the object.
25.
Example program
public classCupcake {
String model;
String flavour;
int price;
public static void main(String[]
args) {
Cupcake c1 = new Cupcake();
c1.model = "Britannia";
c1.flavour = "Choco";
c1.price = 20;
System.out.println(c1.model);
}}
26.
Inheritance is afeature in object-oriented programming that allows one class
(called the subclass or child class) to inherit the properties and behaviors (fields
and methods) of another class (called the superclass or parent class). It acquires
code reusability
Inheritance
27.
Example program
class Person{
String name;
int phone;
public void showAddress() {
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
}
}
class Teachers extends Person {
// Inherits everything from Person
}
28.
class Students extendsPerson {
// Inherits everything from Person
}
class Staffs extends Person {
// Inherits everything from Person
}
public class Main {
public static void main(String[] args) {
Teachers t1 = new Teachers();
t1.name = "John";
t1.phone = 12345;
t1.showAddress();
}
}
29.
Polymorphism
● Polymorphism means"many forms".
● In Java, it means: a method behaves differently based on the object that calls it.
● Poly = “many”
● Morph=”Forms”
Types of polymorphism
- Method overriding
- Method overloading
- Operator overloading
30.
Polymorphism - Methodoverriding
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}}
31.
class Cat extendsAnimal {
void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal d1 = new Dog();
d1.makeSound();
32.
Animal c2 =new Cat();
c2.makeSound();
}
}
Definition:
Method overriding means writing a method in the child class with the same name and
rules as in the parent class, so that the child class version runs instead of the parent’s.
In other words the child class replaces the parent class method with its own version.
33.
Polymorphism - Methodoverloading
class Calculator {
void sum(int a, int b) {
System.out.println("Sum of two ints: " + (a + b));
}
void sum(int a, int b, int c) {
System.out.println("Sum of three ints: " + (a + b + c));
}
34.
void sum(double a,double b) {
System.out.println("Sum of two doubles: " + (a + b));
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
c.sum(10, 20);
c.sum(5, 10, 15);
c.sum(4.5, 3.5); } }
35.
Method overloading -Definition
Method overloading in Java means defining multiple methods with the same name in the
same class, but with different types or numbers of parameters.
36.
Polymorphism - operatoroverloading
public class Main {
public static void main(String[] args) {
int a = 16;
int b = 16;
int result;
result = a + b;
System.out.println("Result is: " + result);
37.
String s1 ="John ";
String s2 = "Smith";
System.out.println(s1 + s2);
}
}
Definition:
Operator overloading means using the same operator (like +) to perform different operations
depending on the data type of the operands.
38.
Encapsulation
● Hiding ofdata (variables & methods) in a class into a single unit is called
encapsulation.
● Variables should be declared as private to restrict direct access.
● To view or modify these private variables, we use public getter and setter methods.
Advantages
● It increases data security
● Increases readability and flexibility
● It provides code reusability
39.
Definition
Encapsulation is oneof the core principles of Object-Oriented Programming (OOP). It
means wrapping data (variables) and methods (functions) together into a single unit
(class), and restricting direct access to some of the object's components for safety and
control.
40.
Example program
class Employee{
private String name;
private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
41.
public int getSalary(){
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
42.
public class MainClass{
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Shruthi");
e.setSalary(25000);
System.out.println(" Name: " + e.getName());
System.out.println(" Salary: " + e.getSalary());
}
}
43.
What is therelevance of using “this” keyword?
The this keyword in Java refers to the current object.
It is commonly used to differentiate between instance variables and method parameters
when they have the same name, especially inside setter methods.
Note:
Getter method is used to read the values
Setter method is used to modify or insert the values
44.
Abstraction
Abstraction is theprocess of hiding internal details and showing only the
essential features of an object.
In Java, abstraction is achieved using abstract classes and interfaces.
Example:
You press a button to start a washing machine you don’t need to know how all
the circuits work inside.
Syntax
abstract class <class_name>
abstract void <method name>;
45.
In Java OOPs(Object-Oriented Programming), abstraction can be achieved in two main ways:
1. Using Abstract Classes
● An abstract class is a class that cannot be instantiated (you can't create objects of it directly).
● It may contain abstract methods (without body) and concrete methods (with body).
● Used when classes share common behavior, but some methods should be implemented differently by subclasses.
2. Using Interfaces
● An interface is a contract that classes agree to follow.
● A class implements an interface and provides the method definitions.
46.
Example program byusing abstract class
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping...");
}
}
47.
class Dog extendsAnimal {
void sound() {
System.out.println("Dog barks");
} }
public class MainClass {
public static void main(String[] args) {
Animal d = new Dog();
d.sound();
d.sleep();
}
}
48.
Example program byusing interface
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}
49.
public class Main{
public static void main(String[] args) {
Animal a1 = new Dog();
a1.makeSound(); }
}
50.
Benefits of objectoriented programming
Encapsulation (Data Hiding)
● Data is wrapped inside a class.
● Only authorized methods can access it.
● Improves security and prevents accidental changes.
Reusability through Inheritance
● A new class can reuse code from an existing class.
● Saves time and avoids code duplication.
Polymorphism (Many Forms)
● Same method behaves differently in different classes.
● Makes code flexible and extensible.
51.
Real-World Mapping
● OOPmodels real-world problems using objects like Student, Account, Employee.
● Makes it easier to design and understand programs.
Modularity
● Program is divided into smaller pieces (classes).
● Makes the program organized and easy to manage.
Easy Maintenance
● If something breaks, only the affected class needs to be changed.
Scalability
● OOP makes it easy to expand the project by adding new classes and features.
52.
How Java IsDifferent from C and C++
Features C C++ JAVA
Programming Style Procedural OOP’s + Procedural Fully object oriented
Platform Works only on one
OS
Works only on one
OS
Works on all OS
(platform-
independent)
Pointers Yes Yes No pointers
Compilation Converts to machine
code
Same as C Converts to bytecode
(runs on JVM)
Memory Handling Manual Manual Automatic
Main Syntax main() main() public static void
main(...)
53.
Features C C++JAVA
Network/Internet Not supported Not supported Built-in support
Speed Fast Fast Slower then
(C/CPP) but safe
Inheritance
(multiple)
No Yes No (but it can
achieve through
interface
54.
Data types inJava
Java is a strongly typed language, which means each variable must be declared with a data
type before using it.
The data types are divided into
● Primitive data type - These are built-in used to store simple values.
● Non- primitive data type - These store references (addresses) to objects, not actual values.
Example program forprimitive data type
public class PrimitiveExample {
public static void main(String[] args) {
byte age = 25;
short year = 2025;
int population = 100000;
long distance = 9876543210L;
float price = 99.99;
double pi = 3.14159;
char grade = 'A';
boolean isPassed = true;
}
Example program fornon-primitive data type
public class NonPrimitiveSimple {
public static void main(String[] args) {
String name = "Shruthi";
int[] numbers = {10, 20, 30};
System.out.println("Name: " + name);
System.out.println("Array values:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
60.
Variables in java
Avariable is a name used to store data in memory that can be used and changed in a
Java program.
Syntax: <dataType>< variableName> = value;
Types of variables in java
● Local variable
● Instance variable
● Static variable
61.
What is localvariable?
● A local variable is a variable that is declared inside a method
● Exists only while the method runs
● Cannot be used outside the method
public class LocalVariableExample {
public void showMessage() {
String message = "Hello, I am a local variable!";
System.out.println(message);
}
public static void main(String[] args) {
LocalVariableExample obj = new LocalVariableExample();
obj.showMessage();
}}
62.
What is instancevariable?
● A variable declared inside a class but outside any method
● It belongs to the object of the class.
● Every object gets its own copy of the instance variable.
Example program:
class Student {
String name;
void showName() {
System.out.println("Name: " + name);
}}
public class Main {
public static void
main(String[] args) {
Student s1 = new
Student();
s1.name = "Shruthi";
s1.showName();}}
63.
What is staticvariable?
A static variable in Java is a variable that belongs to the class rather than any specific object. It is shared
among all instances (objects) of the class. It is declared using the static keyword
Example program
class Student {
static String college = "Kristu Jayanti";
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
System.out.println(s1.college);
System.out.println(s2.college);
}
}
Type conversion
It isalso called implicit conversion / Widening Conversion, here Java automatically
converts a smaller data type to a larger data type.
The order will be:
byte → short → int → long → float → double
public class Main {
public static void main(String[] args) {
int a = 100;
double b = a;
System.out.println("Integer value: " + a);
System.out.println("Converted to double: " + b); }}
66.
Note on charand boolean
Char data type
● char is a 16-bit unsigned data type.
● It stores a single Unicode character
● Internally, it holds an integer value (Unicode) from 0 to 65
● Can be converted to: int, long, float, double
public class Main {
public static void main(String[] args) {
char ch = 'A';
double d = ch;
System.out.println("As double: " + d); } }
Output:
As double: 65.0
67.
Note on charand boolean (cont…..)
Boolean data type
● boolean holds only two values: true or false
● It is not numeric
● Java does not allow any type conversion to or from boolean
68.
Type casting
It isalso called manual conversion / explicit conversion / narrowing conversion. Here you
manually convert a larger data type to a smaller one. Its risky, because it can lead to data loss
or errors.
Syntax
smallerType var = (smallerType) biggerVar;
double d = 10.5;
int num = (int) d;
System.out.println(num);
69.
Example of convertingchar to short
public class Main {
public static void main(String[] args) {
char ch = 'A';
short s = (short) ch;
System.out.println("Char: " + ch);
System.out.println("As short: " + s);
}
}
Output
Char: A
As short: 65
70.
Operators in Java
Anoperator is a symbol that tells the computer to perform a specific mathematical or
logical operation on values or variables.
Types of Java Operators
● Arithmetic Operators
Used to perform basic arithmetic operations like addition, subtraction, etc.
Examples: +, -, *, /, %
● Relational Operators
Used to compare two values.
Examples: ==, !=, >, <, >=, <=
71.
● Logical Operators
Usedto combine multiple conditions.
Examples: &&, ||, !
● Assignment Operators
Used to assign values to variables.
Examples: =, +=, -=, *=, /=, %=
● Increment and Decrement Operators
Used to increase or decrease the value of a variable by 1.
Examples: ++, --
72.
● Conditional Operators(Ternary Operator)
Used to evaluate expressions based on a condition.
Syntax: condition ? value1 : value2
● Bitwise Operators
Used to perform operations on bits.
Examples: &, |, ^, ~, <<, >>
● Special Operators
Includes operators like:
❖ instanceof – checks whether an object is an instance of a specific class.
❖ ?: – conditional operator (also listed above).
❖ . – dot operator (used to access members of a class).
Relational Operators
public classMain {
public static void main(String[] args) {
int a = 10, b = 10;
System.out.println(a <= b);
}
}
77.
Logical Operators
public classMain {
public static void main(String[] args) {
int a = 4;
System.out.println(a > 5 || a < 10);
System.out.println(a > 5 && a < 10);
}
}
78.
Conditional Operators (TernaryOperator)
public class Main {
public static void main(String[] args) {
int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is: " + result);
}
}
79.
Bitwise Operators
public classMain {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println("a & b = " + (a & b));
System.out.println("a | b = " + (a | b));
System.out.println("a ^ b = " + (a ^ b));
System.out.println("~a = " + (~a));
System.out.println("a << 1 = " + (a << 1));
System.out.println("a >> 1 = " + (a >> 1)); }}
80.
instanceof operator
class Animal{}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
System.out.println(d instanceof Dog); // true
System.out.println(d instanceof Animal); // true
}}
81.
Decision-Making
● conditional statementsare used to perform different actions based on various
conditions.
● The conditional statement evaluates a condition before the execution of instructions.
82.
The if statement
Itis one of the simplest decision-making statement which is
used to decide whether a block of code will execute if a
certain condition is true.
Syntax
if (condition) {
// block of code will execute if the condition is true
}
The if….else statement
●An if….else statement includes two blocks that are if block and else block. It is the
next form of the control statement, which allows the execution of code in a more
controlled way.
● It is used when you require to check two different conditions and execute a different
set of codes. The else statement is used for specifying the execution of a block of
code if the condition is false.
85.
Syntax
if (condition)
{
// blockof code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}
86.
Example
var x =40, y=20;
if (x < y)
{
sop("y is greater");
}
else
{
sop("x is greater");
}
87.
if...else if...else ladder
Theif...else if...else ladder is a control structure used to test multiple conditions in
sequence.
Java evaluates each condition one by one from top to bottom, and the first true condition
gets executed.
If none of the conditions are true, the final else block is executed.
88.
Syntax
if (condition1) {
//code block 1
} else if (condition2) {
// code block 2
} else if (condition3) {
// code block 3
} else {
// default code block if none are true
}
89.
Example
public class Main{
public static void main(String[] args) {
int marks = 78;
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 if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F
(Fail)");
}
}
}
90.
Switch statement injava
The switch statement in Java is a control flow statement that allows you to execute one
block of code out of many options, based on the value of a variable or expression.
Syntax
switch (expression) {
case value1:
// code block for value1
break;
case value2:
// code block for value2
break;
case value3:
// code block for value3
break;
// more cases...
default:
// default code block if no match }
91.
Example
public static voidmain(String[] args) {
int myNumber;
switch (myNumber) {
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
default:
System.out.println("Invalid
Number");
break;
}}
92.
Lab program -1
1.Writing a Java program to display all even and odd numbers between two given ranges.
import java.util.Scanner;
public class EvenOddRange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the starting number: ");
int start = input.nextInt();
System.out.print("Enter the ending number: ");
int end = input.nextInt();
System.out.println("nEven numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
93.
System.out.println("nnOdd numbers between" + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
System.out.print(i + " ");
}
}
}
}
94.
Example Switch program
importjava.util.Scanner;
public class calc
{
public static void main(String[] args) {
double num1, num2;
Scanner scanner1 = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner1.nextDouble();
System.out.print("Enter second number:");
Iteration Statements inJava (Loops)
Iteration statements in Java, also known as loops, are used to repeatedly
execute a block of code as long as a certain condition is true.
They allow a program to perform tasks multiple times without writing the
same code again and again.
● for loop
● while loop
● do-while loop
99.
for loop
A forloop in Java is a control flow statement that allows you to execute a block of code a
specific number of times.
It is used when the number of iterations is known in advance.
Syntax:
for (initialization; condition; update) {
// body of the loop
}
100.
Example
public class ForLoopExample{
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
101.
while loop
A whileloop in Java is a control flow statement that repeatedly executes a block of code
as long as a given condition is true.
It is used when the number of iterations is not known in advance — the loop continues
based on the condition.
Syntax
while (condition) {
// body of the loop
}
102.
Example
public class WhileLoopExample{
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}}
103.
do-while loop
A do-whileloop in Java is a looping control structure that executes the block of code at
least once, and then repeats it as long as the condition is true.
Unlike while, the condition is checked after the loop body, not before.
Syntax:
do {
// loop body
} while (condition);
104.
Example
int i =1;
do {
System.out.println(i);
i++;
} while (i <= 3);
105.
String methods injava
String methods in Java are built-in functions provided by the String class (in java.lang
package) that allow you to perform various operations on string data, such as:
● Finding the length of a string
● Comparing strings
● Extracting parts of a string
● Changing case (uppercase/lowercase)
● Replacing characters
● Trimming spaces, and more
106.
Note
In Java, youdo NOT need to import anything to use the String class or its methods.
The String class is part of the java.lang package, which is automatically imported by
default in every Java program.
107.
Example
● length() :Returns the number of characters in the string.
String name = "Java";
System.out.println(name.length());
● charAt(int index): Returns the character at the given index (starting
from 0).
String name = "Java";
System.out.println(name.charAt(2)); // Output: 'v'
108.
Example - (Cont…..)
●equals(String str): Checks if two strings are exactly the same (case-sensitive).
String a = "Hello";
String b = "hello";
System.out.println(a.equals(b)); // Output: false
● substring: Returns a substring from the given index to end.
String s = "Programming";
System.out.println(s.substring(3)); // Output: "gramming"
109.
Example - (Cont…..)
●Replace: Replaces characters in the string.
String msg = "hello";
System.out.println(msg.replace('l', 'p')); // Output: "heppo"
● toLowerCase() and toUpperCase()
String name = "Java";
System.out.println(name.toLowerCase()); // Output: "java"
System.out.println(name.toUpperCase()); // Output: "JAVA"
110.
Example - (Cont…..)
●indexOf(char):Finds the first position of a character or word.
String word = "Technology";
System.out.println(word.indexOf('o')); // Output: 4
● trim():Removes leading and trailing spaces.
String s = " Hello ";
System.out.println(s.trim()); // Output: "Hello"
111.
Example program
public classstringdemo
{
public static void main(String[] args)
{
String text = " Hello World! ";
System.out.println("Length: " + text.length());
String trimmed = text.trim();
System.out.println("Trimmed: "" + trimmed + """);
System.out.println("Uppercase: " + trimmed.toUpperCase());
112.
System.out.println("Lowercase: " +trimmed.toLowerCase());
System.out.println("Substring (6 to end): " + trimmed.substring(6));
System.out.println("Character at index 1: " + trimmed.charAt(1));
}
}
113.
Java Arrays
An arrayin Java is a collection of elements of the same data type, stored in contiguous
memory locations. It allows you to store multiple values in a single variable, instead of
declaring separate variables for each value.
114.
Example -1 -one dimensional array
public class Main {
public static void main(String[] args) {
String[] fruits = {"Banana", "Apple", "Grapes", "Melon"};
System.out.println(fruits[3]);
}
}
115.
Example -2 -one dimensional array
public class Main {
public static void main(String[] args) {
String[] fruits = {"Banana", "Apple", "Grapes", "Melon"};
for (int i = 0; i < fruits.length; ++i) {
System.out.println(fruits[i]);
}
}}
116.
Example - multidimensionalarray
public class Main {
public static void main(String[] args) {
int[][] num = {
{10, 20, 30, 40},
{50, 60, 70, 80}
};
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
System.out.print(num[i][j] + " ");
}
System.out.println();
}
}
}
117.
Labeled Loops inJava
A labeled loop in Java is a loop that is given a name (label). Labels are used to control
nested loops more precisely using break or continue statements.
Why use Labeled Loops?
In nested loops, a regular break or continue affects only the inner loop.
But if you want to:
● Exit from an outer loop early
● Skip the current iteration of the outer loop
You can use a labeled loop to do that.
Example
outer:
for (int i= 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break outer; // breaks outer loop
}
System.out.println(i + " " + j);
}
}
120.
Example
public class Main{
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer; // skips the rest of current outer loop iteration
}
System.out.println(i + " " + j); }}}}