0% found this document useful (0 votes)
5 views

Java

Uploaded by

Ritik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java

Uploaded by

Ritik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Data Types

Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

Primitive data types: primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language. The primitive data types include boolean, char, byte, short, int,
long, float and double.

Non-primitive data types: The Non-Primitive (Reference) Data Types will


contain a memory address of variable values because the reference types
won’t store the variable value directly in memory. They are strings, objects,
arrays, etc.
Array
 An array is a collection of similar type of elements which has
contiguous memory location.
 Array in Java is index-based, the first element of the array is
stored
at the 0th index, 2nd element is stored on 1st index and so on.
 Syntax: specify the data type and the name of the array.
datatype[] arrayName;
or
datatype arrayName[];

e.g. int[10] numbers;


Array
 This statement declares an array named numbers that will hold integers

 An array is a structured way to store multiple items of the same type,


making it easier to manage and manipulate collections of data in Java.
Conti…….
 Initializing an Array
1.Static Initialization: means you provide all the values for the array
at the
time of declaration.
int[] numbers = {1, 2, 3, 4, 5};

2. Dynamic Initialization : involves creating the array first and then


assigning values to it later.
int[] numbers = new int[5];
 Accessing Array Elements
We use the index (starting from 0) to access array elements.
int ith = numbers[i];
// Accesses the ith element.

 Modifying Array Elements


we can change values of the Array elements using their index.
numbers[i] = 10;
// Changes the ith element to 10.
 public class Main {
 public static void main(String[] args) {
 int[] myArray = {1, 2, 3, 4, 5};
 System.out.println("The first element is: " + myArray[1]);
 System.out.println("The fourth element is: " + myArray[4]);
 System.out.println("The length of the array is: " +
myArray.length);
 for (int i = 0; i < myArray.length; i++) {
 System.out.println("Element at index " + i + ": " + myArray[i]);
 }
 }
 Java supports different types of arrays:
1. Single-Dimensional Arrays

These are the most common type of arrays, where elements


are stored in a linear order.
int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional array
2. Multi-Dimensional Arrays

Arrays with more than one dimension, such as two-dimensional

arrays (matrices).
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
 public class Main {
 public static void main(String[] args) {
 int[] myArray = {1, 2, 3, 4, 5};
 System.out.println("The first element is: " + myArray[1]);
 System.out.println("The fourth element is: " + myArray[4]);
 int[][] multiArray = { {1, 2}, {3, 4}, {5, 6} };
 System.out.println("Element at row 1 column 1: " +
multiArray[0][0]);
 }
 }
Operators

 Operators in Java are the symbols used for


performing specific operations in Java.
 Operators in Java help you perform calculations,
compare values, and make decisions in your code.
They are essential for writing effective programs.
 Operators make tasks like addition, multiplication, etc
which look easy although the implementation of
these tasks is quite complex.
Types

 There are multiple types of operators in Java all are mentioned


below:
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator
1. Arithmetic Operators
 They are used to perform simple arithmetic operations on primitive
and non-primitive data types.
 (* ) Multiplication :- Multiplies two numbers.
int sum = 5 * 3;
 (/ ) Division :- Divides one number by another.
int sum = 5 / 3;
 (%) Modulo :- Returns the remainder of a division.
int sum = 5 % 3;
 (+ ) Addition :- Adds two numbers.
int sum = 5 + 3;
 (– ) Subtraction :- Subtracts one number from another.
int sum = 5 - 3;
2. Unary Operators
 Unary operators need only one operand. They are used to increment,
decrement a value.
 (++) Increment operator, used for incrementing the value by 1.
There are two varieties of increment operators.
E.g. a++;
 Post-Increment: Value is first used for computing the result and then
incremented.
 Pre-Increment: Value is incremented first, and then the result is computed.
 (– –) Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operators.
E.g. a--;
 Post-decrement: Value is first used for computing the result and then
decremented.
 Pre-Decrement: The value is decremented first, and then the result is
computed.
2. unary operators
int a = 10;
int b = 10;
System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));


