0% found this document useful (0 votes)
1 views25 pages

JavaNotes 1-6 Chapter Overview

The document provides an overview of Java, highlighting its features, including platform independence, object-oriented principles, and automatic memory management. It compares Java with C, detailing differences in compilation, memory management, and security. Additionally, it covers essential Java concepts such as JDK, JRE, JVM, data types, variables, input handling, casting, operators, and control structures.

Uploaded by

dmasthanmehak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views25 pages

JavaNotes 1-6 Chapter Overview

The document provides an overview of Java, highlighting its features, including platform independence, object-oriented principles, and automatic memory management. It compares Java with C, detailing differences in compilation, memory management, and security. Additionally, it covers essential Java concepts such as JDK, JRE, JVM, data types, variables, input handling, casting, operators, and control structures.

Uploaded by

dmasthanmehak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MQI DEGREE COLLEGE

Chapter 1 – 6 Short Notes for Reference


OOP using JAVA Programming

What is Java?

Java is a high-level, object-oriented programming language designed to be simple, secure,


and platform-independent. It was developed by James Gosling at Sun Microsystems and
officially released in 1995. Today, it's maintained by Oracle Corporation.

Feature Description
Platform- Java programs are compiled into bytecode, which runs on the Java
independent Virtual Machine (JVM). This means "Write Once, Run Anywhere."
Everything in Java is part of a class or object. It supports concepts like
Object-oriented
inheritance, polymorphism, encapsulation, and abstraction.
Java’s syntax is similar to C/C++, but it removes complex and error-
Simple & Familiar
prone features like pointers.
Java runs in a virtual machine, uses strong memory management, and
Secure
has built-in security features.
Java emphasizes early error checking, strong type checking, and
Robust
exception handling.
Java supports concurrent programming using threads, making it good
Multithreaded
for high-performance applications.
Automatic Garbage
Java automatically handles memory cleanup, freeing up unused objects.
Collection

What Does Platform-Independent Mean?

Platform-independent means that a program or software can run on any operating system
or hardware without needing to be rewritten or recompiled for each one.

What is a JIT Compiler in Java?

JIT stands for Just-In-Time Compiler. It's a part of the Java Virtual Machine (JVM) that
improves/ increases the speed/ performance of Java applications by compiling bytecode into
native machine code at runtime.

Difference between Java and C?

Programming Paradigm Procedural Object-Oriented

Compilation To machine code To bytecode (JVM)

Platform Dependent Independent

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 1|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Memory Management Manual Automatic (GC)

Pointers Yes No

Speed Faster Slower (JVM overhead)

Security Low High

Libraries Limited Extensive

Typical Use Cases System-level programming App development, Android

Difference between Java and C


Java and C are both powerful programming languages, but they differ significantly in design,
purpose, and usage. Here's a clear comparison of the key differences between Java and C:
1. Language Type
 Java: Object-oriented programming language (though it supports procedural elements too).
2. Compilation & Execution
 C: Compiled directly into machine code using a compiler like gcc. Runs fast and close to
hardware.
 Java: Compiled into bytecode using the javac compiler, then run on the Java Virtual Machine
(JVM), making it platform-independent.
3. Memory Management
 C: Manual memory management using malloc, free, etc.
 Java: Automatic garbage collection—no manual memory management needed.
4. Platform Dependency
 C: Platform-dependent (compiled separately for each OS/architecture).
 Java: Platform-independent—“Write Once, Run Anywhere” (thanks to the JVM).
5. Pointers
 C: Supports pointers explicitly (can directly manipulate memory).
 Java: No pointers exposed to the programmer (safer and more secure).
6. Code Structure
 C: Program can be written without any object-oriented concepts.
 Java: Everything must be inside a class. Supports encapsulation, inheritance, polymorphism,
etc.
7. Standard Libraries
 C: Minimal standard library (basic I/O, math, etc.).
 Java: Rich standard library (data structures, networking, GUI, threading, etc.).
8. Speed
 C: Generally faster (closer to hardware).
 Java: Slightly slower due to the JVM overhead, though performance is often optimized by Just-
In-Time (JIT) compilation.
9. Security
 C: Less secure (buffer overflows, pointer bugs).

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 2|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

 Java: More secure by design (no direct memory access, built-in security features).
 10. Use Cases
 C: Systems programming (OS kernels, embedded systems, drivers).
 Java: Application development (web apps, Android apps, enterprise systems).

What is JDK (Java Development Kit)?

The Java Development Kit (JDK) is a software development environment used to build,
compile, run, and debug Java applications.

