Unit - 1
Unit - 1
Syllabus
• Procedural vs. object-oriented development,
• basic concepts of object-oriented programming,
• applications and benefits of OOP
• Java Basics: Java as Object-oriented Programming Language
• History of Java,
• Features of Java,
• Difference between Java and C++,
• Java Architecture (JDK, JVM, JRE), Java Tokens:
• Basics of Java programming: Data types, Literals, Variables, Scope and
lifetime of variables,
• Operators. Control Structures including selection, Looping, Arrays.
Procedural Oriented Programming Object-Oriented Programming
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
basic concepts of object-oriented programming
• The Scanner class is used to get user input, and it is found in the
java.util package.
• To use the Scanner class, create an object of the class and use any of
the available methods found in the Scanner class documentation.
• Input Types
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
• import java.util.Scanner;
• public class circle
• {
• public static void main(String args[])
• {
• int x, y, sum;
• Scanner sc=new Scanner(System.in);
• System.out.print("Enter the first number: ");
• x= sc.nextInt();
• System.out.print("Enter the second number: ");
• y=sc.nextInt();
• sum=x+y;
• System.out.println("The sum of two numbers x and y is: " + sum);
• }
• }
Java OOP(Object Oriented Programming) Concepts
Inheritance from C++ supports multiple inheritance, meaning a Java allows multiple inheritance
Multiple Sources class can inherit from multiple base classes. through interfaces,
Difference b/w C++ and Java
Basic C++ Java
Operator Overloading
C++ supports both method overloading Java supports only method
and operator overloading overloading
Pointers C++ includes pointers, which allow direct memory Java does not have pointers
manipulation and access.
Level of Programming C++ allows both high-level and low-level Java is primarily a high-level
programming, making it suitable for system-level language with a focus on simplicity
and performance-critical tasks. and portability.
Structure and Union C++ supports structures and unions, which are Java does not have built-in support
used for grouping related data members. for structures or unions; instead, it
uses classes for data encapsulation.
Garbage C++ needs manual garbage memory Java has an automatic
collection clearance garbage collector
• 2. Floating-Point Literals
• Represent decimal numbers.
• Can be written in standard or scientific notation.
• Examples:
• double decimal = 3.14; // Standard decimal notation
• double scientific = 2.5e-3; // Scientific notation (2.5 × 10^-3)
• By default, floating-point literals are of type double. For float, append F or f:
• float pi = 3.14F;
• 3. Character Literals
• Represent a single Unicode character.
• Enclosed in single quotes (').
• Examples:
• char letter = 'A';
• char escape = '\n'; // Escape sequence for newline
• char unicode = '\u0041'; // Unicode for 'A'
• 4. String Literals
• Represent a sequence of characters.
• Enclosed in double quotes (").
• Examples:
• String greeting = "Hello, World!";
• String escape = "This is a \"quote\"."; // Escaping double quotes
• Strings are immutable in Java.
• 5. Boolean Literals
• Represent logical values.
• Only two possible values: true or false.
• Examples:
• boolean isJavaFun = true;
• boolean isRaining = false;
• 6. Null Literal
• Represents a null reference (no object).
• Used for object references.
• Example:
• String str = null; // No object is assigned to 'str'
• 7. Class Literals
• Represents a Class object for a specific type.
• Formatted as <type>.class.
• Example:
• Class<?> clazz = String.class; // Represents the String class
• public class LiteralsExample {
• public static void main(String[] args) {
• // Integer literals
• int decimal = 42;
• long bigNumber = 1234567890L;
• // Floating-point literals
• double pi = 3.14159;
• float gravity = 9.8F;
• // Character literals
• char grade = 'A';
• char newline = '\n';
• // String literals
• String message = "Hello, Java!";
• // Boolean literals
• boolean isJavaEasy = true;
• // Null literal
• String empty = null;
• // Output
• System.out.println(decimal);
• System.out.println(bigNumber);
• System.out.println(pi);
• System.out.println(gravity);
• System.out.println(grade);
• System.out.println(message);
• System.out.println(isJavaEasy);
• System.out.println(empty);
• }
•}
• Datatypes : data types define the type of data that a variable can hold.
• Java is a strong-typed language, which means that the data type of a variable must be declared before it
can be used. Java data types are broadly categorized into two groups:
• Primitive Data Types
• Non-Primitive Data Types (Reference Types)
• 1. Primitive Data Types
• Primitive data types are the most basic data types in Java. They are predefined by the language and are
not objects. There are 8 primitive data types in Java, divided into four categories:
• a. Integer Types : Store whole numbers (positive, negative, or zero).
• Types:
• byte: 8-bit signed integer. Range: -128 to 127.
• short: 16-bit signed integer. Range: -32,768 to 32,767.
• int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
• long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
• Examples:
• byte b = 100;
• short s = 1000;
• int i = 100000;
• long l = 1000000000L; // Use 'L' or 'l' for long literals
• b. Floating-Point Types : Store decimal numbers.
• Types:
• float: 32-bit single-precision floating-point. Range: ~±3.4e38.
• double: 64-bit double-precision floating-point. Range: ~±1.7e308.
• Examples:
• float f = 3.14F; // Use 'F' or 'f' for float literals
• double d = 3.14159;
char c;
}
• // Define a class named "Student"
• class student
• {
• // Instance variables
• private String name; // Stores the name of the student
• private int age; // Stores the age of the student
• private double gpa; // Stores the GPA of the student
• // Constructor to initialize instance variables
• public student(String name, int age, double gpa)
• {
• this.name = name;
• this.age = age;
• this.gpa = gpa;
• }
• // Method to display student details
• public void displayDetails()
• {
• System.out.println("Name: " + name);
• System.out.println("Age: " + age);
• System.out.println("GPA: " + gpa);
• }
• public class student
• {
• /* declaration of instance variables. */
• public String name; //public instance
• String division; //default instance
• private int age; //private instance
• /* Constructor that initialize an instance variable. */
• public student(String sname)
• {
• name = sname;
• }
• /* Method to intialize an instance variable. */
• public void setDiv(String sdiv)
• {
• division = sdiv;
• }
• /* Method to intialize an instance variable. */
• public void setAge(int sage)
• {
• age = sage;
• }
• /* Method to display the values of instance variables. */
• public void printstud()
• {
• System.out.println("Student Name: " + name );
• System.out.println("Student Division: " + division);
• System.out.println("Student Age: " + age);
• }
•
• /* Driver Code */
• public static void main(String args[])
• {
• student s = new student("Monica");
• s.setAge(14);
• s.setDiv("B");
• s.printstud();
• }
• }
• // Main class to test the Student class
• System.out.println("\nStudent 2 Details:");
• student2.displayDetails();
• }
• }
Static variable example
• class Test{
• // static variable in Test class
• static int var = 10;
• }
• class Geeks
• {
• public static void main (String[] args) {
• // accessing the static variable
• System.out.println("Static Variable : "+Test.var);
• }
• }
• public class student {
• // static variable
• static int age;
• // static method
• static void display() {
• System.out.println("Static Method");
• }
• public static void main(String[] args) {
• public SumExample
•{
• public void calculateSum() {
• int a = 5; // local variable
• int b = 10; // local variable
• int sum = a + b;
• System.out.println("The sum is: " + sum);
• } // a, b, and sum go out of scope here
•}
Control Structure
• Java compiler executes the code from top to bottom.
• The statements in the code are executed according to the order in
which they appear.
• Java provides statements that can be used to control the flow of Java
code.
• Such statements are called control flow statements.
• It is one of the fundamental features of Java, which provides a smooth
flow of program.
• Java provides three types of control flow statements.
• Decision Making statements
• if statements
• switch statement
• Loop statements
• do while loop
• while loop
• for loop
• for-each loop
• Jump statements
• break statement
• continue statement
Decision-Making statements:
• decision-making statements decide which statement to execute and when.
• There are two types of decision-making statements in Java,
• If statement : "if" statement is used to evaluate a condition.
• the If statement gives a Boolean value, either true or false.
• In Java, there are four types of if-statements :
• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
• switch statement :
• Switch statements are similar to if-else-if statements.
• The switch statement contains multiple blocks of code called cases and a single case is executed based
on the variable.
• The case variables can be int, short, byte, char, or enumeration.
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression.
• Break statement terminates the switch block when the condition is satisfied.
•
• if Statement : Executes a block of code if a condition is true.
• // Simple If statement
• public class new2
• {
• public static void main(String[] args) {
• int x = 10;
• int y = 12;
• if(x+y > 20) {
• System.out.println("x + y is greater than 20");
• }}}
• if-else Statement : Executes one block of code if the condition is true, and another block if the condition is false.
• // If else statement
• public class new2
• {
• public static void main(String[] args) {
• int x = 10;
• int y = -12;
• if(x+y < 10)
• {
• System.out.println("x + y is less than 10");
• }
• else
• {
• System.out.println("x + y is greater than 20");
• // else if ladder : Checks multiple conditions in sequence.
• public class new2
• {
• public static void main(String[] args)
• {
• String city = "Delhi";
• if(city == "Meerut")
• {
• System.out.println("city is meerut");
• }
• else if (city == "Noida")
• {
• System.out.println("city is noida");
• }
• else if(city == "Agra")
• {
• System.out.println("city is agra");
• }else
• {
• System.out.println(city);
• }}}
• nested if statements are used when you need to check multiple
conditions in a hierarchical manner.
// Nested if
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
}
else if (number < 0)
{
System.out.println("The number is negative.");
} else
{
System.out.println("The number is zero.");
Switch examples
• do {
• // Code to execute at least once
• } while (condition);
• WAP to print sum of first 10 Natural numbers using For Loop
• public class new2
•{
• public static void main(String[] args)
•{
• int sum = 0;
• for(int j = 1; j<=10; j++)
•{
• sum = sum + j;
•}
• System.out.println("The sum of first 10 natural numbers is " + sum);
• }}
• WAP to print the list of first 10 even numbers using While Loop
• public class new2
• {
• public static void main(String[] args)
• {
•
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• while(i<=10)
• {
• System.out.println(i);
• i = i + 2;
• }}}
• // WAP to print the list of first 10 even numbers using do While Loop
• public class new2
• {
• public static void main(String[] args)
• {
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• do
• {
• System.out.println(i);
• i = i + 2;
• }while(i<=10);
• }
• }
• Jump Statements : These statements allow you to transfer control to another part of the program.
• There are two types of jump statements in Java, i.e., break and continue.
break Statement : Exits a loop or switch statement.
The break statement cannot be used independently in the Java
program, i.e., it can only be written inside the loop or switch statement.
Example :
• public class new2
• {
• public static void main(String[] args)
• {
• for(int i = 0; i<= 10; i++)
• {
• System.out.println(i);
• if(i==6)
• {
• break;
• }}}}
• Continue : the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop.
• public class new2
• {
• public static void main(String[] args)
• {
• for(int i = 0; i<= 2; i++)
• {
• for (int j = i; j<=5; j++)
• {
• if(j == 4)
• {
• continue;
• }
• System.out.println(j);
• }}}
• Arrays : Arrays is used to store multiple values of the same data type
in a single variable.
• They are fixed in size, meaning once an array is created, its size cannot
be changed.
• Arrays are indexed, starting from 0, and can store primitive data types
(e.g., int, char, double) or objects (e.g., String)
• Features :
• Fixed Size: The size of an array is defined at the time of creation and cannot
be changed.
• Indexed: Elements in an array are accessed using their index (starting from 0).
• Homogeneous: All elements in an array must be of the same data type.
• Memory Efficiency: Arrays are stored in contiguous memory locations, making
them efficient for accessing elements.
• Declaring and Initializing Arrays
• 1. Declaring an Array :
• dataType[] arrayName; // Preferred way
• // or
• dataType arrayName[];
• Example:
• int[] numbers; // Declares an array of integers
• String[] names; // Declares an array of strings
• 2. Initializing an Array : Arrays can be initialized using the new keyword or with predefined values.
• Using new Keyword:
• arrayName = new dataType[size];
• Example:
• numbers = new int[5]; // Creates an array of size 5
• names = new String[3]; // Creates an array of size 3
• With Predefined Values:
• dataType[] arrayName = {value1, value2, value3, ...};
• Example:
• int[] numbers = {10, 20, 30, 40, 50}; // Array of size 5
• String[] names = {"Alice", "Bob", "Charlie"}; // Array of size 3
• Accessing Array Elements : Array elements are accessed using their index. The index starts at 0 and goes up to
arrayLength - 1.
• int[] numbers = {10, 20, 30, 40, 50};
• System.out.println(numbers[0]); // Output: 10
• System.out.println(numbers[2]); // Output: 30
• Using for Loop : We can use the for loop to iterate over an array by taking advantage of index numbers.
• public class new2
• {
• public static void main(String[] args)
• {
• // declaration of array in java
• int[] myArray = new int[5];
• // Initialization of array with for loop
• for (int i = 0; i < myArray.length; i++)
• {
• myArray[i] = i * 10;
• }
• // Accessing myArray with for loop
• for (int i = 0; i < myArray.length; i++)
• {
• System.out.println("Value at index " + i + " : " + myArray[i]);
• } }}
• Using Arrays.fill() : Fill() method is present in the arrays class which is part
of java.util package.
• This method is useful to initialize the same value at all indices of an array.
• Example :
• import java.util.Arrays;
• public class new2 {
• public static void main(String[] args)
• {
• String[] myArray = new String[5];
• class new2 {
• public static void main(String[] args)
• {
• // create a 2d array
• int[][] a = {
• {1, 2, 3},
• {4, 5, 6, 9},
• {7},
• };
•
• // calculate the length of each row
• System.out.println("Length of row 1: " + a[0].length);
• System.out.println("Length of row 2: " + a[1].length);
• System.out.println("Length of row 3: " + a[2].length);
• }
• }
Examples
• WAP to adds two matrices and stores the result in a third matrix.
• WAP to multiplies two matrices and stores the result in a third matrix.
• WAP to finds the transpose of a matrix (rows become columns and
vice versa).
• WAP to searches for a specific value in a 2D array.
// Search specific element
public class new2 {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 8;
boolean found = false;
// Searching for the target
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
found = true;
System.out.println("Element " + target + " found at position: (" + i + ", " + j + ")");
break;
}}
if (found) break;
}
if (!found) {
System.out.println("Element " + target + " not found in the matrix.");
• Three-Dimensional (3D) Array : A 3D array is an array of 2D arrays. It can be thought
of as a cube with layers, rows, and columns.
• You can use three nested loops to iterate over a 3D array.
• Declaration and Initialization
• // Syntax
• dataType[][][] arrayName = new dataType[layers][rows][columns];
• Example:
• int[][][] cube = new int[2][3][3]; // 2 layers, each with 3 rows and 3 columns
• For example:
• int[ ][ ][ ] x = new int[2][3][4];
• x[0][0][0] refers to the data in the first table, first row, and first column.
• x[1][0][0] refers to the data in the second table, first row, and first column.
• x[1][2][3] refers to the data in the second table, third row, and fourth column.
• student1 scores: 75, 87, 69
• student2 scores: 90, 87, 85
• student3 scores: 56, 67, 76