System.out.println("Predecrement : " + (--b));
3. Assignment Operator
 Simple Assignment (=) operator is used to assign a value to any
variable. It has right-to-left associativity, i.e. value given on the right-hand
side of the operator is assigned to the variable on the left.
int a = 5;
 (+=) for adding the left operand with the right operand and
then assigning it to the variable on the left.
 (-=) for subtracting the right operand from the left operand
and then assigning it to the variable on the left.
 (*=) for multiplying the left operand with the right operand
and then assigning it to the variable on the left.
 (/=) for dividing the left operand by the right operand and
then assigning it to the variable on the left.
 Assignment operators

int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
4 . Relational Operators:
 These operators are used to check for relations like equality, greater than, and less than. They return
Boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements.
 Some of the relational operators are-
 (==) Equal to, returns true if the left-hand side is equal to the right-hand side.
 (!=) Not Equal to, returns true if the left-hand side is not equal to the right-
hand side.
 (<) less than: returns true if the left-hand side is less than the right-hand side.
 (<=) less than or equal to, returns true if the left-hand side is less than or equal
to the right-hand side.
 (>) Greater than: returns true if the left-hand side is greater than the right-
hand side.
 (>=) Greater than or equal to, returns true if the left-hand side is greater than
or equal to the right-hand side.
4. Relational operators

int a = 10;
int b = 3;
int c = 5;

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 <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
5. Logical Operators:

These operators are used to perform “logical AND” and “logical OR”
operations, i.e., a function similar to AND gate and OR gate in digital
electronics.
Logical operators are:

(&&) Logical AND: returns true when both conditions are true.
(||) Logical OR: returns true if at least one condition is true.
(!)Logical NOT: returns true when a condition is false and vice-
versa.
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
6. Ternary operator
 The ternary operator is a shorthand version of the if-else statement. It
has three operands and hence the name Ternary.

 Syntax: condition ? valueIfTrue : valueIfFalse.

The above statement means that if the condition evaluates to true, then execute
the statements after the ‘?’ else execute the statements after the ‘:’.
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
Control Statements.

 Java compiler executes the code from top to bottom. The statements
in the code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the
flow of Java code. Such statements are called control flow statements.
 Control statements in Java are instructions that manage the flow of
execution of a program based on certain conditions.
 They are used to make decisions, to loop through blocks of code
multiple times, and to jump to a different part of the code based on
certain conditions. Control statements are fundamental to any
programming language, including Java, as they enable the creation of
dynamic and responsive programs.
Java provides three types of control flow statements.

 Decision Making statements


 if statements
 switch statement
 Loop statements
 do while loop
 while loop
 for loop
 Jump statements
 break statement
 continue statement
IF Statement
The if statement in Java evaluates a boolean condition. If the condition is true, the
block of code inside the if statement is executed. It's the simplest form of decision-
making in programming, allowing for the execution of certain code based on a
condition.

 Syntax
if (condition) {
// Code to execute if the condition is true
}
 Flowchart
IF-Else statement
 The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the
if-block is evaluated as false.
 Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
IF-Else-if :
 The if-else-if statement contains the if-statement followed by multiple
else-if statements. In other words, we can say that it is the chain of if-
else statements that create a decision tree where the program may
enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
 Syntax.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
switch' Statement .
 The switch statement in Java allows for the selection of a block of code to be
executed based on the value of a variable or expression. It is an alternative to a
series of if statements and is often more concise and easier to read.
 Syntax
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ...
default:
// Code to be executed if expression does not match any case
}
Flowchart
Looping Statements
 Looping statements are used to execute a block of code repeatedly based on
a given condition or set of conditions. These statements are fundamental to
Java programming, allowing for iteration over data structures, repetitive
tasks, and more. The main types of looping statements in Java are for loop,
while loop and do-while loop.

For loop:
 The for loop (Entry-control) is a control structure that allows repeated
execution of a block of code for a specific number of times. It is typically used
when the number of iterations is known beforehand.
Syntax
for (initialization; condition; update) {
// code block to be executed
}
Here,
Initialization: Typically used to initialize a counter variable.
Condition: The loop runs as long as this condition is true.
Update: Updates the counter variable, usually incrementing or decrementing
 import java.util.Scanner;

 public class FactorialCalculator {


 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.print("Enter a number: ");
 int number = scanner.nextInt();
 int factorial = 1;

 for (int i = 1; i <= number; i++) {


 factorial *= i; // Multiplying with each number up to 'number'
 }

 System.out.println("Factorial of " + number + " is: " + factorial);


 }
 }
while loop:
 A while loop in Java repeatedly executes a block of code as long as a
specified condition remains true. It is ideal for situations where the
number of iterations is not predetermined.

 Syntax
while (condition) {
// code block to be executed
}
Here,

 Condition: The loop continues to run as long as this condition


evaluates to true.
 Code Block: The statements inside the loop execute repeatedly until
the condition becomes false.
 do-while loop:
The do-while loop is a post-tested loop, meaning it executes the body of the loop at
least once before checking the condition. This loop is useful when you need to ensure
that the loop body is executed at least once, regardless of whether the condition is
true or false. After the body of the loop has executed, the condition is tested. If the
condition is true, the loop will execute again. This process repeats until the condition
becomes false.
 Syntax
do {
// Statements to execute
} while (condition);
Here:
 do: This keyword starts the do-while loop.
 while: This keyword is followed by a condition in parentheses.
 condition: A Boolean expression that is evaluated after the loop body has
