0% found this document useful (0 votes)
3 views85 pages

java 1

The document provides an introduction to Java, covering its history, applications, and advantages such as platform independence and community support. It includes installation instructions, Java syntax, data types, operators, and examples of basic programming concepts like loops, conditionals, and arrays. Additionally, it explains access modifiers and various operators in Java, along with sample code snippets for practical understanding.

Uploaded by

neilnickson2007
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)
3 views85 pages

java 1

The document provides an introduction to Java, covering its history, applications, and advantages such as platform independence and community support. It includes installation instructions, Java syntax, data types, operators, and examples of basic programming concepts like loops, conditionals, and arrays. Additionally, it explains access modifiers and various operators in Java, along with sample code snippets for practical understanding.

Uploaded by

neilnickson2007
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

Programming in Java

UNIT 1
Introduction to Java
• Java is a high level programming language - 1995.
• It is owned by Oracle, and more than 3 billion devices run
Java.
It is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
Why Use Java?
• Different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• Most popular programming languages in the world
• Large demand in the current job market
• Easy to learn and simple to use
• Open-source and free
• Secure, fast and powerful
• It has huge community support (tens of millions of developers)
• Object oriented language
• Close to C++ and C#
Check if java is already installed?
• Open Command Prompt
• Type
java -version
• You should see
java version "21.x.x"
• Type
javac -version
• You should see
javac 21.x.x
Step – by – step Installation Procedure
• Step 1: Go to Java Download Website
[Link] Google
[Link]:
“Download JDK Oracle”
[Link] on this link:
👉 [Link]
• Step 2: Download Java for Windows
[Link] the page, you’ll see a version like:
Java SE 21 or Java SE 17
[Link] JDK Download
[Link] down to Windows section
[Link] on:
1. Windows x64 Installer (.exe file)
[Link] the file
• Step 3: Install Java
[Link]-click the downloaded .exe file
[Link] Next
[Link]… then click Close when done
How Java Executes This Program
[Link]


Java Compiler (javac [Link])


[Link] (Bytecode)


JVM (Java Virtual Machine)


Output:
Hello World
Java Syntax
[Link]
public class Main
{
public static void main(String[] args)
{
[Link]("Hello World");
}
}

Output: Hello World


public class Main
{
public static void main(String[] args)
{
[Link]("Hello World!");
[Link]("I am learning Java.");
[Link]("It is awesome!");
}
}
Output: Hello World!
I am learning Java.
It is awesome!
[Link](This sentence will produce an error);

[Link]("Hello World! ");

[Link]("I will print on the same line.");

[Link](3);

[Link](358);

[Link](50000);
Check Palindrome String
public class PalindromeString {
public static void main(String[] args) {
String word = "madam";
String reversed = "";

for (int i = [Link]() - 1; i >= 0; i--) {


reversed += [Link](i);
}

if ([Link](reversed))
[Link](word + " is a palindrome");
else
[Link](word + " is not a palindrome");
}
}
Print Even Numbers from 1 to 20
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
[Link](i);
}
}
}
}
Find ASCII Value of a Character
public class AsciiValue {
public static void main(String[] args) {
char ch = 'A';
int ascii = ch;

[Link]("ASCII value of " + ch + " is: " + ascii);


}
}
Count Digits in a Number
public class CountDigits {
public static void main(String[] args) {
int number = 12345;
int count = 0;

while (number != 0) {
number /= 10;
count++;
}

[Link]("Number of digits: " + count);


}
}
Sum of Natural Numbers up to N
public class SumNatural {
public static void main(String[] args) {
int n = 10;
int sum = 0;

for (int i = 1; i <= n; i++) {


sum += i;
}

[Link]("Sum of first " + n + " natural numbers: " + sum);


}
}
Check Whether Character is Vowel or
Consonant
public class VowelCheck {
public static void main(String[] args) {
char ch = 'e';

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {


[Link](ch + " is a vowel");
} else {
[Link](ch + " is a consonant");
}
}
}
Print Numbers from 10 to 1 (Reverse Order)
public class ReverseOrder {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
[Link](i);
}
}
}
Check Whether a Year is a Century Year
public class CenturyCheck {
public static void main(String[] args) {
int year = 1900;

if (year % 100 == 0) {
[Link](year + " is a Century Year");
} else {
[Link](year + " is NOT a Century Year");
}
}
}
Java Program Execution Flow
You write Java Program

javac
(Java Compiler)

Bytecode (.class file)

