0% found this document useful (0 votes)
19 views94 pages

Unit I

The document provides an introduction to Java programming, covering fundamental concepts such as data types, operators, and the Java Development Kit (JDK). It explains the Java Runtime Environment (JRE) and the Java Virtual Machine (JVM), along with details on primitive data types and type conversion. Additionally, it outlines various operators in Java, including arithmetic, unary, assignment, and relational operators.

Uploaded by

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

Unit I

The document provides an introduction to Java programming, covering fundamental concepts such as data types, operators, and the Java Development Kit (JDK). It explains the Java Runtime Environment (JRE) and the Java Virtual Machine (JVM), along with details on primitive data types and type conversion. Additionally, it outlines various operators in Java, including arithmetic, unary, assignment, and relational operators.

Uploaded by

nc3955
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

21CSE269T – JAVA PROGRAMMING

UNIT – I INTRODUCTION TO JAVA


Unit - I
 Introduction to Java
 Data types
 Key words
 Scoping rules
 Automatic Type Conversion
 Type Casting and Arrays

 Operators Precedence & Associativity


 Expression
 Flow control, Enhanced for loop, switch statements

 Handling Strings, Entry Point for Java Programs


 Class fundamentals: Declaring objects, Assigning object reference variable
 Methods & Method Signatures, Method retuning Values, Method with parameters
Introduction to Java
Java is an object-oriented programming language which is known for its simplicity, portability, and robustness.

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James
Gosling and Patrick Naughton.

Main Features of JAVA


1. Java is a platform independent language
2. Java is an Object Oriented language – 4 Main Concepts(Abstraction, Encapsulation, Inheritance , Polymorphism)
3.Simple
4.Robust
5. Secure
6. ava is distributed
7. Multithreading
8.Portable
9. High Performance
JAVA DEVELOPMENT KIT (JDK)

• JDK = JRE + Library Classes (development tools)

• Java Development Kit (JDK) is a software development environment used to develop java applications

• It physically exists

• JDK is an implementation of Java Platform by Oracle corporation(J2SE, J2EE and J2ME)


JAVA PROGRAMMING ENVIRONMENT AND RUNTIME ENVIRONMENT

The Java Environment

Here Java Environment refers to JRE (Java Runtime Environment) JRE is set of software tools which are used for
developing java applications.

Main component of JRE are JVM, set of libraries , User interface toolkits, deployment technologies and other files.

JRE = JVM + Libraries + Other files

What is JVM?
JVM (Java Virtual Machine)

JVM (Java Virtual Machine) executes java code line by line.


Operations of JVM are:
● Class Loader : Loads code

● Byte code Verifier : Verifies code

● Execution Engine : Executes code

● Runtime Data Area: Provides runtime environment

JVMs are available for many hardware and software platforms - JVM is platform dependent.
Internal Architecture of JVM
A Picture is Worth…
The output of the
compiler is .class
file

The Interpreter's are sometimes referred to as the Java Virtual Machines


PRIMITIVE DATA TYPES
• Primitive data types are those data types that are predefined in the Java
programming language.
• There are a total of eight primitive data types that are predefined in the
Java programming language.
• The size of the primitive data types does not change with changing the
operating system because the Java programming language is independent of
all the operating systems.
• For example: byte, short, int, long, double, float, boolean, char
Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127. Default Value is 0.

short 2 bytes Stores whole numbers from -32,768 to 32,767. Default Value is 0.

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647. Default Value is 0.

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. Default Value is 0L.

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits. Default Value is
0.0f.

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits. Default Value is
0.0d.

boolean 1 bit Stores true or false values. Default Value is false.

char 2 bytes Stores a single character/letter or ASCII values. Default Value is '\u0000'
1. boolean

• The boolean data type has two possible values, either true or false.
• Default value: false.
• They are usually used for true/false conditions.
• Example:

class Main
{
public static void main(String[] args)
{
boolean flag = true;
System.out.println(flag); // prints true
}
}
2. byte

• The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
• If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
3. short

• The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
• If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
4. int

• The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a
minimum value of 0 and a maximum value of 232-1.
• Default value: 0
• Example:

class Main
{
public static void main(String[] args)
{
int range = -4250000;
System.out.println(range); // print -4250000
}
}
5. long

• The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
• Default value: 0
• Example:

class LongExample
{
public static void main(String[] args)
{
long range = -42332200000L;
System.out.println(range); // prints -42332200000
}
}
6. float

• he float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0f)
• Example: • Notice that we have used -
instead of -42.3 in the
42.3f

