0% found this document useful (0 votes)
71 views33 pages

Institute: Uie Department: Cse: Java Programing (CST-205)

The document discusses Java fundamentals including control flow statements, arrays, and some key rules around array creation in Java. Specifically, it covers: - Control flow statements like if-else, switch, while, do-while, for each loops and how they work. - Types of arrays like single and multi-dimensional arrays. It also discusses some advantages and disadvantages of arrays. - Rules for array declaration and creation in Java like the need to specify the size, ability to have zero size arrays, exceptions for negative sizes, and allowed data types for array sizes.

Uploaded by

Santosh Thakur
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)
71 views33 pages

Institute: Uie Department: Cse: Java Programing (CST-205)

The document discusses Java fundamentals including control flow statements, arrays, and some key rules around array creation in Java. Specifically, it covers: - Control flow statements like if-else, switch, while, do-while, for each loops and how they work. - Types of arrays like single and multi-dimensional arrays. It also discusses some advantages and disadvantages of arrays. - Rules for array declaration and creation in Java like the need to specify the size, ability to have zero size arrays, exceptions for negative sizes, and allowed data types for array sizes.

Uploaded by

Santosh Thakur
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/ 33

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science & Engineering)
Java Programing(CST-205)
TOPIC OF PRESENTATION:
Java Fundamentals

DISCOVER . LEARN . EMPOWER


Lecture Objectives

In this lecture, we will discuss:


• About flow control statements
in java.
• Various concepts of array.

2
Control Flow Statements In Java
• Flow control describes the order in which all the statements will be executed at run time.
• Control flow statements, change or break the flow of execution by implementing
decision making, looping, and branching your program to execute particular blocks of
code based on the conditions.
Types of control flow statements:
Selection Statements
• IF-ELSE STATEMENT:
SYNTAX EXAMPLE

public class ExampleIf{


public static void main(String args[]){
boolean b=false;
if(b=true)
{
System.out.println("hello");
}else{
System.out.println("hi");
}}}
OUTPUT:
Hello
Selection Statements
• SWITCH STATEMENT:
Selection Statements
• SWITCH STATEMENT:
If several options are available then it is not recommended to use if-else we should go for switch
statement. Because it improves readability of the code.

SYNTAX EXAMPLE
switch(x){ public class ExampleSwitch{
case 1: public static void main(String args[]){
Action1 int x=10;
break; final int y=20;
switch(x) {
case 2: case 10:
Action2 . . System.out.println("10");
. case y:
default: System.out.println("20");
default action }}}
} OUTPUT: 10 20
Iterative Statements
• WHILE LOOP:
if we don't know the no of iterations in advance then best loop is while loop:

SYNTAX EXAMPLE

Example 1: public class ExampleWhile{


while(rs.next()) public static void main(String args[]){
{ while(true)
System.out.println("hello");
} }}
OUTPUT:
Hello (infinite times).
Iterative Statements
• DO-WHILE LOOP:
If we want to execute loop body at least once then we should go for do-while.

SYNTAX EXAMPLE

public class ExampleDoWhile{


public static void main(String args[]){
do
System.out.println("hello");
while(true);
}}
Output:
Hello (infinite times).
Iterative Statements
• FOR LOOP:
This is the most commonly used loop and best suitable if we know the no of iterations in advance.

SYNTAX EXAMPLE

