0% found this document useful (0 votes)
14 views53 pages

Java Programming Basics Explained

The document provides an introduction to Java, covering its history, features, and core components such as JDK, JRE, and JVM. It explains Java's platform independence, syntax, data types, operators, variables, control structures, and looping statements, along with examples. Additionally, it discusses arrays and their manipulation, including finding maximum elements and reversing arrays.

Uploaded by

general23adi
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)
14 views53 pages

Java Programming Basics Explained

The document provides an introduction to Java, covering its history, features, and core components such as JDK, JRE, and JVM. It explains Java's platform independence, syntax, data types, operators, variables, control structures, and looping statements, along with examples. Additionally, it discusses arrays and their manipulation, including finding maximum elements and reversing arrays.

Uploaded by

general23adi
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

Introduction to Java

Module 1
History of Java

• Java was developed by James Gosling and his team at Sun Microsystems in
1991.
• Initially, it was called “Oak” (named after an oak tree outside Gosling’s
office).
• Later, renamed to Java (inspired by Java coffee).
Features of Java
• Simple – Easy to learn, reduced complexities.
• Object-Oriented – Supports OOPs (Encapsulation, Inheritance,
Polymorphism, Abstraction).
• Platform-Independent – “Write Once, Run Anywhere” with JVM &
Bytecode.
• Secure – No pointers, runs inside JVM.
• Robust – Strong memory management, exception handling,
garbage collection.
• Multithreaded – Multiple tasks at the same time.
JDK,JRE,JVM
JDK (Java Development Kit)
• JDK is the complete package for Java developers.
• It contains:
• JRE
• JVM
• Development tools (compiler javac, debugger, etc.)
• Needed for writing and running Java programs.
JRE (Java Runtime Environment)
• JRE provides everything needed to run Java programs.

• It contains:
JVM, Libraries & class files

• It does not have tools for development (like compiler).

• Used by end-users to run applications.


JVM (Java Virtual Machine)
• JVM is the engine that runs Java programs.

• It converts bytecode into machine code (understandable by the computer).

• JVM makes Java platform-independent.

• Also handles memory management and garbage collection.


Java is Platfrom Independent (WORA)
• Java is platform-independent because it is compiled into bytecode, not
machine code.
• First, JDK compiles a .java file into a .class file, converting Java code into
bytecode.
• Bytecode can run on any operating system that has a Java Virtual Machine
(JVM).
• The JVM converts bytecode into machine-specific code at runtime.
This allows the same Java program to run on Windows, Linux, Mac, or any
other OS without modification.
• Hence, Java follows the principle of “Write Once, Run Anywhere (WORA)”.
Syntax of Java Program

class ClassName {
public static void main(String[] args) {
// Code goes here
[Link]("Hello, World!");
}
}
Explaination:
• class ClassName → Every program must have a class.
• main() method → Entry point of the program (execution starts here).
• [Link]() → Used to print output on the screen.
• {} (curly braces) → Define the block of code.
• ; (semicolon) → Ends a statement.
Data Types in Java
• Data types define the kind of data a variable can store.
• Example: number, character, true/false.

• Types of Data Types


• Primitive (8 types) – basic, built-in • Non-Primitive – user-defined or complex
• byte → small numbers (1 byte)
• short → medium numbers (2 bytes)
• String (e.g., "Java")
• int → integers (4 bytes, default)
• long → large numbers (8 bytes) • Array (e.g., {1,2,3})
• float → decimals, less precision (4 bytes) • Classes & Objects
• double → decimals, more precision (8
bytes, default)
• char → single character (2 bytes)
• boolean → true/false (1 bit)
Operators in Java

Operators in java are special symbols that perform operations on variables or values.
These operators are essential in programming as they allow you to manipulate data
efficiently.

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Unary Operators
Arithmetic Operators

• Perform mathematical calculations.


• Symbols: +, -, *, /, %

Example:

int a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
Relational Operators

• Compare two values and return true or false.


• Symbols: ==, !=, >, <, >=, <=

Example:

int a = 5, b = 3;
[Link](a > b); // true
[Link](a == b); // false
Logical Operators

• Used to combine conditions.


• Symbols: && , || , !

Example:

boolean x = true, y = false;


[Link](x && y); // false
[Link](!x); // false
Assignment Operators

• Used to assign values to variables.


• Symbols: = , += , -=

Example:

int a = 10;
a += 5; // a = a + 5 → 15
int b = 5;
b -=2; //b=b-2 → 3
Unary Operators

• Increase or decrease value by 1.


• Symbols: ++ , -- (pre and post)

Example:

int a = 5;
[Link](++a); // 6 (pre-increment)
[Link](a++); // 6 (post-increment,then
a = 7)
Variables in Java