JVM
(Java Virtual Machine)

Machine Code

CPU Executes

Output
Java Data Types
• Byte
• Short
• Int
• Long
• Float
• Double
• Char
• Boolean.
• String
• Array
• Class
• Interface
Data Type Real-Time Example
byte Student age = 20
short College ID = 25001
int Employee salary = 50000
long India's population = 1450000000L
float Body temperature = 36.8f
double Value of π = 3.1415926535
char Blood group letter = 'B'
boolean Exam result = true (Pass)
String Student name = "Ravi"
Array Marks = {80, 85, 90, 95}
Java Tokens
• Keywords
• Identifiers
• Literals
• Operators
• Separators
• Comments
Token Description Examples

Reserved words that have predefined


class, public, static, void, int, if, else, for,
Keywords meanings in Java. They cannot be used
while, return, new, this
as variable names.

Names given by the programmer to studentName, age, totalMarks, Main,


Identifiers
variables, methods, classes, and objects. calculateSum(), Employee

Fixed values directly written in the


Literals 100, 3.14, 'A', "Hello", true, false, null
program.

Symbols used to perform operations on


Operators +, -, *, /, %, ==, !=, >, <, &&, `
variables and values.

Symbols used to separate different parts


Separators (){}[];,.
of a Java program.
Access Modifiers
• Private
• Default
• Public
• Protected
private – Only accessible inside the same
class
public class PrivateExample
{
private int number = 5;

private void show()


{
[Link]("Private number: " + number);
}

public static void main(String[] args)


{
PrivateExample obj = new PrivateExample();
[Link]();
}
}
Default – No keyword, accessible only in same
package
class DefaultExample
{
void display()
{
[Link]("This is Default Access Modifier");
}
}

public class TestDefault


{
public static void main(String[] args)
{
DefaultExample obj = new DefaultExample();
[Link]();
}
}
protected – Accessible in same package +
subclasses
class Animal
{
protected void sound()
{
[Link]("Animal makes sound");
}
}

public class Dog extends Animal


{
public static void main(String[] args)
{
Dog obj = new Dog();
[Link]();
}
}
public – Accessible from anywhere
public class PublicExample
{
public void greet()
{
[Link]("Hello from PublicExample");
}
}
public class TestPublic
{
public static void main(String[] args)
{
PublicExample obj = new PublicExample();
[Link]();
}
}
Operators in Java
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Unary Operators
• Bitwise Operators
• Ternary Operators
• Instanceof Operators
Arithmetic Operators
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10, b = 3;

[Link]("a + b = " + (a + b)); // Addition


[Link]("a - b = " + (a - b)); // Subtraction
[Link]("a * b = " + (a * b)); // Multiplication
[Link]("a / b = " + (a / b)); // Division
[Link]("a % b = " + (a % b)); // Modulus
}
}
Relational Operators
public class RelationalOperators {
public static void main(String[] args) {
int a = 10, b = 20;

[Link]("a == b: " + (a == b)); // Equal to


[Link]("a != b: " + (a != b)); // Not equal to
[Link]("a > b: " + (a > b)); // Greater than
[Link]("a < b: " + (a < b)); // Less than
[Link]("a >= b: " + (a >= b)); // Greater than or equal to
[Link]("a <= b: " + (a <= b)); // Less than or equal to
}
}
Logical Operators
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true, b = false;

[Link]("a && b: " + (a && b)); // Logical AND


[Link]("a || b: " + (a || b)); // Logical OR
[Link]("!a: " + !a); // Logical NOT
}
}
Assignment Operators
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10, b = 5;

a += b; // a = a + b
[Link]("a += b: " + a);

a -= b; // a = a - b
[Link]("a -= b: " + a);

a *= b; // a = a * b
[Link]("a *= b: " + a);

a /= b; // a = a / b
[Link]("a /= b: " + a);

a %= b; // a = a % b
[Link]("a %= b: " + a);
}
}
Unary Operators
public class UnaryOperators {
public static void main(String[] args) {
int a = 10;

[Link]("a: " + a);


[Link]("++a: " + ++a); // Pre-increment
[Link]("a++: " + a++); // Post-increment
[Link]("a after a++: " + a);

[Link]("--a: " + --a); // Pre-decrement


[Link]("a--: " + a--); // Post-decrement
[Link]("a after a--: " + a);

[Link]("!true: " + !true); // Logical NOT


}
}
Bitwise Operators
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5, b = 3;

[Link]("a & b: " + (a & b)); // Bitwise AND


[Link]("a | b: " + (a | b)); // Bitwise OR
[Link]("a ^ b: " + (a ^ b)); // Bitwise XOR
[Link]("~a: " + ~a); // Bitwise NOT

[Link]("a << 1: " + (a << 1)); // Left shift


[Link]("a >> 1: " + (a >> 1)); // Right shift
[Link]("a >>> 1: " + (a >>> 1)); // Unsigned right shift
}
}
Ternary Operator
public class TernaryOperator {
public static void main(String[] args) {
int a = 10, b = 20;

// Using ternary operator


String result = (a > b) ? "a is greater" : "b is greater";
[Link](result);
}
}
Instanceof Operator
public class InstanceofOperator {
public static void main(String[] args) {
String str = "Hello, Java!";

// Check if object is instance of String class


if (str instanceof String) {
[Link]("str is an instance of String");
}

// Check if object is instance of Integer class


Integer num = 100;
if (num instanceof Integer) {
[Link]("num is an instance of Integer");
}
}
}
public class InstanceofOperator {
public static void main(String[] args) {
String str = "Hello, Java!"; // Declaring a String object

// Check if 'str' is an instance of the Integer class (invalid check)


if (str instanceof Integer) {
[Link]("str is an instance of Integer");
} else {
[Link]("str is not an instance of Integer");
}

Integer num = 100; // Declaring an Integer object


// Check if 'num' is an instance of the String class (invalid check)
if (num instanceof String) {
[Link]("num is an instance of String");
} else {
[Link]("num is not an instance of String");
}
}
}
Arrays in Java
Fixed number of elements of the same data type.
Declaring and Creating Arrays
int[] numbers = new int[5];
(or)
int numbers[] = new int[5];

Initializing Arrays
int[] marks = {90, 80, 70, 85, 95};

Accessing Array Elements


[Link](marks[0]);
[Link](marks[4]);
Logic of Using Arrays
[Link] array – tell Java how many values you want to store.
[Link] values – assign values to each index.
[Link] values – read or change the values using the index.
Create and Use a 1D Array (Single row of values)
public class OneDArray {
public static void main(String[] args) {
// Step 1: Create an array of 5 integers
int[] marks = new int[5];

// Step 2: Store values


marks[0] = 90;
marks[1] = 85;
marks[2] = 75;
marks[3] = 80;
marks[4] = 95;

// Step 3: Access values using loop


[Link]("Marks of 5 students:");
for (int i = 0; i < 5; i++) {
[Link]("Student " + (i + 1) + ": " + marks[i]);
}
}
}
Output
Marks of 5 students:
Student 1: 90
Student 2: 85
Student 3: 75
Student 4: 80
Student 5: 95
Two-Dimensional Array – Like a table

Subject 1 Subject 2 Subject 3


Student 1 90 85 88
Student 2 70 75 80
public class TwoDArray {
public static void main(String[] args) {
int[][] marks = {
{90, 85, 88},
{70, 75, 80}
};

// 2 rows (students), 3 columns (subjects)


for (int i = 0; i < [Link]; i++) {
[Link]("Student " + (i + 1) + " Marks:");
for (int j = 0; j < marks[i].length; j++) {
[Link]("Subject " + (j + 1) + ": " + marks[i][j]);
}
[Link]();
}
}
}
Output
Student 1 Marks:
Subject 1: 90
Subject 2: 85
Subject 3: 88

Student 2 Marks:
Subject 1: 70
Subject 2: 75
Subject 3: 80
public class Simple2DArray {
public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] numbers = {
{1, 2},
{3, 4}
};

// Print the 2D array


[Link]("2D Array Elements:");
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < numbers[i].length; j++) {
[Link](numbers[i][j] + " ");
}
[Link](); // new line after each row
}
}
}
3D Array
3D array is like a cube or a group of 2D tables.
int[][][] arr = new int[2][2][2];
total elements = 2 × 2 × 2 = 8 elements
3D Array Java Program
public class ThreeDArrayExample {
public static void main(String[] args) {

// [Class][Student][Subject]
int[][][] marks = {
{ // Class 1
{85, 90, 88}, // Student 1
{78, 82, 80} // Student 2
},
{ // Class 2
{92, 89, 95}, // Student 1
{75, 70, 68} // Student 2
}
};
// Display all marks
for (int i = 0; i < [Link]; i++) {
[Link]("Class " + (i + 1));

for (int j = 0; j < marks[i].length; j++) {


[Link]("Student " + (j + 1) + ": ");

for (int k = 0; k < marks[i][j].length; k++) {


[Link](marks[i][j][k] + " ");
}

[Link]();
}

[Link]();
}
}
}
Output
Class 1
Student 1: 85 90 88
Student 2: 78 82 80

Class 2
Student 1: 92 89 95
Student 2: 75 70 68
Common Array Functions
public class ArrayFunctions {
public static void main(String[] args) {
// Step 1: Declare and initialize array
int[] numbers = {40, 10, 30, 20};

// 1. Print original array


[Link]("Original array: " + [Link](numbers));

// 2. Sort the array


[Link](numbers);
[Link]("Sorted array: " + [Link](numbers));

// 3. Search for an element (30) using binary search


int index = [Link](numbers, 30);
[Link]("Index of 30: " + index);
// 4. Copy part of the array (first 3 elements)
int[] copy = [Link](numbers, 3);
[Link]("Copied first 3 elements: " + [Link](copy));

// 5. Fill an array with a value


int[] filled = new int[5];
[Link](filled, 100);
[Link]("Filled array with 100: " + [Link](filled));

// 6. Compare two arrays


boolean isEqual = [Link](numbers, copy);
[Link]("numbers and copy are equal? " + isEqual);

// 7. Copy range of elements (index 1 to 3)


int[] rangeCopy = [Link](numbers, 1, 4);
[Link]("Copied range (index 1 to 3): " + [Link](rangeCopy));
}
}
Output
Original array: [40, 10, 30, 20]
Sorted array: [10, 20, 30, 40]
Index of 30: 2
Copied first 3 elements: [10, 20, 30]
Filled array with 100: [100, 100, 100, 100, 100]
numbers and copy are equal? false
Copied range (index 1 to 3): [20, 30, 40]
Matrix Addition
public class MatrixAddition {
public static void main(String[] args) {
// Step 1: Define two 2x2 matrices
int[][] A = {
{1, 2},
{3, 4}
};

int[][] B = {
{5, 6},
{7, 8}
};

// Step 2: Create a result matrix of the same size


int[][] result = new int[2][2];
// Step 3: Add elements from both matrices
for (int i = 0; i < 2; i++) { // rows
for (int j = 0; j < 2; j++) { // columns
result[i][j] = A[i][j] + B[i][j];
}
}

// Step 4: Display the result matrix


[Link]("Result of Matrix Addition:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
[Link](result[i][j] + " ");
}
[Link](); // new line after each row
}
}
}
Output
Result of Matrix Addition:
68
10 12
Control Structures in Java
1. Decision-Making Statements
if, if...else, else if
Switch
2. Looping Statements
for loop
while loop
Do while loop
For each loop
3. Jump Statements
break in loop
continue in loop
return in method
public class DecisionExample {

public static void main(String[] args) {

int number = 10;

// if

if (number > 0) {

[Link]("Number is positive");

// if-else

if (number % 2 == 0) {

[Link]("Even number");

} else {

[Link]("Odd number");

// if-else if-else

if (number < 0) {

[Link]("Negative number");

} else if (number == 0) {

[Link]("Zero");

} else {

[Link]("Positive number");

}
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;
default: [Link]("Other day");
}
}
}
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
}
}
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
[Link]("i = " + i);
i++;
}
}
}
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
[Link]("Number: " + i);
i++;
} while (i <= 2);
}
}
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int num : numbers) {
[Link]("Value: " + num);
}
}
}
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
[Link]("i = " + i);
}
}
}
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
[Link]("i = " + i);
}
}
}
public class ReturnExample {
public static void main(String[] args) {
[Link]("Start");
showMessage();
[Link]("End");
}

public static void showMessage() {


[Link]("Inside method");
return; // Exit the method
}
}
public class ForEachExample1 {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {


[Link]("Number: " + num);
}
}
}
public class ForEachExample2 {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango"};

for (String fruit : fruits) {


[Link]("Fruit: " + fruit);
}
}
}
Strings in Java
• Represent sequences of characters
Creating Strings
String s1 = "Hello"; // Using string literal
String s2 = new String("World"); // Using new keyword
Common String Methods
Method Description Example Output

length() Returns length of string "hello".length() 5


Returns char at given
charAt(index) "hello".charAt(1) 'e'
index
substring(start, end) Extracts substring "hello".substring(1, 4) "ell"
equals(str) Compares contents "abc".equals("abc") true
Case-insensitive "Hello".equalsIgnoreCa
equalsIgnoreCase(str) true
compare se("hello")
toUpperCase() Converts to uppercase "java".toUpperCase() "JAVA"
toLowerCase() Converts to lowercase "JAVA".toLowerCase() "java"
concat(str) Concatenates strings "Hi".concat(" there") "Hi there"
replace(a, b) Replaces characters "apple".replace('p','b') "abble"
Removes leading/
trim() " java ".trim() "java"
trailing spaces
String Comparison
public class StringCompare {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
String c = new String("Java");

[Link](a == b); // true (same reference from string pool)


[Link](a == c); // false (different object)
[Link]([Link](c)); // true (same content)
}
}
String Concatenation
public class StringConcat {
public static void main(String[] args) {
String name = "John";
String msg = "Hello, " + name + "!";
[Link](msg);
}
}
Java Program: Various String Operations
public class StringOperations {
public static void main(String[] args) {
// 1. String creation
String str1 = "Java Programming";
String str2 = new String(" Welcome to Java! ");

// 2. length()
[Link]("Length of str1: " + [Link]());

// 3. charAt()
[Link]("Character at index 5: " + [Link](5));

// 4. substring()
[Link]("Substring from index 5 to 11: " + [Link](5, 12));

// 5. toUpperCase() and toLowerCase()


[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
// 6. equals() and equalsIgnoreCase()
[Link]("Equals 'Java Programming'? " + [Link]("Java Programming"));
[Link]("Equals Ignore Case: " + [Link]("java programming"));

// 7. trim()
[Link]("Trimmed str2: '" + [Link]() + "'");

// 8. replace()
[Link]("Replace 'Java' with 'Python': " + [Link]("Java", "Python"));

// 9. indexOf()
[Link]("Index of 'Pro': " + [Link]("Pro"));

// 10. split()
String[] words = [Link](" ");
[Link]("Split words:");
for (String word : words) {
[Link](word);
}
// 11. concat()
String str3 = "Language";
[Link]("Concatenated String: " + [Link](" " + str3));

// 12. startsWith() and endsWith()


[Link]("Starts with 'Java'? " + [Link]("Java"));
[Link]("Ends with 'ing'? " + [Link]("ing"));
}
}
Output:
• Length of str1: 16
• Character at index 5: P
• Substring from index 5 to 11: Progra
• Uppercase: JAVA PROGRAMMING
• Lowercase: java programming
• Equals 'Java Programming'? true
• Equals Ignore Case: true
• Trimmed str2: 'Welcome to Java!'
• Replace 'Java' with 'Python': Python Programming
• Index of 'Pro': 5
• Split words:
• Java
• Programming
• Concatenated String: Java Programming Language
• Starts with 'Java'? true
• Ends with 'ing'? true
String BufferClass
• StringBuffer class in Java is used to create mutable (modifiable)
sequences of characters.
• Unlike String, which is immutable, StringBuffer allow us to change the
contents without creating a new object every time.

Example:
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer("Hello");
Example for String Class
public class StringConcatExample {
public static void main(String[] args) {
String str1 = "Hello";
[Link](" World"); // Not stored
[Link]("Without storing concat result: " + str1); // Output: Hello

// Now storing the result


String str2 = [Link](" World");
[Link]("After storing concat result: " + str2); // Output: Hello World
}
}
Output
Without storing concat result: Hello
After storing concat result: Hello World
Difference between String Class and String Buffer
Class public class StringVsStringBuffer {
public static void main(String[] args) {

// Using String (Immutable)


String str = "Hello";
[Link](" World");
[Link]("String result: " + str);

// Using StringBuffer (Mutable)


StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link]("StringBuffer result: " + sb);
}
}
Append Strings Using StringBuffer
public class AppendExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Welcome");
[Link](" to Java!");
[Link]("Result: " + sb); }
}
Reverse a String Using StringBuffer
public class ReverseExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link]();
[Link]("Reversed: " + sb);
}
}
Insert Text into a String
public class InsertExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("JavaProgramming");
[Link](4, " ");
[Link]("After insert: " + sb); }
}
Replace Part of the String
public class ReplaceExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("I love Python");
[Link](7, 13, "Java");
[Link]("After replace: " + sb); // Output: I love Java
}
}
Delete Characters from a StringBuffer
public class DeleteExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("UnnecessaryText");
[Link](0, 11);
[Link]("After delete: " + sb);
}

You might also like