Java_Programming_Notes.pdf
Document Details
Uploaded by ImpeccableLearning
Tags
Full Transcript
Java Programming NOTES OF JAVA PROGRAMMING Prepared and Compiled by CE & IT Department LJ Polytechnic STUDENT ADVISORY Dear Students, Please be informed that the notes provided by the institute offer...
Java Programming NOTES OF JAVA PROGRAMMING Prepared and Compiled by CE & IT Department LJ Polytechnic STUDENT ADVISORY Dear Students, Please be informed that the notes provided by the institute offer a concise presentation of the syllabus. While these notes are helpful for an overview and quick revision, We would strongly suggest that you refer to the prescribed textbooks / Reference book for a comprehensive understanding and thorough preparation of all exams and writing in the examination. Best regards, LJ Polytechnic. પ્રિય પ્રિદ્યાર્થીઓ, તમને જાણ કરિામા આિે છે કે સંસ્ર્થા દ્વારા િદાન કરિામાં આિેલી નોંધો અભ્યાસક્રમની સંક્ષિપ્ત િસ્તુપ્રત આપે છે. આ નોંધો પ્રિહંગાિલોકન અને ઝડપી પુનરાિતતન માટે મદદરૂપ હોઈ શકે છે તેમ છતા, અમે ભારપ ૂિતક સ ૂચન કરીએ છીએ કે પ્રિદ્યાર્થી તમામ પરીિાઓ અને પરીિામાં લેખનની વ્યાપક સમજણ અને સંપ ૂણત તૈયારી માટે માત્ર સ ૂચિેલા પાઠ્યપુસ્તકો/સંદભત પુસ્તકનો સંદભત લો. એલજે પોક્ષલટેકપ્રનક. JAVA PROGRAMMING UNIT-1 FUNDAMENTALS OF JAVA PROGRAMMING 1.1 INTRODUCTION OF JAVA Java is a high-level, object-oriented programming language that is designed to be portable, simple, and secure. It was created in the mid-1990s by James Gosling at Sun Microsystems (which is now owned by Oracle Corporation) and has since become one of the most popular programming languages in use today. One of the key features of Java is its platform independence. Java programs can run on any computer system that has a Java Virtual Machine (JVM) installed, which means that developers can write code once and run it on any platform. This makes Java an ideal language for developing web applications and mobile apps. Another important feature of Java is its object-oriented programming (OOP) model. Everything in Java is an object, which makes it easy to create reusable code and maintain large codebases. Java also has strong type checking, which helps to prevent common programming errors. Java has a vast array of libraries and frameworks that make it easy to write complex programs quickly. It is widely used for developing enterprise-level applications, web applications, mobile apps, games, and much more. In order to get started with Java programming, you will need to download and install the Java Development Kit (JDK) from Oracle's website. Once you have the JDK installed, you can use an Integrated Development Environment (IDE) such as Eclipse, IntelliJ IDEA, or NetBeans to write and debug your code. 1.2 FEATURES OF JAVA: Java is a powerful and versatile programming language with many features that make it popular among developers. Some of the key features of Java include: 1. Platform Independence: Java programs are compiled into platform-independent bytecode that can be run on any platform that has a Java Virtual Machine (JVM) installed. This makes Java programs highly portable. 2. Object-Oriented Programming: Java is a pure object-oriented programming language. Everything in Java is an object, which makes it easy to write reusable code and build complex applications. 3. Robust and Secure: Java was designed to be a secure and robust language. It has many built-in security features such as a security manager, which ensures that Java programs can run safely even in untrusted environments. JAVA PROGRAMMING 4. Multithreading: Java supports multithreading, which allows multiple threads of execution to run concurrently within a single program. This is especially useful for applications that need to perform multiple tasks at the same time. 5. High Performance: Java is known for its high performance and scalability. The JVM optimizes Java bytecode at runtime, which helps to improve the performance of Java applications. 6. Rich Libraries: Java has a vast array of libraries and frameworks that make it easy to write complex programs quickly. These libraries cover everything from network programming and database connectivity to user interface design and graphics. 7. Architecture-neutral: Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. 8. Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and automatic memory management (garbage collection). 9. Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. 10. Compiled and Interpreted: Java can be considered both a compiled and an interpreted language because its source code is first compiled into a binary byte-code. This byte-code runs on the Java Virtual Machine (JVM), which is usually a software-based interpreter. 1.3 JAVA VIRTUAL MACHINE AND BYTE CODE The Java Virtual Machine (JVM) is a key component of the Java platform. It is a software that provides an environment in which Java bytecode can be executed. The JVM interprets the bytecode and translates it into machine language that can be executed by the computer's processor. Java bytecode is a highly optimized set of instructions that is produced when Java source code is compiled. It is a platform-independent format that can be executed on any system that has a JVM installed. This means that a Java program can be developed on one platform and then run on any other platform without modification. JAVA PROGRAMMING The Java bytecode is designed to be highly optimized for execution on the JVM. It is a low-level representation of the original Java source code, and includes many optimizations such as constant folding, dead code elimination, and method in-lining. These optimizations help to improve the performance of Java programs. The JVM is responsible for interpreting and executing the bytecode. It provides a number of important features, including memory management, garbage collection, and security. The JVM also includes a just-in- time (JIT) compiler, which can dynamically compile frequently used bytecode into machine code for faster execution. Overall, the JVM and bytecode are important components of the Java platform. They provide a platform- independent way to execute Java programs, while also offering a high degree of performance, security, and reliability. 1.4 TYPES OF JAVA PROGRAM 1. Console Programs: These are text-based programs that run in a command-line interface (CLI). They are often used for simple tasks such as data input/output, system administration, or automation. 2. Desktop Applications: These are graphical user interface (GUI) programs that run on a desktop computer. They can be used for a wide range of purposes, such as word processing, video editing, or image manipulation. 3. Web Applications: These are server-side programs that run on a web server and provide services to clients via a web browser. They can be used for a wide range of purposes, such as e-commerce, social media, or content management. 4. Mobile Applications: These are programs that run on mobile devices such as smartphones and tablets. They can be used for a wide range of purposes, such as gaming, communication, or productivity. 5. Applets: These are small Java programs that run within a web browser. They are often used for interactive web applications, such as games or multimedia presentations. 6. Enterprise Applications: These are large-scale programs that are designed to run within a corporate environment. They can be used for a wide range of purposes, such as customer relationship management, supply chain management, or financial management. JAVA PROGRAMMING 1.5 BASIC CONCEPT OF OOP Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code to manipulate that data. The basic concept of OOP revolves around four principles, known as the "four pillars of OOP": Encapsulation: Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. Inheritance: Inheritance is the process of creating new classes by inheriting properties and methods from existing classes. This allows the new classes to reuse code and behaviour from the existing classes, reducing code duplication and improving code maintainability. Polymorphism: Polymorphism is the ability of objects to take on multiple forms. This allows objects to behave in different ways depending on the context in which they are used. Polymorphism is achieved through method overriding and method overloading. Abstraction: Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. 1.6 PROCEDURE ORIENTED V/S OBJECT ORIENTED 1. Data and behaviour: In POP, data and behaviour are separate concepts, with data stored in global variables and behaviour defined in procedures. In OOP, data and behaviour are combined into objects, which encapsulate both. 2. Encapsulation: Encapsulation is a key feature of OOP that allows objects to hide their internal state and expose well-defined interfaces. This helps to protect the object's data and ensures that the object's behaviour remains consistent. POP does not provide the same level of encapsulation. 3. Inheritance: Inheritance is a powerful feature of OOP that allows objects to inherit properties and behaviour from parent classes. This can help to reduce code duplication and improve code maintainability. POP does not provide a native way to implement inheritance. JAVA PROGRAMMING 4. Polymorphism: Polymorphism is another powerful feature of OOP that allows objects to take on multiple forms. This allows objects to behave in different ways depending on the context in which they are used. POP does not provide a native way to implement polymorphism. 5. Modularity: OOP provides a more modular approach to programming, with code organized into objects and classes. This makes it easier to reuse code and maintain large programs. In POP, code is organized into functions or procedures, which can be harder to reuse and maintain in large programs. 6. Scalability: OOP is generally more scalable than POP, as it allows for code to be easily extended and modified over time. In contrast, POP can become unwieldy and difficult to maintain as the size of a program grows. 1.7 BASIC PROGRAM OF JAVA public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } public: This is an access modifier that makes the class accessible to other classes in the same package or other packages. class: This keyword is used to define a new class. HelloWorld: This is the name of the class we're defining. {}: This block of code contains the class definition. public: This is an access modifier that makes the method accessible to other classes in the same package or other packages. static: This keyword makes the method a class method that can be called without creating an instance of the class. void: This keyword specifies that the method doesn't return a value. main: This is the name of the method. It's the entry point of the program and is executed when the program is run. (String[] args): This is the method's argument list. In this case, it takes an array of strings as an argument. {}: This block of code contains the method definition. JAVA PROGRAMMING System.out.println("Hello, World!"); : This line of code prints "Hello, World!" to the console. System.out is a predefined output stream in Java, and println() is a method that prints a string to the console and adds a newline character at the end. 1.8 BASIC DATA TYPES Java has several primitive data types that represent the basic building blocks of data in the language. These include: 1. byte: A byte is a signed 8-bit integer, with a range of -128 to 127. Example:byte b = 100; 2. short: A short is a signed 16-bit integer, with a range of -32,768 to 32,767. Example:short s = 5000; 3. int: An int is a signed 32-bit integer, with a range of -2,147,483,648 to 2,147,483,647. Example:int i = 100000; 4. long: A long is a signed 64-bit integer, with a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Example:long l = 1234567890L; 5. float: A float is a single-precision 32-bit floating-point number, with a range of approximately 1.4E- 45 to 3.4E+38, and a precision of about 7 decimal digits. Example:float f = 3.14f; 6. double: A double is a double-precision 64-bit floating-point number, with a range of approximately 4.9E-324 to 1.8E+308, and a precision of about 15 decimal digits. Example:double d = 3.14159; 7. boolean: A boolean represents a logical value, either true or false. Example:char c = 'A'; 8. char: A char represents a single character in Unicode, with a range of '\u0000' (or 0) to '\uffff' (or 65,535). Example:boolean b1 = true; boolean b2 = false; In addition to these primitive data types, Java also has a rich set of reference data types, such as classes, interfaces, and arrays, which are built using the primitive data types. Classes: A class is a blueprint or template for creating objects that encapsulate data and behavior. A class can contain fields (variables) to store data, and methods (functions) to perform operations on that data. Objects are instances of a class, and each object has its own set of values for the fields defined in the class. Here's an example of a simple class definition in Java: JAVA PROGRAMMING public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } Interfaces: An interface is a collection of abstract methods that define a set of behaviors that a class can implement. In Java, interfaces are used to define contracts between different classes or components in a system. A class can implement one or more interfaces, and by doing so, it agrees to provide implementations for all the methods defined in those interfaces. Here's an example of a simple interface definition in Java: public interface Drawable { public void draw(); } Arrays: An array is a collection of elements of the same data type, stored in contiguous memory locations. In Java, arrays are used to store and manipulate collections of data. Arrays can be of any data type, including primitive types and objects. Here's an example of how to create and use an array of integers in Java: int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers); System.out.println(numbers); numbers = 10; System.out.println(numbers); JAVA PROGRAMMING 1.9 OPERATORS In Java, operators are symbols that perform operations on one or more operands (values, variables, or expressions). There are several types of operators in Java, including: Arithmetic operators: Arithmetic operators are used to perform arithmetic operations on numerical values. The basic arithmetic operators in Java are: + (addition) - (subtraction) * (multiplication) / (division) % (modulus) EXAMPLE: int a = 10; int b = 5; // addition int sum = a + b; // sum = 15 // subtraction int difference = a - b; // difference = 5 // multiplication int product = a * b; // product = 50 // division int quotient = a / b; // quotient = 2 // modulus int remainder = a % b; // remainder = 0 JAVA PROGRAMMING Assignment operators: Assignment operators are used to assign values to variables. The basic assignment operator in Java is =. There are also compound assignment operators that combine arithmetic operations with assignment, such as +=, -=, *=, /=, and %=. EXAMPLE: int a = 10; int b = 5; // basic assignment a = b; // a = 5 // compound assignment a += b; // equivalent to a = a + b; a = 10 + 5 = 15 b -= a; // equivalent to b = b - a; b = 5 - 15 = -10 Comparison operators: Comparison operators are used to compare two values and return a boolean value indicating the result. The basic comparison operators in Java are: == (equal to) != (not equal to) < (less than) > (greater than) = (greater than or equal to) EXAMPLE: int a = 10; int b = 5; // equal to boolean isEqual = (a == b); // isEqual = false // not equal to boolean notEqual = (a != b); // notEqual = true // greater than boolean greaterThan = (a > b); // greaterThan = true JAVA PROGRAMMING // less than or equal to boolean lessThanOrEqual = (a (right shift) >>> (unsigned right shift) EXAMPLE: int a = 60; // 0011 1100 int b = 13; // 0000 1101 JAVA PROGRAMMING // bitwise AND int andResult = a & b; // andResult = 0000 1100 // bitwise OR int orResult = a | b; // orResult = 0011 1101 // bitwise XOR int xorResult = a ^ b; // xorResult = 0011 0001 // bitwise NOT int notResult = ~a; // notResult = 1100 0011 // left shift int leftShiftResult = a > 2; // rightShiftResult = 0000 1111 // unsigned right shift int unsignedRightShiftResult = a >>> 2; // unsignedRightShiftResult = 0000 1111 Conditional operator: The conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. It has the following syntax: condition ? value1 : value2 If the condition is true, the operator returns value1, otherwise it returns value2. EXAMPLE: int a = 10; int b = 5; // conditional operator int max = (a > b) ? a : b; // max = 10 JAVA PROGRAMMING Increment or Decrement Operator: The Java increment or decrement operators require only one operand. Increment or decrement operators are used to perform increment and decrement operations. Example : int x=10; x++ // 10 (11) ++x // 12 x-- //12 (11) --x //10 JAVA PROGRAMMING UNIT-2 CONTROL FLOW AND ARRAY 2.1 VARIABLE AND IT’S TYPE Variable is a named storage location that holds a value of a particular type. Variables are used to store and manipulate data within a program. Java variables can be classified into different types based on their characteristics and usage. 1.Local Variables: Local variables are declared within a method, constructor, or a block of code. They are accessible only within the scope where they are declared. Local variables must be initialized before they are used. Their lifespan is limited to the block in which they are declared. EXAMPLE: public class LocalVariableExample { public static void main(String[] args) { int age = 25; // local variable System.out.println("Age: " + age); } } 2.Instance Variables (Non-Static Variables): Instance variables are declared within a class but outside of any method, constructor, or block. Each instance of a class has its own copy of instance variables. They are initialized with default values if not explicitly assigned. Instance variables are accessible throughout the class and can be accessed using the object of the class. EXAMPLE: public class InstanceVariableExample { String name; // instance variable public static void main(String[] args) { InstanceVariableExample obj = new InstanceVariableExample(); JAVA PROGRAMMING obj.name = "John"; // accessing instance variable using object System.out.println("Name: " + obj.name); } } 3.Class Variables (Static Variables): Class variables are declared with the static keyword within a class but outside of any method, constructor, or block. Unlike instance variables, there is only one copy of each class variable that is shared among all instances of the class. Class variables are initialized with default values if not explicitly assigned. They can be accessed using the class name itself, without creating an instance of the class. EXAMPLE: public class ClassVariableExample { static int count; // class variable public static void main(String[] args) { ClassVariableExample.count = 10; // accessing class variable using class name System.out.println("Count: " + ClassVariableExample.count); } } 2.2 TYPE CASTING AND CONVERSION TYPE CASTING Type casting refers to the process of converting a value from one data type to another. Java supports two types of casting: implicit casting (widening) and explicit casting (narrowing). 1.Implicit Casting (Widening): This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This happens when the two data types are compatible and also when we assign the value of a smaller data type to a larger data type. EXAMPLE: public class ImplicitCastingExample { public static void main(String[] args) { JAVA PROGRAMMING int myInt = 10; double myDouble = myInt; // Implicit casting from int to double System.out.println("myInt: " + myInt); System.out.println("myDouble: " + myDouble); } } 2.Explicit Casting (Narrowing): The process of conversion of higher data type to lower data type is known as narrowing typecasting. It is not done automatically by Java but needs to be explicitly done by the programmer, which is why it is also called explicit typecasting. EXAMPLE: public class ExplicitCastingExample { public static void main(String[] args) { double myDouble = 10.5; int myInt = (int) myDouble; // Explicit casting from double to int System.out.println("myDouble: " + myDouble); System.out.println("myInt: " + myInt); } } CONVERSION Type conversion is simply the process of converting data of one data type into another. This process is known as type conversion, typecasting, or even type coercion. The Java programming language allows programmers to convert both primitive as well as reference data types. 1.Converting String to int: public class StringToIntExample { public static void main(String[] args) { String numberString = "123"; int number = Integer.parseInt(numberString); System.out.println("Number: " + number); } } JAVA PROGRAMMING 2.Converting int to String: public class IntToStringExample { public static void main(String[] args) { int number = 123; String numberString = String.valueOf(number); System.out.println("Number: " + numberString); } } 3.Converting String to double: public class StringToDoubleExample { public static void main(String[] args) { String numberString = "10.5"; double number = Double.parseDouble(numberString); System.out.println("Number: " + number); } } 2.3 WRAPPER CLASS Wrapper classes are used to provide a way to treat primitive data types as objects. Each primitive data type has a corresponding wrapper class in Java. Wrapper classes are mainly used for converting primitive types into objects, enabling them to be used in scenarios that require objects. Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Int long Long float Float double Double JAVA PROGRAMMING 2.3.1 Auto boxing The automatic conversion of primitive data type into its corresponding wrapper class is known as auto boxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short. Wrapper class Example: Primitive to Wrapper: public class WrapperExample1 { public static void main(String args[]) { //Converting int into Integer int a=20; Integer i=Integer.valueOf(a);//converting int into Integer explicitly Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a+" "+i+" "+j); } } Output: 20 20 20 2.3.2 Unboxing The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of auto boxing. Wrapper class Example: Wrapper to Primitive public class WrapperExample2 { public static void main(String args[]) { //Converting Integer to int Integer a=new Integer(3); int i=a.intValue();//converting Integer to int explicitly int j=a;//unboxing, now compiler will write a.intValue() internally JAVA PROGRAMMING System.out.println(a+" "+i+" "+j); }} Output: 333 EXAMPLE: public class WrapperExample { private int value; public WrapperExample(int value) { this.value = value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public static void main(String[] args) { WrapperExample wrapper = new WrapperExample(10); System.out.println("Initial value: " + wrapper.getValue()); wrapper.setValue(20); System.out.println("Updated value: " + wrapper.getValue()); } } JAVA PROGRAMMING 2.4 DECISION AND 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. It is one of the fundamental features of Java, which provides a smooth flow of program. 1.Decision Making statements if statements switch statement 2.Loop statements do while loop while loop for loop for-each loop 3.Jump statements break statement continue statement 1.Decision Making statements As the name suggests, decision-making statements decide which statement to execute and when. Decision- making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement. 1) If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below. Simple if statement if-else statement if-else-if ladder Nested if-statement Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true. Syntax: if(condition) { statement 1; //executes when condition is true } JAVA PROGRAMMING EXAMPLE: public class Student { 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 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 } EXAMPLE: public class Student { 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"); } } } JAVA PROGRAMMING Output: x + y is greater than 20 if-else-if ladder: 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 } EXAMPLE: public class Student { 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); } } } Output: Delhi JAVA PROGRAMMING Nested if-statement: In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-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 Student { public static void main(String[] args) { String address = "Delhi, India"; if(address.endsWith("India")) { if(address.contains("Meerut")) { System.out.println("Your city is Meerut"); }else if(address.contains("Noida")) { System.out.println("Your city is Noida"); }else { System.out.println(address.split(",")); } }else { System.out.println("You are not living in India"); } } } Output: Delhi JAVA PROGRAMMING Switch Statement: In Java, 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 which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program. Points to be noted about switch statement: The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java Cases cannot be duplicate Default statement is executed when any of the case doesn't match the value of expression. It is optional. Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed. While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. Syntax: switch (expression){ case value1: statement1; break;. case valueN: statementN; break; default: default statement; } EXAMPLE: public class Student{ public static void main(String[] args) { int num = 2; switch (num){ case 0: System.out.println("number is 0"); break; case 1: System.out.println("number is 1"); break; JAVA PROGRAMMING default: System.out.println(num); } } } Output: 2 2. Loop statements In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition. In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time. for loop while loop do-while loop for loop for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code. Syntax: for(initialization, condition, increment/decrement) { //block of statements } JAVA PROGRAMMING EXAMPLE: public class Calculattion { public static void main(String[] args) { // TODO Auto-generated method stub int sum = 0; for(int j = 1; j