Definition
• A variable is a name given to a memory location that stores a value.
• The value can change during program execution.
• Think of a variable as a container that holds data.
Syntax
dataType variableName = value;

Example:

int age = 20;


String name = "Hello World";
Types of Variables in Java

In Java, variables are classified into three main types based on where they are
declared and how they are used.
1. Local Variables
• Declared inside a method, constructor, or block.
• Created when the method is called and destroyed when it ends.
• Must be initialized before use.
• Scope: only within that method/block.
Example:

void main() {
int num = 10; // local variable
[Link](num);
}
2. Instance Variables (Non-Static Variables)

• Declared inside a class but outside methods/constructors.


• Each object of the class gets its own copy.
• Default values are given if not initialized (e.g., 0 for int, null for objects).
• Accessed using the object.

Example:

class Student {
String name; // instance (non-static) variable
int age; // instance (non-static) variable
}
3. Static Variables (Class Variables)

• Declared with the keyword static inside a class.


• Shared by all objects of the class (only one copy exists).
• Memory allocated only once, when the class is loaded.
• Accessed using the class name.

Example:

class Student {
static String name= "Ramesh"; // static variable
}
Difference between Non-Static and Static Variables
Non-static variable Static variable
1 These variable should not be preceded by any static These variables are preceded by static keyword. Example:
keyword. Example:class A class A
{ {
int a; static int b;
} }
2 Memory is allocated for these variable whenever an Memory is allocated for these variable at the time of
object is created. loading of the class.
3 Memory is allocated multiple times whenever a new Memory is allocated for these variable only once in the
object is created. program.

4 Non-static variable also known as instance variable


Memory is allocated at the time of loading of class so these
because memory is allocated whenever an instance is
are also known as class variable.
created.

Static variable are common for every object (memory


5 Non-static variable are specific to an object. location is sharable by every object reference of the same
class).

6 Non-static variable can be accessed with object Static variable can be accessed with class reference.
reference. Syntax: obj_ref.variable_name Syntax: class_name.variable_name
Control Structures in Java

In Java, control structures decide the order in which statements are executed in a
program. They help us control the flow of execution based on conditions and
repetitions. There are three main types of control structures:

1. Decision-Making (Selection) Statements: if statement, if-else statement,if-else-if


ladder, switch statement

2. Looping Statements: for loop, while loop, do-while loop

3. Jump Statements: break, continue, return


Decision-Making Statements in Java

In Java, decision-making statements are used to execute a block of code only when certain
conditions are true.
They help programs make choices and follow different paths depending on the situation.

1. if Statement
The simplest form of decision-making.
• It checks a condition.
• If the condition is true → block of code runs.
• If false → block of code is skipped.

Syntax:
• if (condition) {
// code to execute if condition is true
• }
Example:
public class IfExample {
public static void main(String[] args) {
int age = 20;

if (age >= 18) {


[Link]("You are eligible to vote.");
}

[Link]("Program ended.");
}
}

Output:
You are eligible to vote.
2. if-else Statement

• Provides two choices.


• If condition is true → executes the first block.
• Otherwise → executes the else block.

Syntax:

if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:

public class IfElseExample {


public static void main(String[] args) {
int number = 10;

if (number % 2 == 0) {
[Link](number + " is Even.");
} else {
[Link](number + " is Odd.");
}
}
}

Output:
10 is Even
3. if-else-if Ladder

• Used when there are multiple conditions.


• Conditions are checked from top to bottom.
• As soon as one condition is true, its block executes, and the rest are skipped.

Syntax:

if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if all conditions are false
}
Example:

public class IfElseIfExample {


public static void main(String[] args) {
int marks = 75;

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 75) {
[Link]("Grade: A");
} else if (marks >= 60) {
[Link]("Grade: B");
} else if (marks >= 40) {
[Link]("Grade: C");
} else {
[Link]("Fail");
}
}
} Output:
Grade: A
4. Nested if Statement

• An if statement inside another if.


• Useful when checking multiple levels of conditions.

Syntax:

if (condition1) {
if (condition2) {
// code if both conditions are true
}
}
Example:
public class NestedIfExample {
public static void main(String[] args) {
int age = 25;
boolean hasVoterID = true;

if (age >= 18) {


if (hasVoterID) {
[Link]("You can vote.");
} else {
[Link]("You need a Voter ID to
vote.");
}
} else {
[Link]("You are not eligible to vote.");
}
Output:
} You can vote.
}
5. switch Statement
• Used when we need to choose one option from many.
• Works with:
• int, byte, short, char (primitive types)
• String (since Java 7)
• enum (special class for constants)

Syntax:
switch(expression) {
case value1:
// code for case 1
break;
case value2:
// code for case 2
break;
...
default:
// code if no cases match
}
Example:
public class SwitchExample {
public static void main(String[] args) {
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;
case 6:
[Link]("Saturday");
break;
Looping Statements in Java

In Java, loops are used to execute a block of code repeatedly as long as a


condition is true.
They help avoid writing the same code multiple times.

They are:
1. for loop
2. do while loop
3. while loop
for Loop

• Best used when you know how many times you want to repeat.
• Syntax includes initialization, condition, and update in one line.

Syntax:

for(initialization; condition; update) {


// code to be executed
}
Example:

public class ForLoopExample {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
}
}

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
while Loop

• Used when the number of iterations is not fixed.


• The condition is checked before the loop body executes. That is why it is called an
Entry Controlled Loop (condition checked at entry)

Syntax:

while(condition) {
// code to be executed
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link]("Number: " + i);
i++;
}
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
do-while Loop

• Similar to while loop, but executes at least once even if the condition is false.
• Condition is checked after the loop body. That is why it is called an Exit Controlled
Loop (condition checked at exit).

Syntax:

do {
// code to be executed
} while(condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
[Link]("Value: " + i);
i++;
} while (i <= 5);
}
}

Output:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Arrays in Java

What is an Array?

• An array is a collection of similar data types.


• Stores multiple values in a single variable.
• Each element is accessed using an index (starting from 0).

Syntax:

dataType[] arrayName = new dataType[size];


Example 1: Basic Array

public class ArrayExample {


public static void main(String[] args) {
int numbers[] = new int[5]; // array of size 5

// Storing values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Printing values using for loop


for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Array Manipulation

Finding Maximum Element


public class ArrayMaxExample {
public static void main(String[] args) {
int arr[] = {12, 45, 67, 23, 89, 34};
int max = arr[0];

for (int num : arr) {


if (num > max) {
max = num;
}
}

[Link]("Maximum value: " + max);


}
}

Output:
Maximum value: 89
• Reversing an Array
public class ArrayReverseExample {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};

[Link]("Original Array:");
for (int num : arr) {
[Link](num + " ");
}

[Link]("\nReversed Array:");
for (int i = [Link] - 1; i >= 0; i--) {
[Link](arr[i] + " ");
}
} Output:
} Original Array:
12345
Reversed Array:
54321
Strings in Java
What is a String?

1) A String is a sequence of characters.


2) In Java, Strings are objects of the String class.
3) Strings are immutable which means that once a String object is created, its value
cannot be changed. If you want to modify a string a new String object is created and
the original remains unchanged.

There are two ways to create a string in Java:

1) Using String Literal 2) Using new keyword


Syntax: Syntax:
String str = "Hello"; String str = new String("Hello");
Example :

Basic String
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello World";
[Link](greeting);
}
}

Output:
Hello World
String Methods
Java provides many built-in methods to work with text data in a string.
Here are the most important and commonly used methods:

1. length()
• Finds the number of characters in a string.
String str = "Java Programming";
[Link]([Link]());
Output: 16

2. charAt(int index)
• Returns the character at a given index (starts from 0).
String str = "Hello";
[Link]([Link](1));

Output: e
3. substring()
• Extracts part of a string.
String str = "Hello Java";
[Link]([Link](6)); // from index 6
[Link]([Link](0, 5)); // from index 0 to 4

Output:
Java
Hello

4. toUpperCase() / toLowerCase()
• Converts string to uppercase or lowercase.
String str = "Java";
[Link]([Link]());
[Link]([Link]());

Output:
JAVA
java
5. equals() / equalsIgnoreCase()
• Compares two strings.
String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // case-sensitive
[Link]([Link](s2));// case-insensitive

Output:
false
true

6. concat()
• Joins two strings.
String s1 = "Hello";
String s2 = "World";
[Link]([Link](" " + s2));

Output: Hello World


7. contains()
• Checks if the string contains given text.
String str = "Java Programming";
[Link]([Link]("Java"));
[Link]([Link]("Python"));

Output:
true
false

8. indexOf() / lastIndexOf()
• Finds index of first or last occurrence of a character or word.
String str = "Programming";
[Link]([Link]("g"));
[Link]([Link]("g"));

Output:
3
10
9. trim()
• Removes spaces from beginning and end.
String str = " Hello Java ";
[Link]([Link]());

Output: Hello Java

10. replace()
• Replaces one character with another.
String str = "Java";
[Link]([Link]('a', 'o'));

Output: Jovo
Summary

• length() → total characters


• charAt() → character at index
• substring() → part of string
• toUpperCase()/toLowerCase() → change case
• equals()/equalsIgnoreCase() → compare strings
• concat() → join strings
• contains() → check if text exists
• indexOf()/lastIndexOf() → position of text
• trim() → remove spaces
• replace() → replace character

You might also like