class Main program.


{ • It's because -42.3 is
public static void main(String[] args) a double literal.
{
• To tell the compiler to treat -
float number = -42.3f; 42.3 as float rather than double,
System.out.println(number); // prints -42.3 you need to use f or F.
}
}
7. double

• The double data type is a double-precision 64-bit floating-point.


• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0d)
• Example:

class Main
{
public static void main(String[] args)
{
double number = -42.3;
System.out.println(number); // prints -42.3
}
}
8. char
• It's a 16-bit Unicode character.
• The minimum value of the char data type is '\u0000' (0) and the maximum value of the is
'\uffff'.
• Default value: '\u0000’
• Example:
class Main {
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
• Example:
class Main
{
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
}
TYPE CONVERSION AND CASTING
• Type casting is a mechanism in which one data type is converted to another
data type using a casting () operator by a programmer.
• Example:
Narrowing Casting (manually) - converting a larger type to a smaller type
double -> float -> long -> int -> char -> short -> byte

• Type conversion allows a compiler to convert one data type to another data
type at the compile time of a program or code.
• Example:
Widening Casting (automatically) - converting a small type to a larger type
byte -> short -> char -> int -> long -> float -> double
Difference between Type Casting and Type Conversion
OPERATORS

• Operators are symbols used to perform operations on variables and values.


• Operators are special symbols used for
- mathematical functions
- assignment Statements
- logical Comparisons

Examples
3+5 // uses + operator
14+5-4*(5-3) // uses +, -, * operators
Types of operators in Java:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. Instance of operator
Java Operator Precedence

Operator Type Category Precedence


Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.

• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
Example
// Arithmetic Operators
import java.io.*;
// Drive Class
class GFG
{
// Main Function
public static void main (String[] args) Output
{ • Addition:30
int a = 10;
int b = 3;
• Substraction:10
System.out.println("a + b = " + (a + b)); • Multiplication:200
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
• Division:2
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
2.Unary Operators
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

• incrementing/decrementing a value by one


• negating an expression
• inverting the value of a Boolean

Example 1 : ++ and –
Output
10
public class OperatorExample 12
{
public static void main(String args[])
12
{ 10
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Example 2:
Output:
public class OperatorExample
{
-11
public static void main(String args[]) 9
{ false
int a=10; true
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
3. Assignment Operator

• The general format of the assignment operator is:


variable = value;

• The assignment operator can be combined with other operators to build a shorter version of the statement
called a Compound Statement.

• +=, 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.
• %=, for assigning the modulo of the left operand by the right operand and then assigning it to the variable
on the left.
import java.io.*; Output:
class GFG
{
f += 3: 10
public static void main(String[] args) f -= 2: 8
{
int f = 7;
f *= 4: 32
System.out.println("f += 3: " + (f += 3)); f /= 3: 10
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
f %= 2: 0
System.out.println("f /= 3: " + (f /= 3)); f &= 0b1010: 0
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
f |= 0b1100: 12
System.out.println("f |= 0b1100: " + (f |= 0b1100)); f ^= 0b1010: 6
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
f <<= 2: 24
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1)); f >>= 1: 12
System.out.println("f >>>= 1: " + (f >>>= 1));
f >>>= 1: 6
}
}
4. Relational Operators

These operators are used to check for relations like equality, greater than, and less than.
The general format is,
variable relation_operator value

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.
import java.io.*;
class GFG
{ Output:
public static void main(String[] args) a > b: true
{
a < b: false
int a = 10;
int b = 3; a >= b: true
int c = 5; a <= b: false
System.out.println("a > b: " + (a > b)); a == c: false
System.out.println("a < b: " + (a < b)); a != c: true
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.

Conditional 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
Example:
import java.io.*;
class GFG
{
public static void main (String[] args) Output
{ x && y: false
boolean x = true; x || y: true
boolean y = false; !x: 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.

The general format is:

condition ? if true : if false

// Java program to illustrate max of three numbers using ternary operator.


public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

Output
Max of three numbers = 30
7. Bitwise Operators

• These operators are used to perform the manipulation of individual bits of a number.
• can be used with any of the integer types.
• used when performing update and query operations of the Binary indexed trees.

• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
import java.io.*;
class GFG
{
public static void main(String[] args) Output :
{ d & e: 8
int d = 0b1010;
int e = 0b1100; d | e: 14
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e)); d ^ e: 6
System.out.println("d ^ e: " + (d ^ e)); ~d: -11
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2)); d << 2: 40
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1)); e >> 1: 6
} e >>> 1: 6
}
8. Shift Operators

General format-

number shift_op number_of_places_to_shift;

• <, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as multiplying the number with some power of two.

• >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the number
with some power of two.

• >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit is set to 0.
import java.io.*;
// Driver Class
class GFG
{
// main function
Output
public static void main(String[] args)
a<<1 : 20, a>>1 : 5
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
9. Instance of operator

• The instance of the operator is used for type checking.


• It can be used to test if an object is an instance of a class, a subclass, or an interface.
• General format-

object instance of class/subclass/interface


Example
class operators
{
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an // instance of Boy or interface
System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Person: "+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "+ (obj2 instanceof MyInterface));
}
}
class Person Output
{ obj1 instanceof Person: true
} obj1 instanceof Boy: false
class Boy extends Person implements MyInterface
obj1 instanceof MyInterface: false
{
} obj2 instanceof Person: true
interface MyInterface { obj2 instanceof Boy: true
} obj2 instanceof MyInterface: true
VARIABLES
• A variable is the holder that can hold the value while the java program is executed.

• A variable is assigned with a datatype.

• It is name of reserved area allocated in memory. In other words, it is a name of memory


location.

• There are three types of variables in java: local, instance and static.

• A variable provides us with named storage that our programs can manipulate.

• Each variable in Java has a specific type, which determines the size and layout of the
variable’s memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
• Before using any variable, it must be declared.

• The following statement expresses the basic form of a variable declaration :

datatype variable [ = value][, variable [ = value] ...] ;

• Here data type is one of Java’s data types and variable is the name of the variable.

• To declare more than one variable of the specified type, use a comma-separated list.

Example:
• int a, b, c; // Declaration of variables a, b, and c.
• int a = 20, b = 30; // initialization
• byte B = 22; // Declaration initializes a byte type variable B.
Types of Variable

There are three types of variables in java:


• local variable
• instance variable
• static variable
Local Variable

• Local variables are declared inside the methods, constructors, or blocks.


• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.
Instance Variable

• A variable declared inside the class but outside the method, is called instance variable.
• Instance variables are declared in a class, but outside a method, constructor or any block.

• A slot for each instance variable value is created when a space is allocated for an object in
the heap.
• Instance variables are created when an object is created with the use of the keyword ‘new’
and destroyed when the object is destroyed.

• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present throughout
the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
Instance Variable

• The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can
be given for these variables with the use of access modifiers.

• Instance variables have default values.


○ numbers, the default value is 0,
○ Booleans it is false,
○ Object references it is null.

• Values can be assigned during the declaration or within the constructor.


• Instance variables cannot be declared as static.
• Instance variables can be accessed directly by calling the variable name inside the class.

• However, within static methods (when instance variables are given accessibility), they
• should be called using the fully qualified name. ObjectReference.VariableName.
Static Variable

• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many objects
are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables.
• However, most static variables are declared public since they must be available for users
of the class.
Static Variable

• Default values are same as instance variables.


○ numbers, the default value is 0;
○ Booleans, it is false;
○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants) are
all in upper case.
• If the static variables are not public and final, the naming syntax is the same as instance
and local variables.
Example for local, instance and static variables:

class LearningVariables
{
static int x =10; //This is a static variable
int y = 15; // This is an instance variable
void method ( )
{
int z = 20; // This is a local variable
}
}
Example for local variable:

import java.io.*;
public class A
{
public void TeacherAge()
{
int age = 25; // local variable
System.out.println("a = " + age);
}
public static void main(String args[])
{
A obj = new A();
obj.TeacherAge();
}
}
Example for instance variable:

import java.io.*;
class Marks
{
int engMarks; //instance variable
}
class MarksDemo
{
public static void main(String args[])
{
Marks obj = new Marks();
obj.engMarks = 50;
System.out.println("Marks = " + obj.engMarks);
}
}
Example for static variable:

import java.io.*;
class Emp
{
public static double salary; //static variable
public static String name = "Tuhin";
}
public class EmpDemo
{
public static void main(String args[])
{
Emp.salary = 1000;
System.out.println(Emp.name);
System.out.println(Emp.salary);
}
}
ARRAYS
• Array is a collection of similar type of elements that have contiguous memory location.
• In Java all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using member length.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.

Disadvantage of Java Array


• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
• To solve this problem, collection framework is used in java.

Types of Array in java


1. One- Dimensional Array
2. Multidimensional Array
One-Dimensional Arrays

• An array is a group of like-typed variables that are referred to by a common name.


• An array declaration has two components: the type and the name.
• type declares the element type of the array.
• The element type determines the data type of each element that comprises the array.
• We can also create an array of other primitive data types like char, float, double..etc or
user defined data type(objects of a class).
• Thus, the element type for the array determines what type of data the array will hold.

Syntax:
• type var-name[ ];

Instantiation of an Array in java


• array-var = new type [size];
Example:
class Testarray
{
public static void main(String args[]){ Output:
int a[]=new int[5]; //declaration and instantiation 10
a[0]=10; //initialization 20
a[1]=20; 70
a[2]=70; 40
a[3]=40; 50
a[4]=50;
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]); //printing array
}
}
Example: Declaration, Instantiation and Initialization of Java Array
class Testarray1
{
public static void main(String args[]) Output:
{ 33
int a[]={33,3,4,5}; //declaration, instantiation and initialization 3
for(int i=0;i<a.length;i++) //length is the property of array 4
System.out.println(a[i]); //printing array 5
}
}
We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++) Output:
if(min>arr[i]) 3
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Multidimensional Arrays

• Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array.
• These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.

Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Multidimensional Arrays

Example: // Demonstrate a two-dimensional array.


class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0; Output:
for(i=0; i<4; i++)
{
01234
for(j=0; j<5; j++) 56789
twoD[i][j] = k;
10 11 12 13 14
k++; 15 16 17 18 19
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
STRINGS
• In general string is a sequence of characters. String is an object that represents a sequence of characters.
• The java.lang.String class is used to create string object.
• In java, string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:

• Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

• +
• The CharSequence interface is used to represent sequence of characters.
• It is implemented by String, StringBuffer and StringBuilder classes.
• It means can create string in java by using these 3 classes.

The string objects can be created using two ways.


1. By String literal
2. By new Keyword
1. String Literal
• Java String literal is created by using double quotes.
• For Example:
String s=”welcome”;
• Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn’t exist in
the pool, a new string instance is created and placed in the pool.
• For example:
String s1=”Welcome”;
String s2=”Welcome”;
• In the above example only one object will be created.
• Firstly JVM will not find any string object with the value “Welcome” in string constant pool, so it
will create a new object.
• After that it will find the string with the value “Welcome” in the pool, it will not create new object
but will return the reference to the same instance.
• To make Java more memory efficient.
2. By new keyword

• String s=new String(“Welcome”);


• In such case, JVM will create a new string object in normal (non pool) heap memory and
the literal “Welcome” will be placed in the string constant pool.
• The variable s will refer to the object in heap (non pool).
• The java String is immutable i.e. it cannot be changed.
• Whenever we change any string, a new instance is created.
• For mutable string, you can use StringBuffer and StringBuilder classes.
Example:
public class String_Example
{
public static void main(String args[])
{
String s1=“java”;
char c[]={‘s’,’t’,’r’,’i’,’n’,’g’};
String s2=new String(c);
String s3=new String(“example”);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Java String class methods

• The java.lang.String class provides many useful methods to perform operations on sequence of char values.
The following program is an example for String concat function:

class string_method
{
public static void main(String args[]) Output:
{ Java Programming
String s=”Java”;
s=s.concat(“ Programming”);
System.out.println(s);
}
}
CONTROL STATEMENT
• Control statements decide the flow (order or sequence of execution of statements) of a
Java program.
• In Java, statements are parsed from top to bottom.
• Therefore, using the control flow statements can interrupt a particular section of a
program based on a certain condition.one or more clauses.
Conditional / Selection Statements

1) Simple if
2) if-else
3) if-else-if ladder
4) switch
1. Simple if