public class ExampleFor{


public static void main(String args[]){
int a=10,b=20;
for(int i=0;a<b;i++){ // i = 1
System.out.println("hello");
}
System.out.println("hi");
}}
Output:Hello (infinite times).
Iterative Statements
• FOR EACH LOOP(ENHANCED FOR LOOP):
• For each Introduced in 1.5version.
• Best suitable to retrieve the elements of arrays and collections.
• Write code to print the elements of single dimensional array by normal for loop and enhanced for loop.
Comparison of for while and do while
Transfer Statements
• BREAK STATEMENT:
We can use break statement in the following cases.
• Inside switch to stop fall-through.
• Inside loops to break the loop based on some condition.
INSIDE SWITCH INSIDE LOOPS
class Test{ public class PracticeBreakFor {
public static void main(String args[]){ public static void main(String[] args) {
int x=0; int x = 10;
switch(x) { while(x < 20){
case 0: System.out.println(x);
System.out.println("hello"); x++;
break ; if(x > 15)
case 1: break; }
System.out.println("hi"); } }
Output: Hello
}
Transfer Statements
• CONTINUE STATEMENT:
We can use continue statement to skip current iteration and continue for the next iteration.

OUTPUT:
13579
Predict the output?
What will be the result, if we try to compile and execute the following code?
class Sample{
public static void main(String[]args) {
boolean b = true;
if(b){
System.out.println(" if block ");
}
else {
System.out.println(“ else block ");
}
}
}
Java program to demonstrate the use of infinite for loop
which prints an statement  

public class ForExample {  
public static void main(String[] args) {  
    //Using no condition in for loop  
    for(;;){  
        System.out.println("infinitive loop");  
 }  
}  
}
MCQ based on while loop
What will be the result, if we try to compile and execute the following code
snippets
1.
class Sample {
public static void main(String[] args) {
while(false)
System.out.println("while loop");
}
}
Comparison of Break and continue
Arrays in Java
• An array is an indexed collection of fixed number of homogeneous data elements.
ADVANTAGE OF ARRAY:
• The main advantage of arrays is we can represent multiple values with the same name so that
readability of the code will be improved.
DISADVANTAGE OF ARRAY:
• Fixed in size that is once we created an array there is no chance of increasing or decreasing the
size based on our requirement that is to use arrays concept compulsory.
• we should know the size in advance which may not possible always.
• We can resolve this problem by using collections.
Arrays Declarations
• Single dimensional array declaration:
int[] a;//recommended to use because name is clearly separated from the type
int []a;
int a[];
• At the time of declaration we can't specify the size otherwise we will get compile time error.
int[] a;//valid
int[5] a;//invalid
• Two dimensional array declaration:
int[][] a;
int [][]a;
int a[][]; All are valid.
int[] []a;
int[] a[]
Arrays Declarations
• If we want to specify the dimension before the variable that rule is applicable only for the 1st
variable.
• Second variable onwards we can't apply in the same declaration.

• Array construction:
Every array in java is an object hence we can create by using new operator.
int[] a=new int[3];
For every array type corresponding classes are available but these classes are part of java language
and not available to the programmer level.
Arrays Creation : Rules
Rule 1: At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.
int[] a=new int[3];
int[] a=new int[];//C.E:array dimension missing

Rule 2: It is legal to have an array with size zero in java.


int[] a=new int[0];
System.out.println(a.length);//0

Rule 3: If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
int[] a=new int[-3];//R.E:NegativeArraySizeException
Arrays Creation : Rules
Rule 4: The allowed data types to specify array size are byte, short, char, int. By mistake if we are
using any other type we will get compile time error.
int[] a=new int['a'];//(valid)
byte b=10;
int[] a=new int[b];//(valid)
short s=20;
int[] a=new int[s];//(valid)
int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)
length Vs length():
length:
1. It is the final variable applicable only for arrays.
2. It represents the size of the array.
int[] x=new int[3];
System.out.println(x.length());//C.E: cannot find symbol
System.out.println(x.length);//3

length() method:
1. It is a final method applicable for String objects.
2. It returns the no of characters present in the String.
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
Is an array a primitive type or an object in Java?
An array in Java is an object.
class Test
{
public static void main(String[] args)
{ int[] ia = new int[3];
System.out.println(ia.getClass()); System.out.println(ia.getClass().getSuperclass()); } }
}
}
OUTPUT
class [I class java.lang.Object where the string "[I" is the run-time type signature for the
class object "array with component type int".
Anonymous Array in Java
• Java supports the feature of an anonymous array, so you don't need to declare the
array while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array to method.  
public class TestAnonymousArray{  
//creating a method which receives an array as a parameter  
static void printArray(int arr[]){  
for(int i=0;i<arr.length;i++)  
System.out.println(arr[i]);  }  
public static void main(String args[]){  
printArray(new int[]{10,22,44,66});//passing anonymous array to method  
}}  
ArrayStoreException
• Arrays have the property that an array of one type is assignable to an array of its
supertype, it is possible to play games with the compiler and try to trick it into
storing the wrong kind of object in an array.
• Java may not be able to check the types of all objects that you place into arrays at
compile time.
• In those cases, it’s possible to receive an ArrayStoreException at runtime if you
try to assign the wrong type of object to an array element.
• For example:
String [] strings = new String [10];
Object [] objects = strings; // alias String [] as Object []
objects[0] = new Date(); // Runtime ArrayStoreException!
JAGGED ARRAY
• Jagged arrays in java are arrays containing arrays of different length. Jagged arrays are also multidimensional arrays.
• Jagged arrays in java sometimes are also called as ragged arrays.
• public class JaggedArraysInJava
{
    public static void main(String[] args)
    {
        //One Dimensional Array of lenghth 3
        int[] OneDimensionalArray1 = {1, 2, 3};
 
        //One Dimensional Array of lenghth 4
        int[] oneDimensionalArray2 = {4, 5, 6, 7};
 
        //One Dimensional Array of lenghth 5
        int[] oneDimensionalArray3 = {8, 9, 10, 11, 12};
  ………
JAGGED ARRAY (cont…)
    //Jagged Two Dimensional Array
        int[][] twoDimensionalArray = {OneDimensionalArray1, oneDimensionalArray2, oneDimensionalArray3};
 
        //Printing elements of Two Dimensional Array
        for (int i = 0; i < twoDimensionalArray.length; i++)
        {
            for (int j = 0; j < twoDimensionalArray[i].length; j++)
            {
                System.out.print(twoDimensionalArray[i][j]+"\t");
            }
            System.out.println();
        }
    }
}
QUIZ
Q1. Select which of the following are valid array definition
1. int[] a;
2. int a[] = new int[5]
3. int a[5] = new int[5];
4. int a[] = {1,2,3};
5. int[] a = new int[]{1,2,3};
6. int[] a = new int[5]{1,2,3,4};
QUIZ
Q2. What will be the result, if we try to compile and execute the following
codes
class Sample {
public static void main(String[] args) {
int[] a = new int[5]{1,2,3};
for(int i : a)
System.out.println(i);
}
}
Summary:

In this session, you were able to :


• Learn about control statements in java
• Understand arrays its features.
References:

Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw Hill
Companies
3. John P. Flynt Thomson, Java Programming.

Video Lectures :
https://www.youtube.com/watch?v=dZb5ofv0twk

https://www.youtube.com/watch?v=-oi9Pg0128M
THANK YOU

You might also like