It's the complete toolkit for Java developers — it includes everything needed to write and run
Java programs.

JDK = JDK + JRE + JVM

What is JRE (Java Runtime Environment)?

The Java Runtime Environment (JRE) is the part of Java that lets you run Java programs.
It provides the libraries, Java Virtual Machine (JVM), and other components necessary to
execute Java applications — but not to develop them.

What is JVM (Java Virtual Machine)?

The Java Virtual Machine (JVM) is the engine that runs Java programs. It's a virtual
machine that interprets or compiles Java bytecode into machine code specific to your
computer's operating system and hardware.

Component Purpose Includes


JDK For developing Java apps JRE + compiler & tools
JRE For running Java apps JVM + libraries
JVM Executes Java bytecode Core of the JRE

Types of Java Programs

Java is a general-purpose language, which means you can use it to build many different kinds
of applications. Here are the main types of Java programs:

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 3|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

StandAlone Application Software(These are traditional desktop programs that run locally
on your computer.)

and

Applet Application Software (What is an Applet in Java?)

An applet is a small Java program that is embedded into a web page and runs in a browser
using a Java plugin or applet viewer. It was once used for creating interactive web content like
animations, games, or calculators.)

What are Java Tokens?

In Java, tokens are the smallest units of a program that the compiler understands. When you
write Java code, the compiler breaks it down into these tokens to analyze and execute it.

Types of Java Tokens

There are 6 main types of tokens in Java:

Token Type Description Example


Reserved words with special meaning in
1. Keywords int, class, if, for
Java
Names you give to variables, classes,
2. Identifiers myVar, Student, calculateSum
methods
3. Literals Fixed values assigned to variables 100, 'A', "Hello World", true
4. Operators Symbols that perform operations +, -, *, /, =, ==
Symbols used to separate code
5. Separators {, }, (, ), ;, ,
elements
// single-line comment, /* multi-
6. Comments Notes ignored by the compiler
line */

Primitive Data Types

These are the basic built-in types in Java. There are 8 primitive types:

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 4|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Type Size Description Example

byte 1 byte Whole numbers from -128 to 127 byte b = 100;

short 2 bytes Whole numbers from -32,768 to 32,767 short s = 5000;

int 4 bytes Whole numbers (default for integers) int x = 12345;

long 8 bytes Large whole numbers long l = 123456789L;

float 4 bytes Decimal numbers with 6–7 digits precision float f = 3.14f;

double 8 bytes Decimal numbers with 15 digits precision double d = 3.14159;

char 2 bytes A single Unicode character char c = 'A';

boolean 1 bit Logical value: true or false boolean isJavaFun = true;

What are Variables in Java?

A variable in Java is a container that holds data during the execution of a program. Each
variable has a type, which determines the kind of data it can store, and a name (identifier) used
to reference it.

Syntax: <datatype> identifier_name;

Types of Variables in Java

There are three main types of variables based on their scope and lifetime:

Variable Type Description Example Usage

Declared inside a method or block, only


java<br>void method()
1. Local Variables accessible within it. Not initialized by default, so
{<br> int x = 10;<br>}
you must assign a value before use.

2. Instance Declared inside a class but outside methods.


java<br>class Person
Variables (Non- Each object (instance) has its own copy. Default
{<br> String name;<br>}
static fields) values assigned if not initialized.

3. Static Variables Declared with the static keyword inside a class. java<br>class Counter

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 5|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Variable Type Description Example Usage

(Class variables) Shared among all instances of the class. {<br> static int
count;<br>}

How to Read Input from Keyboard in Java

The most common way to read user input from the keyboard in Java is by using the Scanner
class from the [Link] package.

Step-by-step Example to Read Input

1. Import the Scanner class:

import [Link];

2. Create a Scanner object:

Scanner scanner = new Scanner([Link]);

3. Use Scanner methods to read different types of input:

Method Reads Example Input


nextInt() An integer 123
nextDouble() A double (decimal) 3.14
nextLine() A full line (String) Hello world
next() A single word (String) Java
nextBoolean() Boolean (true or false) true

4. Close the Scanner (optional but recommended):

[Link]();

Complete Example:

import [Link];

public class InputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 6|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Enter your salary: ");


double salary = [Link]();

[Link]("Name: " + name);


[Link]("Age: " + age);
[Link]("Salary: " + salary);

[Link]();
}
}

Notes:

 Use nextLine() to read whole lines (including spaces).


 Use next() to read a single word (until the next space).
 When mixing nextLine() with other nextXYZ() methods, be careful with the newline
character left in the buffer.

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 7|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

What is Casting in Java?

Casting is the process of converting one data type into another. In Java, this is commonly
used to convert between primitive types or reference types (objects).

Types of Casting in Java

1. Primitive Type Casting

 Widening Casting (Automatic) — Implicit

Converting a smaller type to a larger type size. This happens automatically.

| Example: byte → short → int → long → float → double |

int i = 100;
double d = i; // int to double (widening) - automatic

 Narrowing Casting (Manual) — Explicit

Converting a larger type to a smaller type. This must be done manually using
parentheses.

double d = 100.04;
int i = (int) d; // double to int (narrowing) - explicit cast, decimal part lost

2. Reference Type Casting (Objects)

 Upcasting (Automatic)

Converting a subclass object to a superclass type. Safe and done automatically.

Animal a = new Dog(); // Dog is subclass of Animal

 Downcasting (Explicit)

Converting a superclass reference back to a subclass type. Must be done manually and
may throw a ClassCastException if the object is not actually of that subclass.

Animal a = new Dog();


Dog d = (Dog) a; // Downcasting, explicit

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 8|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Why Casting?

 To convert between compatible types when needed.


 To handle polymorphism with object references.
 To save memory or match method parameter types.

Casting Type Direction Automatic/Manual Example


Widening (Primitive) Smaller → Larger Automatic int → double
Narrowing (Primitive) Larger → Smaller Manual double → int
Subclass →
Upcasting (Reference) Automatic Dog → Animal
Superclass
Downcasting Superclass → Animal → Dog (with
Manual
(Reference) Subclass cast)

Operators in Java

Operators are special symbols or keywords in Java that perform operations on variables and
values. They are the building blocks of expressions.

Categories of Java Operators

Operator
Description Examples
Type
1. Arithmetic Perform mathematical calculations +, -, *, /, %
2. Relational Compare two values and return boolean result ==, !=, >, <, >=, <=
3. Logical Combine multiple boolean expressions && (AND), `
4.
Assign values to variables =, +=, -=, *=, /=, %=
Assignment
++, --, + (plus), - (minus), !
5. Unary Operate on a single operand
(NOT)
6. Bitwise Perform bit-level operations &, `
7. Ternary Shortcut for if-else in one line condition ? expr1 : expr2
Tests if an object is an instance of a
8. instanceof obj instanceof ClassName
class/interface

Additional Java Operators

Operator Description Example


:: (Method Used to refer to methods or
ClassName::methodName or
Reference constructors in functional
object::methodName
Operator) programming (Java 8+)

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 9|P a ge


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Operator Description Example


new Creates new objects or arrays new String("Hello")
Access members (methods/fields) of [Link]() or
. (Dot Operator)
objects or classes [Link]()
[] (Array Subscript
Access elements in an array arr[0]
Operator)
Used to group expressions or to
() (Parentheses) (a + b) * c, methodName()
invoke methods
-> (Lambda Used in lambda expressions (Java
(x) -> x * x
Operator) 8+)
@ (Annotation
Used to declare annotations in code @Override, @Deprecated
Marker)

Control Structures in Java

Control structures let you control the flow of your program — deciding which code runs and
how many times it runs.

1. Conditional Statements

a) if Statement

Runs a block of code if a condition is true.

if (condition) {
// code to execute if condition is true
}

b) if-else Statement

Runs one block if true, another if false.

if (condition) {
// if condition true
} else {
// if condition false
}

c) if-else if-else

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 10 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Tests multiple conditions in sequence.

if (condition1) {
// code 1
} else if (condition2) {
// code 2
} else {
// code 3
}

d) switch Statement

Selects code to execute based on the value of a variable (good for multiple discrete cases).

switch (variable) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}

2. Looping Statements

a) for Loop

Repeats code a fixed number of times.

for (int i = 0; i < 5; i++) {


[Link](i);
}

b) while Loop

Repeats code as long as the condition is true.

int i = 0;
while (i < 5) {
[Link](i);
i++;
}

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 11 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

c) do-while Loop

Like while, but runs the code at least once before checking the condition.

int i = 0;
do {
[Link](i);
i++;
} while (i < 5);

3. Branching Statements

a) break

Exits the nearest loop or switch immediately.

for (int i = 0; i < 10; i++) {


if (i == 5) break;
[Link](i);
}

b) continue

Skips the current iteration and jumps to the next loop iteration.

for (int i = 0; i < 10; i++) {


if (i % 2 == 0) continue; // skips even numbers
[Link](i); // prints odd numbers only
}

c) return

Exits from a method immediately and optionally returns a value.

int sum(int a, int b) {


return a + b;
}

Summary Table

Control Structure Purpose Syntax Example

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 12 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Control Structure Purpose Syntax Example

if Conditional execution if (condition) { }

if-else Two-way branching if (cond) { } else { }

switch Multi-way branching switch(var) { case: break; }

for Fixed repetition for(init; cond; update) { }

while Conditional repetition while(condition) { }

do-while Repeat at least once do { } while(condition);

break Exit loop/switch early break;

continue Skip current loop iteration continue;

return Exit method return value;

1. If-Else Example
int age = 20;

if (age >= 18) {


[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}

Output:
You are an adult.

2. If-Else If-Else Example


int marks = 75;

if (marks >= 90) {


[Link]("Grade: A");
} else if (marks >= 75) {

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 13 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else {
[Link]("Fail");
}

Output:
Grade: B

3. Switch Example
int day = 3;
String dayName;

switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Invalid day"; break;
}

[Link](dayName);

Output:
Wednesday

4. For Loop Example


for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}

Output:

makefile
CopyEdit
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 14 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

5. While Loop Example


int i = 1;
while (i <= 5) {
[Link]("Count: " + i);
i++;
}

Output:
Same as For loop above.

6. Do-While Loop Example


int i = 1;
do {
[Link]("Count: " + i);
i++;
} while (i <= 5);

Output:
Same as For and While loops above.

7. Break Statement Example


for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // exit loop when i is 6
}
[Link](i);
}

Output:

1
2
3
4
5

8. Continue Statement Example


for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skip printing 3

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 15 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

}
[Link](i);
}

Output:

CopyEdit
1
2
4
5

9. Return Statement Example


public class Demo {
public static int add(int a, int b) {
return a + b; // exit method and return sum
}

public static void main(String[] args) {


int sum = add(5, 10);
[Link]("Sum is: " + sum);
}
}

Output:
Sum is: 15

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 16 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Class

 A class is a blueprint or template for creating objects.


 It defines properties (variables/fields) and behaviors (methods/functions).
 Think of a class like a blueprint for a house; it defines the structure but isn’t the actual
house itself.

Example:
public class Car {
// Properties (fields)
String color;
int year;

// Method (behavior)
void drive() {
[Link]("The car is driving.");
}
}

🔹 Object

 An object is an instance of a class.


 When you create an object, you allocate memory and get a real “thing” based on the class
blueprint.
 Each object can have its own values for the class’s fields.

Creating an object from the Car class:


Car myCar = new Car();
[Link] = "Red";
[Link] = 2020;
[Link](); // Output: The car is driving.

🔹 Methods

 Methods define actions or behaviors for a class.


 They can take inputs (parameters), perform operations, and return results.
 Methods help organize code into reusable blocks.

Example Method with parameters and return type:

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 17 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

public class Calculator {


// Method to add two numbers and return the result
int add(int a, int b) {
return a + b;
}
}

Using the method:

Calculator calc = new Calculator();


int sum = [Link](5, 3);
[Link]("Sum: " + sum); // Output: Sum: 8

Summary
Concept Description Example

Class Blueprint defining properties and behaviors class Car { ... }

Object Instance of a class with actual data Car myCar = new Car();

Method Function inside a class performing a task void drive() { ... }

Sure! Here’s a clear explanation of Constructors in Java and their types:

What is a Constructor?

 A constructor is a special method used to initialize objects when they are created.
 It has the same name as the class and no return type (not even void).
 Automatically called when you use new to create an object.
 Used to set initial values for object properties.

Example of a Constructor
public class Car {
String color;
int year;

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 18 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

// Constructor
public Car(String color, int year) {
[Link] = color;
[Link] = year;
}
}

Creating an object:

Car myCar = new Car("Blue", 2022);


[Link]([Link]); // Output: Blue

Types of Constructors

1. Default Constructor

 Provided automatically by Java if you don’t write any constructor.


 Has no parameters and initializes object with default values.

Example:

public class Car {


String color;
int year;

// No constructor written here — Java provides a default one.


}

You can create object as:

Car myCar = new Car(); // Calls default constructor

2. No-Argument Constructor (No-Arg Constructor)

 A constructor you define explicitly without parameters.


 Usually used to set default values.

Example:

public class Car {


String color;
int year;

// No-argument constructor
public Car() {

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 19 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

color = "White";
year = 2020;
}
}

3. Parameterized Constructor

 A constructor with parameters to initialize the object with specific values.

Example (as above):

public Car(String color, int year) {


[Link] = color;
[Link] = year;
}

Important Notes

 If you write any constructor (no-arg or parameterized), Java won’t provide the default
constructor anymore.
 You can overload constructors (have multiple constructors with different parameter
lists).

Constructor Overloading Example:


public class Car {
String color;
int year;

// No-arg constructor
public Car() {
color = "Black";
year = 2019;
}

// Parameterized constructor
public Car(String color, int year) {
[Link] = color;
[Link] = year;
}
}

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 20 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

What is Method Overloading?

 Method Overloading means having multiple methods with the same name but
different parameter lists (different number, type, or order of parameters) in the same
class.
 It allows methods to perform similar but slightly different tasks, improving code
readability and usability.

Why Use Method Overloading?

 Makes your API cleaner by using the same method name for similar actions.
 You don’t have to come up with different names for methods that do related things.
 The compiler determines which method to call based on the arguments you pass.

Rules for Method Overloading

1. Same method name.


2. Different parameter list (number, type, or order).
3. Can have different return types (but return type alone is not enough to overload).
4. Can have different access modifiers.

Example of Method Overloading


public class Calculator {

// Adds two integers


public int add(int a, int b) {
return a + b;
}

// Adds three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Adds two double values


public double add(double a, double b) {
return a + b;
}
}

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 21 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Using the overloaded methods


Calculator calc = new Calculator();

[Link]([Link](5, 3)); // Calls add(int, int), Output: 8


[Link]([Link](5, 3, 2)); // Calls add(int, int, int),
Output: 10
[Link]([Link](5.5, 3.3)); // Calls add(double, double),
Output: 8.8

Summary
Method Signature Description

add(int a, int b) Adds 2 integers

add(int a, int b, int c) Adds 3 integers

add(double a, double b) Adds 2 doubles (decimal numbers)

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 22 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Arrays in Java

 An array is a container that holds a fixed number of values of the same type.
 Indexed starting from 0.
 Useful to store multiple values in a single variable.

Declaring and Initializing an Array


int[] numbers = new int[5]; // array of 5 integers, default values 0
numbers[0] = 10;
numbers[1] = 20;

Or initialize with values directly:

int[] numbers = {10, 20, 30, 40, 50};

Accessing Array Elements


[Link](numbers[2]); // Output: 30

2️⃣ String in Java

 String is a predefined class that represents immutable sequences of characters.


 Strings are objects in Java but can be used like primitive types due to special support.
 Immutable means once created, the string cannot be changed.

Creating Strings
String s1 = "Hello";
String s2 = new String("World");

Common String Methods

Method Description Example

length() Returns length of string "Hello".length() → 5

charAt(index) Returns char at specified index "Hello".charAt(1) → 'e'

substring(start, end) Returns substring "Hello".substring(1,4) → "ell"

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 23 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Method Description Example

equals() Checks if strings are equal "abc".equals("abc") → true

toUpperCase() Converts to uppercase "hello".toUpperCase() → "HELLO"

toLowerCase() Converts to lowercase "HELLO".toLowerCase() → "hello"

3️⃣ Predefined Classes (Commonly Used)

Java provides many useful classes in [Link] and other packages. Here are a few key ones:

a) Math Class

Contains math functions like sqrt, pow, random.

double result = [Link](25); // 5.0


int max = [Link](10, 20); // 20
double randomNum = [Link](); // random double between 0.0 and 1.0

b) Scanner Class (for input)

Used to read input from the user (keyboard).

import [Link];

Scanner scanner = new Scanner([Link]);


[Link]("Enter a number: ");
int num = [Link]();

c) Arrays Utility Class

Provides static methods to manipulate arrays (sorting, searching, printing).

import [Link];

int[] arr = {5, 2, 8, 1};


[Link](arr); // sorts array
[Link]([Link](arr)); // prints [1, 2, 5, 8]

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 24 | P a g e


MQI DEGREE COLLEGE
Chapter 1 – 6 Short Notes for Reference
OOP using JAVA Programming

Quick Summary Table


Concept Purpose Example

Array Store fixed-size sequence of same type int[] arr = {1,2,3};

String Immutable sequence of characters String s = "Hello";

Math Math functions [Link](16);

Scanner Reading user input Scanner sc = new Scanner([Link]);

Arrays Utility Array helper methods [Link](arr);

Anees Ahmed Ameer – Asst. Professor – MQI Degree College. 25 | P a g e

You might also like