Syntax :
Example:
if(condition)
public class Student
{
{
statement 1; //executes when condition is true
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");

}
}
}

Output:
x + y is greater than 20
2. if-else

Syntax: Example:
if(condition) public class Student
{ {
statement 1; //executes when condition is true public static void main(String[] args)
} {
else int x = 10;
{ int y = 12;
statement 2; //executes when condition is false if(x+y < 10)
} {
System.out.println("x + y is less than10");
}
else
{
System.out.println("x + y is greater than 20");

}
}
}
Output:
x + y is greater than 20
3. if-else–if ladder

The if-else-if ladder statement executes one condition from multiple statements.
Example:
public class Student
{
public static void main(String[] args)
Syntax of if-else-if : {
if(condition 1) String city = "Delhi";
if(city == "Meerut")
{
{
statement 1; //executes when condition 1 is true System.out.println("city is meerut");
} }
else if(condition 2) else if (city == "Noida")
{ {
statement 2; //executes when condition 2 is true System.out.println("city is noida");
}
} else if(city == "Agra")
else {
{ System.out.println("city is agra");
statement 2; //executes when all the conditions are false }
else
} {
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement

Syntax:

if(condition 1)
{
statement 1; //executes when condition 1 is true
}
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
Example:
public class JavaNestedIfExample2
{
public static void main(String[] args)
{
int age=25; Output:
int weight=48; You are not eligible to donate blood
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");

}
}
else
{
System.out.println("Age must be greater than 18");
}
}
5. Java Switch Statement

• The Java switch statement executes one statement from multiple conditions.
• It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• Each case statement can have a break statement which is optional.
• When control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10"); Output:
break; 20
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Loop / Iterative Statement

• These are used to execute a block of statements multiple times.


• It means it executes the same code multiple times so it saves code.
• These are also called Iteration statements.

There are three types of iterative control statements:

1. For loop
2. While loop
3. Do-while loop
1. for loop

For loop can initialize the variable, check condition and increment/decrement value. It consists
of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true
or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statements (For Body)
}
// Java Program to demonstrate the example of
Output
for loop which prints table of 1 1
public class ForExample 2
{ 3
public static void main(String[] args) 4
5
{
6
for(int i=1;i<=10;i++) 7
{ 8
System.out.println(i); 9
} 10
}
}
Nested for loop

• a for loop inside the another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.
public class PyramidExample
{ Output
public static void main(String[] args)
{ *
for(int i=1;i<=5;i++) **
{ ***
for(int j=1;j<=i;j++) ****
*****
{
System.out.print("* ");
}
System.out.println(); //new line
}
}
}
2. while loop

The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
Note: important thing about while loop is that, sometimes it may not even execute. If
the condition to be tested results into false, the loop body is skipped and first
statement after the while loop will be executed.

Syntax:
while (condition)
{
//code to be executed
increment / decrement statement
}
Example:
public class WhileExample Output
{ 1
public static void main(String[] args) 2
{
3
int i=1;
while(i<=10) 4
{ 5
System.out.println(i); 6
i++; 7
}
8
}
} 9
10
3. do while loop

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition
is true.
Note: If the number of iteration is not fixed and have to execute the loop at least once, it is
recommended to use a do-while loop.
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and
control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or
decrements loop variable.
Example:
i++;
Syntax do while loop: Example:
do public class DowhileExample Output:
{ { 1
//code to be executed / loop body public static voidW main(String[] args) 2
{ 3
//update statement int i=1; 4
}while (condition); do 5
{ 6
System.out.println(i); 7
i++; 8
}while(i<=10); 9
} 10
}
Flow control / Jump Statement

Jumping statements are control statements that transfer execution control from one point to another point in the
program.
There are two Jump statements that are provided in the Java programming language:
1. Break statement.
2. Continue statement.

1. Break statement
Using Break Statement to exit a loop:
• In java, the break statement is used to terminate the execution of the nearest looping statement or switch
statement.
• The break statement is widely used with the switch statement, for loop, while loop, do-while loop.
Syntax:
break;
1. break
Example:
import java.io.*;
class GFG
{ Output
public static void main(String[] args)
{ 0
int n = 10; 1
for (int i = 0; i < n; i++)
{ 2
if (i == 6) 3
break;
System.out.println(i); 4
} 5
}
}
Use Break as a form of goto
class GFG
{
public static void main(String[] args)
• Java does not have a goto {
statement because it produces an for (int i = 0; i < 3; i++)
unstructured way to alter the flow {
of program execution. one : { // label one Output:
two : { // label two
• Java illustrates an extended form three : { // label three i=0
of the break statement. This form System.out.println("i=" + i); after label one
of break works with the label. if (i == 0) i=1
break one; // break to label one after label two
• The label is the name of a label if (i == 1)
that identifies a statement or a break two; // break to label two after label one
block of code. if (i == 2) i=2
break three; // break to label three after label three
} after label two
Syntax: System.out.println("after label three");
} after label one
break label; System.out.println("after label two");
}
System.out.println("after label one");
}
}
}
2. continue

Example:
import java.io.*;
The continue statement pushes the class GFG
next repetition of the loop to take
place, hopping any code between {
Output:
itself and the conditional public static void main(String[] args)
0
expression that controls the loop. {
1
for (int i = 0; i < 10; i++)
2
{
3
if (i == 6)
4
{
5
System.out.println();
7
continue;
8
}
9
System.out.println(i);
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy