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

Java Keywords and Control Statements Guide

Uploaded by

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

Java Keywords and Control Statements Guide

Uploaded by

abhinavrajnair
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Keywords

Java keywords are also known as reserved words. Keywords are particular words that
act as a key to a code. These are predefined words by Java so they cannot be used as
a variable or object name or class name.

List of Java Keywords


A list of Java keywords or reserved words are given below:

1. abstract: Java abstract keyword is used to declare an abstract class. An abstract


class can provide the implementation of the interface. It can have abstract and
non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type.
It can hold True and False values only.
3. break : Java break keyword is used to break the loop or switch statement. It
breaks the current flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data
values.
5. case: Java case keyword is used with the switch statements to mark blocks of
text.
6. catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
7. char : Java char keyword is used to declare a variable that can hold unsigned
16-bit Unicode characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.
10. default: Java default keyword is used to specify the default block of code in a
switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can
iterate a part of the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.
13. else: Java else keyword is used to indicate the alternative branches in an if
statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant
value. It is used with a variable. It is used to restrict the user from updating the
value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure.
This block is always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is
true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and
accessible to the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an
instance of the specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface: Java interface keyword is used to declare an interface. It can have
only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit
integer.
27. native: Java native keyword is used to specify that a method is implemented in
native code using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes
the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible
within the package and outside the package but through inheritance only. It
can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an
item is accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution
is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.
36. static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure
portability.
38. super: Java super keyword is a reference variable that is used to refer to parent
class objects. It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes
code based on test value. The switch statement tests the equality of a variable
against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections
or methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or
constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The
throw keyword is mainly used to throw custom exceptions. It is followed by an
instance.
43. throws: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return
value.
47. volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part
of the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.
true, false, and null are not keywords, but they are literals and
reserved words that cannot be used as identifiers.
goto Not in use, and has no function
const Defines a constant. Not in use - use final instead

Java Control Statements | Control Flow in Java


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.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

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.

34M
651
Java Try Catch

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) 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 of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Consider the following example in which we have used the if statement in the java
code.

[Link]

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. [Link]("x + y is greater than 20");
7. }
8. }
9. }

Output:

x + y is greater than 20

2) 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:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }

Output:

x + y is greater than 20
3) 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 of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }

Output:

Delhi
4. 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 of Nested if-statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4. if([Link]("India")) {
5. if([Link]("Meerut")) {
6. [Link]("Your city is Meerut");
7. }else if([Link]("Noida")) {
8. [Link]("Your city is Noida");
9. }else {
10. [Link]([Link](",")[0]);
11. }
12. }else {
13. [Link]("You are not living in India");
14. }
15. } }

Output:

Delhi
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:

o The case variables can be int, short, byte, char, or enumeration. String type is
also supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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.
The syntax to use the switch statement is given below.

switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}

Consider the following example to understand the flow of the switch statement.

// Java Program to check the size


// using the switch...case statement
class Main {
public static void main(String[] args) {
int number = 44;
String size;
// switch statement to check size
switch (number) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
// match the value of week
case 44:
size = "Large";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
}
[Link]("Size: " + size);
}
}

Output:

Size: Large

Example: Simple Calculator using Java switch Statement.

import [Link];
class Main {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
// create an object of Scanner class
Scanner input = new Scanner([Link]);
// ask users to enter operator
[Link]("Choose an operator: +, -, *, or /");
operator = [Link]().charAt(0);
// ask users to enter numbers
[Link]("Enter first number");
number1 = [Link]();

[Link]("Enter second number");


number2 = [Link]();

switch (operator) {

// performs addition between numbers


case '+':
result = number1 + number2;
[Link](number1 + " + " + number2 + " = " + result);
break;
// performs subtraction between numbers
case '-':
result = number1 - number2;
[Link](number1 + " - " + number2 + " = " + result);
break;
// performs multiplication between numbers
case '*':
result = number1 * number2;
[Link](number1 + " * " + number2 + " = " + result);
break;
// performs division between numbers
case '/':
result = number1 / number2;
[Link](number1 + " / " + number2 + " = " + result);
break;
default:
[Link]("Invalid operator!");
break;
}
[Link]();
}
}

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.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, 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.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

The flow chart for the for-loop is given below.


Consider the following example to understand the proper functioning of the for loop
in java.

[Link]

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax
to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Consider the following example to understand the functioning of the for-each loop in
Java.

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to
use a while loop. Unlike for loop, the initialization and increment/decrement doesn't
take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start
of the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.

The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the
loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in
Java.

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the
for loop.

[Link]

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

[Link]

1. public class Calculation {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. [Link](k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }

Output:

0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

1. public class ContinueExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. [Link](j);
14. }
15. }
16. }
17.
18. }

Output:

0
1
2
3
5
1
2
3
5
2
3
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. Since Java 7, you
can use strings in the switch statement.

In other words, the switch statement tests the equality of a variable against multiple
values.

Points to Remember

o There can be one or N number of case values for a switch expression.


o The case value must be of switch expression type only. The case value must
be literal or constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-
time error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
o 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.
o The case value can have a default label which is optional.

Syntax:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Flowchart of Switch Statement

41.6M
784
Difference between JDK, JRE, and JVM

Example:

[Link]

1. public class SwitchExample {


2. public static void main(String[] args) {
3. //Declaring a variable for switch expression
4. int number=20;
5. //Switch expression
6. switch(number){
7. //Case statements
8. case 10: [Link]("10");
9. break;
10. case 20: [Link]("20");
11. break;
12. case 30: [Link]("30");
13. break;
14. //Default case statement
15. default:[Link]("Not in 10, 20 or 30");
16. }
17. }
18. }
Test it Now

Output:

20

Finding Month Example:

[Link]

1. //Java Program to demonstrate the example of Switch statement


2. //where we are printing month name for the given number
3. public class SwitchMonthExample {
4. public static void main(String[] args) {
5. //Specifying month number
6. int month=7;
7. String monthString="";
8. //Switch statement
9. switch(month){
10. //case statements within the switch block
11. case 1: monthString="1 - January";
12. break;
13. case 2: monthString="2 - February";
14. break;
15. case 3: monthString="3 - March";
16. break;
17. case 4: monthString="4 - April";
18. break;
19. case 5: monthString="5 - May";
20. break;
21. case 6: monthString="6 - June";
22. break;
23. case 7: monthString="7 - July";
24. break;
25. case 8: monthString="8 - August";
26. break;
27. case 9: monthString="9 - September";
28. break;
29. case 10: monthString="10 - October";
30. break;
31. case 11: monthString="11 - November";
32. break;
33. case 12: monthString="12 - December";
34. break;
35. default:[Link]("Invalid Month!");
36. }
37. //Printing month of the given number
38. [Link](monthString);
39. }
40. }

Output:

7 - July

Program to check Vowel or Consonant:

If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.

[Link]

1. public class SwitchVowelExample {


2. public static void main(String[] args) {
3. char ch='O';
4. switch(ch)
5. {
6. case 'a':
7. [Link]("Vowel");
8. break;
9. case 'e':
10. [Link]("Vowel");
11. break;
12. case 'i':
13. [Link]("Vowel");
14. break;
15. case 'o':
16. [Link]("Vowel");
17. break;
18. case 'u':
19. [Link]("Vowel");
20. break;
21. case 'A':
22. [Link]("Vowel");
23. break;
24. case 'E':
25. [Link]("Vowel");
26. break;
27. case 'I':
28. [Link]("Vowel");
29. break;
30. case 'O':
31. [Link]("Vowel");
32. break;
33. case 'U':
34. [Link]("Vowel");
35. break;
36. default:
37. [Link]("Consonant");
38. }
39. }
40. }
Output:

Vowel

Java Switch Statement is fall-through


The Java switch statement is fall-through. It means it executes all statements after the
first match if a break statement is not present.

Example:

[Link]

1. //Java Switch Example where we are omitting the


2. //break statement
3. public class SwitchExample2 {
4. public static void main(String[] args) {
5. int number=20;
6. //switch expression with int value
7. switch(number){
8. //switch cases without break statements
9. case 10: [Link]("10");
10. case 20: [Link]("20");
11. case 30: [Link]("30");
12. default:[Link]("Not in 10, 20 or 30");
13. }
14. }
15. }
Test it Now

Output:

20
30
Not in 10, 20 or 30

Java Switch Statement with String


Java allows us to use strings in switch expression since Java SE 7. The case statement
should be string literal.

Example:

[Link]
1. //Java Program to demonstrate the use of Java Switch
2. //statement with String
3. public class SwitchStringExample {
4. public static void main(String[] args) {
5. //Declaring String variable
6. String levelString="Expert";
7. int level=0;
8. //Using String in Switch expression
9. switch(levelString){
10. //Using String Literal in Switch case
11. case "Beginner": level=1;
12. break;
13. case "Intermediate": level=2;
14. break;
15. case "Expert": level=3;
16. break;
17. default: level=0;
18. break;
19. }
20. [Link]("Your Level is: "+level);
21. }
22. }
Test it Now

Output:

Your Level is: 3

Java Nested Switch Statement


We can use switch statement inside other switch statement in Java. It is known as
nested switch statement.

Example:

[Link]

1. //Java Program to demonstrate the use of Java Nested Switch


2. public class NestedSwitchExample {
3. public static void main(String args[])
4. {
5. //C - CSE, E - ECE, M - Mechanical
6. char branch = 'C';
7. int collegeYear = 4;
8. switch( collegeYear )
9. {
10. case 1:
11. [Link]("English, Maths, Science");
12. break;
13. case 2:
14. switch( branch )
15. {
16. case 'C':
17. [Link]("Operating System, Java, Data Structure");
18. break;
19. case 'E':
20. [Link]("Micro processors, Logic switching theory");

21. break;
22. case 'M':
23. [Link]("Drawing, Manufacturing Machines");
24. break;
25. }
26. break;
27. case 3:
28. switch( branch )
29. {
30. case 'C':
31. [Link]("Computer Organization, MultiMedia");
32. break;
33. case 'E':
34. [Link]("Fundamentals of Logic Design, Microelectro
nics");
35. break;
36. case 'M':
37. [Link]("Internal Combustion Engines, Mechanical Vi
bration");
38. break;
39. }
40. break;
41. case 4:
42. switch( branch )
43. {
44. case 'C':
45. [Link]("Data Communication and Networks, Multi
Media");
46. break;
47. case 'E':
48. [Link]("Embedded System, Image Processing");
49. break;
50. case 'M':
51. [Link]("Production Technology, Thermal Engineerin
g");
52. break;
53. }
54. break;
55. }
56. }
57. }
Test it Now

Output:

Data Communication and Networks, MultiMedia

Java Enum in Switch Statement


Java allows us to use enum in switch statement. Java enum is a class that represent the
group of constants. (immutable such as final variables). We use the keyword enum and
put the constants in curly braces separated by comma.

Example:

[Link]

1. //Java Program to demonstrate the use of Enum


2. //in switch statement
3. public class JavaSwitchEnumExample {
4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
5. public static void main(String args[])
6. {
7. Day[] DayNow = [Link]();
8. for (Day Now : DayNow)
9. {
10. switch (Now)
11. {
12. case Sun:
13. [Link]("Sunday");
14. break;
15. case Mon:
16. [Link]("Monday");
17. break;
18. case Tue:
19. [Link]("Tuesday");
20. break;
21. case Wed:
22. [Link]("Wednesday");
23. break;
24. case Thu:
25. [Link]("Thursday");
26. break;
27. case Fri:
28. [Link]("Friday");
29. break;
30. case Sat:
31. [Link]("Saturday");
32. break;
33. }
34. }
35. }
36. }
Test it Now

Output:

Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

Java Wrapper in Switch Statement


Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch
statement.

Example:

[Link]

1. //Java Program to demonstrate the use of Wrapper class


2. //in switch statement
3. public class WrapperInSwitchCaseExample {
4. public static void main(String args[])
5. {
6. Integer age = 18;
7. switch (age)
8. {
9. case (16):
10. [Link]("You are under 18.");
11. break;
12. case (18):
13. [Link]("You are eligible for vote.");
14. break;
15. case (65):
16. [Link]("You are senior citizen.");
17. break;
18. default:
19. [Link]("Please give the valid age.");
20. break;
21. }
22. }
23. }
Test it Now

Output:
You are eligible for vote.

[Link]

1. //Java For-each loop example which prints the


2. //elements of the array
3. public class ForEachExample {
4. public static void main(String[] args) {
5. //Declaring an array
6. int arr[]={12,23,44,56,78};
7. //Printing array using for-each loop
8. for(int i:arr){
9. [Link](i);
10. }
11. }
12. }
Test it Now

Output:

12
23
44
56
78

Java Labeled For Loop


We can have a name of each Java for loop. To do so, we use label before the for loop.
It is useful while using the nested for loop as we can break/continue specific for loop.

Note: The break and continue keywords breaks or continues the innermost for loop
respectively.

Syntax:

1. labelname:
2. for(initialization; condition; increment/decrement){
3. //code to be executed
4. }

Common questions

Powered by AI

The 'implements' keyword in Java is preferred over 'extends' when a class needs to adopt behavior defined in one or more interfaces, enabling multiple inheritance of type, which Java does not support directly through classes. By implementing an interface, a class promises to provide concrete implementations for all abstract methods declared in the interfaces, enabling polymorphic behavior and separation of method specification from implementation. This is particularly useful when a class needs to adhere to multiple roles or functionalities defined across different interfaces, ensuring a flexible and scalable design pattern in object-oriented systems. In contrast, 'extends' is used for single inheritance between classes .

The 'try-catch-finally' block in Java is a mechanism within a method to handle exceptions where 'try' encloses code that might throw an exception, 'catch' handles the exception, and 'finally' executes code regardless of whether an exception occurred. This allows for graceful degradation of the program, enabling resource release and smooth error recovery. On the other hand, the 'throws' keyword is used in a method signature to declare that a method might throw exceptions and need to be handled externally, promoting modular error handling. While 'try-catch-finally' deals directly with exception handling within a method's context, 'throws' provides a broader contract for exception propagation and handling outside the method .

In Java, 'enum' types can be used within 'switch' statements to define a fixed set of constants, enforcing type safety and improving code clarity. Since enums represent a specific group of related constants, they can be utilized in switches to test against enumerated values, reducing the likelihood of errors associated with arbitrary literals. Using enums within switch statements also enhances code readability, allowing developers to express a direct mapping between constants and specific logic blocks. This way, enums in switches help maintain clean, readable, and error-reduced code when dealing with a predefined set of possible values .

The 'void' keyword in Java signifies that a method does not return any value. It is essential in method declarations to specify the method's behavior explicitly as a procedure that performs tasks without providing output data. This distinction is crucial when defining actions within a class, as it clarifies that the method's purpose is procedural rather than functional. The use of 'void' ensures that memory is managed efficiently since no space is allocated for return storage, facilitating clearer code intent and performance optimization when a return value is not needed .

The 'synchronized' keyword in Java is used to ensure that critical sections or methods are accessed by only one thread at a time, providing thread-safe process execution. It locks an object for any shared resource and releases the lock during the completion of the thread execution. This is crucial in concurrent programming to prevent issues such as thread interference and memory consistency errors, which can result in incorrect behavior or corrupted data. By managing threads accessing shared resources, 'synchronized' ensures sequential execution of critical code sections, maintaining data integrity and enabling safe multithreaded operations .

The 'final' keyword in Java is used to make a variable a constant, meaning its value cannot be changed once initialized. When applied to variables, it restricts any further modification, ensuring data integrity through the code execution. Attempting to reassign a new value to a 'final' variable results in a compile-time error, which helps in maintaining a fixed state or logic throughout the program execution .

The 'strictfp' keyword in Java signifies that floating-point calculations within a method or class will follow IEEE 754 standards, ensuring consistent results across different platforms. This is significant for portability, as 'strictfp' guarantees that the precision and range for floating-point arithmetic are maintained uniformly, regardless of underlying hardware or operating system variations. Applying 'strictfp' is particularly important in scientific computations where predictable and precise floating-point behavior is critical to maintaining accuracy and integrity of results across diverse environments .

The 'switch' keyword in Java controls the flow by testing the equality of a variable against multiple values, unlike 'if' statements which evaluate a Boolean condition. A switch statement evaluates cases based on literal or constant values and supports types like byte, short, int, long, enumerated values, and strings. The 'switch' statement executes blocks of code based on a matched case value and can include a default label to handle cases that do not match any specified case. While 'if' statements are more suitable to evaluate conditions leading to two outcomes (true or false), 'switch' statements are preferred when a variable needs to be compared against several discrete values .

The 'abstract' keyword in Java is used to define abstract classes and methods. An abstract class serves as a blueprint, providing a partial implementation for other classes, allowing for the creation of class hierarchies. Abstract methods, declared within an abstract class, do not have an implementation and are meant to be overridden in subclasses, enforcing a certain structure across related classes. This supports polymorphism and dynamic method resolution by allowing subclasses to provide specific implementations tailored to their roles in the application. Abstract classes thus enable a level of abstraction that aids in designing robust and scalable object-oriented systems .

The 'instanceof' keyword in Java plays a crucial role in runtime type checking by determining whether an object is an instance of a specified class or subclass or implements a particular interface. It returns a Boolean value and is used to prevent ClassCastExceptions by ensuring that the object being cast is indeed an instance of the target class type, thus enabling safer casting in the code. This keyword is essential in scenarios where polymorphic behavior is prevalent and can aid in implementing decision-making processes based on the object type .

You might also like