executed. If this condition evaluates to true, the loop will execute again. If it
evaluates to false, the loop will terminate, and control passes to the
statement immediately following the loop.
public class Calculation {
public static void main(String[] args)
{
// TODO Auto-generated method
stub
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
 Jump statements are used to transfer control to another part of
the program. They are particularly useful for breaking out of loops
or skipping to the next iteration of a loop.
The main types of jump statements are break, continue. Each
serves a different purpose in controlling the flow of execution.
Break-Statement :
 The break statement is used to exit from a loop (for, while, do-
while) or a switch statement. When encountered, it terminates the
loop or switch statement and transfers control to the statement
immediately following the loop or switch.
Syntax:
break;
Continue-Statement:
 The continue statement skips the current iteration of a loop (for,
while, do-while) and proceeds to the next iteration. It effectively
jumps to the end of the loop's body and re-evaluates the loop's
condition.

 Syntax
continue;
 int day = 4;
 switch (day) {
 case 1:
 System.out.println("Monday");
 break;
 case 2:
 System.out.println("Tuesday");
 break;
 case 3:
 System.out.println("Wednesday");
 break;
 case 4:
 System.out.println("Thursday");
 break;
 case 5:
 System.out.println("Friday");
 break;
 case 6:
 System.out.println("Saturday");
 break;
 case 7:
 System.out.println("Sunday");
 break;
 }
Byte Code
 Byte Code can be defined as an intermediate code generated by the compiler
after the compilation of source code(JAVA Program). This intermediate code
makes Java a platform-independent language.
 Compiler converts the source code or the Java program
into the Byte Code(or machine code), and secondly,
the Interpreter executes the byte code on the system.
 The Interpreter can also be
called JVM(Java Virtual Machine).
 The byte code is the common piece
between the compiler(which creates it)
and the Interpreter (which runs it).
JVM(Java Virtual Machine)
 Java virtual machine, or JVM, loads, verifies, and runs Java bytecode. It is
known as the interpreter or the core of the Java programming language.
 JVM is responsible for converting bytecode to machine-specific code and is
necessary in both JDK and JRE.
 It platform-dependent and performs many functions, including memory
management and security. In addition, JVM can run programs that are
written in other programming languages that have been converted to Java
bytecode.
 Components
 JVM consists of three main components or subsystems:
 Class Loader Subsystem is responsible for loading, linking, and
initializing a Java class file (that is, “Java file”), otherwise known as dynamic
class loading.
 Runtime Data Areas contain method areas, PC registers, stack areas,
and threads.
 Execution Engine contains an interpreter, compiler, and garbage
collection area.
JRE
 Java Runtime Environment, or JRE, is a set of software tools
responsible for execution of the Java program or application on your
system.
 JRE uses heap space for dynamic memory allocation for Java objects.
JRE is also used in JDB (Java Debugging.
 JDK.
 Java Development Kit, or JDK, is a software development kit that is a
superset of JRE. It is the foundational component that enables Java
application and Java applet development. It is platform-specific, so
separate installers are needed for each operating system (for
example, Mac, Unix, and Windows).
Role of JDK
 JDK contains all the tools that are required to compile, debug, and run
a program developed using the Java platform. (It’s worth noting that
Java programs can also be run by using command line.)
 JDK is the development platform, while JRE is for execution.
 JVM is the foundation, or the heart of the Java programming
language, and ensures the program’s Java source code will be
platform-agnostic.
 JVM is included in both JDK and JRE—Java programs won’t run without
it.
 import java.util.Scanner;
 public class Main {

 public static void main(String[] args) {


 Scanner sc = new Scanner(System.in);

 // Arithmetic Operators
 System.out.println("Enter two numbers:");
 int a = sc.nextInt();
 int b = sc.nextInt();

 System.out.println("Arithmetic Operations:");
 System.out.println("Addition (a + b) = " + (a + b));
 System.out.println("Subtraction (a - b) = " + (a - b));
 System.out.println("Multiplication (a * b) = " + (a * b));
 System.out.println("Division (a / b) = " + (a / b));
 System.out.println("Modulus (a % b) = " + (a % b));
 // Relational Operators
 System.out.println("Relational Operations:");
 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 < b: " + (a < b));
 System.out.println("a >= b: " + (a >= b));
 System.out.println("a <= b: " + (a <= b));
 // Logical Operators
 boolean condition1 = (a > 0);
 boolean condition2 = (b > 0);
 System.out.println("Logical Operations:");
 System.out.println("condition1 && condition2: " + (condition1 &&
condition2));
 System.out.println("condition1 || condition2: " + (condition1 ||
condition2));
 System.out.println("!condition1: " + (!condition1));

 // if-else control statement


 System.out.println("If-Else Control Statement:");
 if (a > b) {
 System.out.println("a is greater than b");
 } else if (a < b) {
 System.out.println("a is less than b");
 } else {
 System.out.println("a is equal to b");
 }
 // switch-case control statement
 System.out.println("Enter a number (1-3) to demonstrate switch-
case:");
 int num = sc.nextInt();
 switch (num) {
 case 1:
 System.out.println("You chose option 1");
 break;
 case 2:
 System.out.println("You chose option 2");
 break;
 case 3:
 System.out.println("You chose option 3");
 break;
 default:
 System.out.println("Invalid choice");
 break;
 }
 // for loop
 System.out.println("\nFor Loop:");
 for (int i = 1; i <= 5; i++) {
 System.out.println("Iteration " + i);
 }

 // while loop
 System.out.println("\nWhile Loop:");
 int counter = 1;
 while (counter <= 3) {
 System.out.println("Counter is: " + counter);
 counter++;
 }
 // do-while loop
 System.out.println("\nDo-While Loop:");
 int Counter = 1;
 do {
 System.out.println("Do-While iteration: " + doCounter);
 Counter++;
 } while (Counter <= 3);

 // Ternary Operator
 System.out.println("\nTernary Operator:");
 int max = (a > b) ? a : b;
 System.out.println("The maximum of a and b is: " + max);

 sc.close();
 }
 }

You might also like