[go: up one dir, main page]

0% found this document useful (0 votes)
25 views23 pages

BCS306A Module 1 Question Answers

The document provides a comprehensive overview of Java programming, covering object-oriented programming principles, data types, variables, operators, and control statements. It explains the advantages of OOP over procedural programming, features of Java, and the significance of platform independence through the Java Virtual Machine (JVM). Additionally, it details various programming concepts such as tokens, keywords, literals, type casting, and operator precedence.

Uploaded by

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

BCS306A Module 1 Question Answers

The document provides a comprehensive overview of Java programming, covering object-oriented programming principles, data types, variables, operators, and control statements. It explains the advantages of OOP over procedural programming, features of Java, and the significance of platform independence through the Java Virtual Machine (JVM). Additionally, it details various programming concepts such as tokens, keywords, literals, type casting, and operator precedence.

Uploaded by

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

MODULE 1

QUESTION AND ANSWERS

An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three


OOP Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals,
Comments, Separators, The Java Keywords). Data Types, Variables, and Arrays: The Primitive
Types (Integers, Floating-Point Types, Characters, Booleans), Variables, Type Conversion and
Casting, Automatic Type Promotion in Expressions, Arrays, Introducing Type Inference with
Local Variables. Operators: Arithmetic Operators, Relational Operators, Boolean Logical
Operators, The Assignment Operator, The ? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration Statements
(while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a
for Loop, Nested Loops), Jump Statements (Using break, Using continue, return).

1. Explain the two paradigms of programming.


Procedural Programming

Procedural Programming is derived from structured programming and is based on the


concept of calling procedures, also known as routines, subroutines, or functions. It follows a
step-by-step approach to break down a task into a set of variables and routines via a sequence
of instructions. Examples of procedural programming languages include C, FORTRAN,
Pascal, and BASIC.

Key Characteristics:
 Top-Down Approach: Programs are divided into small parts called functions.
 No Access Specifiers: There are no access specifiers like private, public, or protected.
 Less Secure: Procedural programming does not have a proper way of hiding data, making
it less secure.
 No Inheritance: There is no concept of inheritance.
 Function-Centric: Functions are more important than data.
 Medium-Sized Programs: Suitable for designing medium-sized programs.
 Procedure Abstraction: Uses the concept of procedure abstraction.
 No Code Reusability: Code reusability is absent.

Object-Oriented Programming

Object-Oriented Programming (OOP) is based on the concept of objects that contain data in
the form of attributes and code in the form of methods. OOP models software design around
data or objects rather than functions and logic 2. Examples of OOP languages include Java,
C++, Python, and C#.

Key Characteristics:
 Bottom-Up Approach: Programs are divided into small parts called objects.
 Access Specifiers: Includes access specifiers like private, public, and protected.
 More Secure: Provides data hiding, making it more secure.
 Inheritance: Supports inheritance, allowing new objects to inherit characteristics from
existing ones.
 Data-Centric: Data is more important than functions.
 Large and Complex Programs: Suitable for designing large and complex programs.
 Data Abstraction: Uses the concept of data abstraction.
 Code Reusability: Code reusability is present due to inheritance.

2. List the advantage of OOPs over Procedure-oriented programming


language.

OOPs makes development and maintenance easier. But in Procedure-oriented programming


language, it is not easy to manage if code grows as project size grows.

OOPs provides data hiding whereas in Procedure-oriented programming language, global data
can be accessed from anywhere.

OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.

3. List and explain OOPs principles in Java.

Principle Description Benefit


Protects data, simplifies
Encapsulation Binds data and methods; hides internal state
debugging
Shares properties and methods between
Inheritance Promotes reuse, organizes code
classes
Polymorphism One function taking different forms Adds flexibility and scalability
Abstraction Hides complexity, shows essential features Simplifies usage, reduces clutter

4. List and explain features of JAVA.

Java is Objected Oriented High-Level Language and its features are:

1. Simple
 Java has a clean and easy-to-understand syntax.
 It removes complex features like pointers.
 Automatic garbage collection simplifies memory management.
2. Object-Oriented
 Everything in Java is treated as an object.
 Supports core OOP principles: encapsulation, inheritance, polymorphism, and
abstraction.
3. Platform Independent
 Java follows the Write Once, Run Anywhere (WORA) principle.
 Code is compiled into bytecode, which can run on any system with a Java
Virtual Machine (JVM).

4. Portable
 Bytecode is not dependent on any specific hardware or OS.
 Java programs can run on multiple platforms without modification

5. Secure
 Java provides built-in security features like bytecode verification and
sandboxing.
 It avoids direct memory access, reducing vulnerabilities like buffer overflows.

6. Robust
 Designed to handle errors gracefully, maintain stability under unexpected
conditions, and ensure the reliability of software applications.

7. Multithreaded
 Java supports concurrent execution of two or more threads.
 Ideal for applications like games, simulations, and real-time systems

8. High Performance
 Though interpreted, Java uses Just-In-Time (JIT) compilers to improve
performance.
 Efficient memory and thread management contribute to speed.

9. Distributed
 Java supports distributed computing via technologies.
 Useful for building networked applications.

10. Dynamic
 Java supports dynamic loading of classes at runtime.
 It can interact with native methods written in C or C++.

6. Justify “Compile Once and run anywhere” in Java.


Or
How platform independence is achieved in java.
Or
Explain the process of compiling and running the java application with
the example.

“Compile Once and Run Anywhere” in Java refers to its platform independence, made
possible by the Java Virtual Machine (JVM).

Java code, it is compiled into bytecode (.class files), not directly into machine-specific
instructions.

This bytecode is interpreted by the JVM, which acts as a bridge between the Java program and
the underlying hardware.
7. Explain two components of Java.

Java Development Kit (JDK) and Java Runtime Environment (JRE) are two essential
components in the Java

Feature JDK JRE


Purpose Develop and run Java programs Only run Java programs
Includes JRE + development tools JVM + class libraries
Target Users Developers End users
Tools Compiler, debugger, etc. No development tools

8. Define Token and list different types of tokens.

Token is basic building block of a program or it is smallest lexical unit of a program.

Different types of tokens are:

Keywords, Data types, Variables, Operators, Identifiers, Separators or Punctuators,


Literals and Constants.

9. What is a keyword?

Keywords are the tokens which have special meaning in the programming language.
They are also called as reserved words.
Example – for, if, else, while, etc.
10. Discuss different data types in java along with its default values.

Data type defines what type of data is stored in a variable and amount of memory
allocated for the variable. Java is strongly typed language which means a variable must
be declared before being used. Java also checks for type compatibility during assignment
or parameter passing. Different data types in java are :

11. What is variable?

Variable named memory location to store a value that can be changed anywhere in the
program.

Syntax of declaring a variable:


<data type> variable name < = value];

Example :

int a; // declaration of variable

int b = 12; // initialization of variable;

int c;

c = a + b; // dynamic initialization of variable;

12. What is constant?

Constant is named memory location to store a value that cannot be changed anywhere in the
program. ‘final’ keyword is used in java to declare constants.

13. Explain about literals in java.

Literals are fixed values in the program. Java supports several types of literals, each
corresponding to a data type:

Integer Literals

Used for whole numbers.


 Decimal: int x = 100;
 Binary (prefix 0b): int y = 0b1010; // equals 10
 Octal (prefix 0): int z = 012; // equals 10
 Hexadecimal (prefix 0x): int h = 0xA; // equals 10

Floating-Point Literals

Used for decimal numbers.


 float f = 3.14f; // Note the f suffix
 double d = 2.71828;

Character Literals

Single characters enclosed in single quotes.


 char c = 'A';
 You can also use Unicode: char u = '\u0041'; // 'A'

String Literals

Sequences of characters enclosed in double quotes.


 String s = "Hello, Java!";
Boolean Literals

Only two possible values:


 true or false

Null Literal
Represents the absence of a value for reference types.
 String str = null;

14.What is Identifier and list the rules for identifiers in Java?

An identifier is the name used to identify elements in your Java program—like variables,
arrays, methods, classes, interfaces, and more.

Rules for Naming Identifiers in Java:


 Can contain letters, digits, underscores (_), and dollar signs ($)
 Must begin with a letter (A–Z or a–z), underscore _, or dollar sign
 Cannot be a Java keyword
 Case-sensitive
 No length limit

15.What is Comment and how are comments added in java?

Comments are used to make code more readable and understandable. They are ignored by the
compiler, meaning they don’t affect how the program runs.

Single-line Comment
 Begins with //
 Used for brief explanations or notes

Multi-line Comment
 Starts with /* and ends with */
 Used for longer explanations or to temporarily disable blocks of code

16.What is Separator or punctuators?

In Java, separators (also called punctuators) are special symbols used to structure the
code and have special meaning.
Example :
Semicolon (;) – used to end a statement
Braces ({ } ) – Defines blocks of code
Comma , - used to separate statements, separate arguments in functions, etc.
17.What is whitespace character?

Whitespace characters are considered non-printable characters and they don’t produce a
visible symbol when displayed—they affect layout and spacing rather than content.

Space (' ') Separates words and symbols


Tab ('\t') Indents code for readability
Newline ('\n') Moves to the next line
Carriage Return ('\r') Used in some systems to return to the beginning of the line
Form Feed ('\f') Advances to the next page (rarely used)

18. Explain type casting and type conversion in java with example?

Type casting and type conversion are techniques used to convert a variable of one data
type to another data type.

Concept Description Performed By Example

Type Conversion Automatically converts a smaller type Java compiler int → long → float →
(Widening) to a larger type (implicit) double

Type Casting Manually converts a larger type to a Programmer double → float → long
(Narrowing) smaller type (explicit) → int → short → byte

Example (type conversion) :

int a = 10;
double b = a; // int is automatically converted to double
System.out.println(b); // Output: 10.0

Example (type casting):

double x = 10.75;
int y = (int) x; // Explicit cast from double to int
System.out.println(y); // Output: 10

19. Explain automatic type conversion in expression.

When evaluating an expression, Java automatically promotes operands to the largest data
type involved in the operation. This is called automatic type conversion. Automatic type
conversion is done only when following conditions are met.

 Two types are compatible


Numeric type is not compatible with char or Boolean.
char and boolean are not compatible with each other.
 The destination type is larger than the source type.

Example :

byte b = 10;
short s = 20;
int result = b + s; // both b and s are promoted to int
System.out.println(result); // Output: 30

int i = 5;
float f = 6.5f;
float result = i + f; // i is promoted to float
System.out.println(result); // Output: 11.5

20. List the short circuit operators and show concept using few examples.

short-circuit operators are logical operators that skip evaluating the second operand if
the result can be determined from the first operand alone. This improves performance and
avoids unnecessary computation—or even runtime errors.

Java has two short-circuit logical operators:

Operator Name Description


&& Logical AND Evaluates second operand only if the first is true
|| Logical OR Evaluates second operand only if the first is false

Example 1 : ( Using Logical AND operator)

int x = 5;
if (x > 0 && x < 10) {
System.out.println("x is between 1 and 9");
}

If x > 0 is false, Java won’t check x < 10 because the whole condition can't be
true.

Example 2 : ( Using Logical Or operator)

int y = 15;
if (y < 10 || y > 12) {
System.out.println("y is either less than 10 or greater than 12");
}

If y < 10 is true, Java won’t check y > 12 because the condition is already
satisfied.
21. List different types of operators in Java.

Operators are symbols used for calculation, comparison and joining expression.

Different types of operators in Java are:

1. Arithmetic Operators
● +: Addition
● -: Subtraction
● *: Multiplication
● /: Division
● %: Modulus (remainder)
2. Relational Operators
● ==: Equal to
● !=: Not equal to
● >: Greater than
● <: Less than
● >=: Greater than or equal to
● <=: Less than or equal to
3. Logical Operators
● &&: Logical AND
● ||: Logical OR
● !: Logical NOT

4. Bitwise Operators
● &: Bitwise AND
● |: Bitwise OR
● ^: Bitwise XOR (exclusive OR)
● ~: Bitwise NOT (complement)
● <<: Left shift
● >>: Signed right shift
● >>>: Unsigned right shift
5. Unary Operators
 + Unary plus
 - Unary minus
 ++ Increment operator
 -- Decrement operator
 ! Unary Not (logical)

6. Ternary Operator
 ?: ?:

22. Explain precedence of operators in Java with example.

Operator precedence in Java determines the order in which operators are evaluated in
expressions. When multiple operators appear in a single expression, those with higher
precedence are evaluated first. If operators have the same precedence, their
associativity (left-to-right or right-to-left) decides the evaluation order.
Precedence Level Operators Associativity
Brackets () (parentheses), [], method calls Left to Right
Unary ++, --, + (unary), - (unary), !, ~ Right to Left
*, /, % Left to Right
Arithmetic
+, - Left to Right
Shift <<, >>, >>> Left to Right
<, >, <=, >= Left to Right
Relational
==, != Left to Right
& Left to Right
Bitwise ^ Left to Right
| Left to Right
&& Left to Right
Logical
|| Left to Right
Ternary ?: Right to Left
Assignment =, +=, -=, etc. Right to Left

Example 1:

int a = 10, b = 5, c = 2;
boolean result = a + b * c > 20 && b - c < 5;
System.out.println(result); // Output: true

Example 2:

int x = 8, y = 3;
int result = (x > y) ? x + y * 2 : x - y * 2;
System.out.println(result); // Output: 14

Example 3:

int a = 5, b = 3;
a += b & 2 | 1;
System.out.println(a); // Output: 7

Example 4:

int a = 4, b = 6, c = 5;
String result = (a > b) ? "A is greater" : (b > c ? "B is greatest" : "C is greatest");
System.out.println(result); // Output: B is greatest

23. Illustrate the working of >> and >>> operators.

In Java >>> is called the unsigned right shift operator. It’s used to shift bits to the right
without preserving the sign bit, which makes it different from the regular >> operator
which is signed right shift operator.
Operator Name Sign Bit Preserved? Leftmost Bits Filled With
>> Signed right shift Yes Sign bit (0 or 1)
>>> Unsigned right shift No Always 0

For positive numbers, >> and >>> behave the same. The difference only shows up when
the number is negative, because >> preserves the sign bit while >>> does not.

Example :

int x = 8;
int y = 8;
System.out.println(x>>2);
System.out.println(y>>>2);

int a = -40;
int b = -40;
System.out.println( a>>2);
System.out.println(b>>>2);

Output :
2
2
-10
1073741814

Output above shows that

 >> and >>> behaves same for +ve nos.


 >> operator retain sign bit for -ve nos.
 >>> operator makes sign bit always 0 ( +ve)

24. Illustrate with an example working of ternary operator.

The ternary operator in Java is a shorthand for an if-else statement. It makes code more
compact and readable for simple conditions.

Syntax:
condition ? expression1 : expression2

Example :

public class TernaryExample {


public static void main(String[] args) {
int number = 7;

// Using ternary operator to check even or odd


String result = (number % 2 == 0) ? "Even" : "Odd";

System.out.println("The number is " + result);


}
}

25. Illustrate arithmetic compound statement.

An arithmetic compound statement in Java typically refers to a statement that


combines an arithmetic operation with assignment using compound assignment
operators.

Benefits :

 Cleaner and more concise code


 Reduces redundancy

Example :

public class CompoundExample {


public static void main(String[] args) {
int a = 10;

a += 5; // a = a + 5 → a becomes 15
a -= 3; // a = a - 3 → a becomes 12
a *= 2; // a = a * 2 → a becomes 24
a /= 4; // a = a / 4 → a becomes 6
a %= 5; // a = a % 5 → a becomes 1

System.out.println("Final value of a: " + a);


}
}

26. List and explain control statements in Java with programming example.

A program is normally executed sequentially which means statements are executed one after
other. All problems cannot be solved using this approach. Few problems may require few
statements to be skipped or repeated again and again. Control structures are used to alter
sequential flow of execution.

Conditional structures: ( used for skipping set of statements)

if, if-else, if-else-if, switch

Looping structures: (used for repeating a set of statements)

for, while, do-while

if syntax
if (expression) {
// statements --- these statements are executed when above expression is true and
And not executed if above expression is evaluated to true
}

Example :

int number = 10;

if (number % 2 == 0) {
System.out.println("The number is even.");
}

if-else syntax

if (expression) {
// statements -- these statements are executed when above expression is true
}
else {
// statements - these statements are executed when above expression is false
}

Example :

int age = 17;

if (age >= 18) {


System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote yet.");
}

if-else-if syntax

if (expression1)
{
// statements -- these statements are executed when above expression1 is true
}
else if(expression2)
{
// statements -- these statements are executed when above expression2 is true
}

else if (expression3)
{
// statements -- these statements are executed when above expression3 is true
}
.
.
else
{
// statements -- these statements are executed when all above expressions are
false
}

Example :

if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}

switch Statement

In Java, the if..else..if ladder executes only one block of code among many blocks. The
switch statement can be a substitute for long if..else..if ladders which generally makes
code more readable. Switch can only test for equality.

The syntax of switch statement is:

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

Example :

int day = 3; // Let's say 1 = Monday, 2 = Tuesday, ..., 7 = Sunday

switch (day) {
case 1:
System.out.println("It's Monday. Back to work!");
break;
case 2:
System.out.println("It's Tuesday. Keep going!");
break;
case 3:
System.out.println("It's Wednesday. Halfway there!");
break;
case 4:
System.out.println("It's Thursday. Almost the weekend!");
break;
case 5:
System.out.println("It's Friday. Weekend vibes!");
break;
case 6:
System.out.println("It's Saturday. Time to relax!");
break;
case 7:
System.out.println("It's Sunday. Recharge for the week!");
break;
default:
System.out.println("Invalid day number.");
}

The switch statement evaluates it's expression (mostly variable) and compares with
values (can be expression) of each case label. The switch statement executes all
statements of the matching case label. Notice, the use of break statement. This statement
terminates the execution of switch statement. The break statements are important because
if they are not used, all statements after the matching case label are executed in sequence
until the end of switch statement.

for loop syntax

for (initialization; testExpression; update expression)


{
// codes inside for loop's body
}

The initialization expression is executed only once.


Then, the test expression is evaluated. Here, test expression is a boolean expression.
If the test expression is evaluated to true,
Codes inside the body of for loop is executed.
Then the update expression is executed.
Again, the test expression is evaluated.
If the test expression is true, codes inside the body of for loop is executed and
update expression is executed.
This process goes on until the test expression is evaluated to false.
If the test expression is evaluated to false, for loop terminates.

If the test expression is never false, for loop will run forever. This is called infinite for loop.

Example :

for (int i = 1; i <= 5; i++) {


System.out.println("Number: " + i);
}

while loop syntax


The syntax of while loop is:

while (testExpression) {
// codes inside body of while loop
}

The test expression inside parenthesis is a boolean expression.

If the test expression is evaluated to true, statements inside the while loop are executed.
then, the test expression is evaluated again.
This process goes on until the test expression is evaluated to false.
If the test expression is evaluated to false, while loop is terminated.

Example :

int i = 1;

while (i <= 5) {
System.out.println("Number: " + i);
i++;
}

do-while loop syntax

The do...while loop is similar to while loop with one key difference. The body of
do...while loop is executed for once before the test expression is checked.

The syntax of do..while loop is:

do {
// codes inside body of do while loop
} while (testExpression);

The body of do...while loop is executed once (before checking the test expression). Only
then, the test expression is checked.
If the test expression is evaluated to true, codes inside the body of the loop are executed,
and the test expression is evaluated again. This process goes on until the test expression is
evaluated to false.
When the test expression is false, the do..while loop terminates.

Example :

int i = 1;

do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);

for-each loop
for-each loop in java lets looping through of each element in a collection without needing
an index. It’s clean, readable, and avoids common mistakes like off-by-one errors.

Syntax:
for (type variable : collection) {
// code to execute with each element
}

 type: The data type of the elements in the collection.


 variable: A temporary variable that holds each element during iteration.
 collection: The array or collection you're looping through.

Example :
int values[] = {14,17,45};

for (int i: values)


System.out.println(i);

Output :
14
17
45

27. Explain about local variable type inference and with example.

Local variable type reference in a feature in java that allows type of a local variable to be
determined from the type of its initializer. This is achieved using keyword ‘var’.

Example :

class TypeInferenceDemo {
public static void main(String args[])
{
var x = 10.0f;
System.out.println(((Object) x).getClass().getName());

var y = 10.0;
System.out.println(((Object) y).getClass().getName());
}
}

Output :

java.lang.Float ---- x is initialized with float value and hence datatype of x is float
java.lang.Double ---- y is initialized with double value and hence datatype of x is float
Restrictions in usage of ‘var’ :

 var counter; // not allowed as initializer is required


 var myArray = new int[3]; // this is valid
 var[] myArray = new int[3]; // invalid
 var myArray[] = new int[3]; // invalid
 local variable type inference cannot be used to declare
the exception type caught by a catch statement

try {
int result = 10 / 0;
} catch (var e) { // invalid
System.out.println("Exception caught: " + e.getMessage());
}

28. What are jump Statements and explain with example.

jump statements are used to transfer control to another part of the program. They’re
especially useful for altering the normal flow of loops. Different jump statements in java
are :

Statement Purpose Common Use Case


Exits a loop or switch
break Terminating a loop early.
block immediately
Skips the current Skipping specific values in a loop. Skips the
continue iteration and moves to lines that follow inside the loop and transfers
the next one control to update expression.
Exits from a method and Transfers control from the method to the
return
optionally returns a value statement after call to method.
goto Not supported in Java Java intentionally avoids it to keep code clean

Example (break):

for (int i = 0; i < 5; i++) {


if (i == 3) {
break; // exits the loop when i is 3
}
System.out.println(i);
}

Output of above code snippet:


0
1
2

Example (continue):
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // skips following statement when i is 3
}
System.out.println(i);
}
Output of above code snippet:
0
1
2
4

return statement:

The return statement in Java is used to exit from a method and optionally send a value
back to the caller. It’s a fundamental part of how methods communicate results.

return statement -

 Ends method execution immediately.


 Returns a value if the method is not void.
 If the method is void, return; simply exits without sending anything.

Syntax :
return value; // For methods that return something
return; // For void methods

Rules to Remember

 The return type in the method signature must match the type of value returned.
 You must use return in non-void methods.
 return can be used to exit early from a method conditionally.
 There can be multiple return statements in a method.

Example (return in a void method) :

public class Greeter {


public void greet(String name) {
if (name == null) {
return; // exits early
}
System.out.println("Hello, " + name);
}
}

29. Explain various scopes of variables in java.

Block is set of statements enclosed between curly braces ({}) and block defines the scope
of a variable. There are two types of scopes : class scope and method scope.

Method scope:
Method’s scope ends with its closing curly brace. There can be n number of scopes or
blocks inside method scope.

 A variable declared inside a scope or block is visible to all inner scopes or blocks.
 Variables are created while entering the scope and destroyed while leaving the
scope. Lifetime of a variable is confined to a scope.
 Variable in the outer scope and inner scope cannot have same name.

Example :

class scopeDemo {
public static void main(String args[])
{
int i =10;
{
//int i = 20; // invalid
int j = 30;
i = 40 ; // variables of outer scope can be accessed and modified
in inner scope
System.out.println("i "+ i); // outer scope variables are visible
in inner scope
System.out.println("j "+ j);
}
// System.out.println("j "+ j); // variable j not visible here as it is
declared in inner scope
}
}
Output :
i 40
j 30

30. Explain labeled break statement.

Normally, break only exits the innermost block. Using a labeled break, one can exit from
a block which is labeled.

Example:

public class LabeledBreakDemo {


public static void main(String[] args) {
outerLoop: // This is the label
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
if (i == 2 && j == 2) {
System.out.println("Breaking out of outer loop");
break outerLoop; // Exits the outer loop directly
}
}
}
System.out.println("Loop exited");
}
}
Output of above code:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
Breaking out of outer loop
Loop exited

31. Explain the syntax of declaration of arrays in Java.

Array is a non-primitive datatype and can store group of values of same data type. Each
value in an array is accessed using index which starts from 0;

Syntax of creating 1D array:

dataType[] arrayName = new datatype[size];


 dataType can be data type like: int, char, double, byte etc. or an object
 arrayName is an identifier

Example of 1D array:

public class OneDArrayExample {


public static void main(String[] args) {
// Declare and initialize a 1D array of integers
int[] numbers = {10, 20, 30, 40, 50};

// Print each element using a loop


System.out.println("Elements in the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
}
}

Syntax of 2D Array:

dataType[][] arrayName = new dataType[rows][columns];

public class TwoDArrayExample {


public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Print the 2D array


System.out.println("2D Array (Matrix):");
for (int i = 0; i < matrix.length; i++) { // rows
for (int j = 0; j < matrix[i].length; j++) { // columns
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // new line after each row
}
}
}

Programs

1. Develop a Java Program to convert Celsius temperature to Fahrenheit.


2. Write a java program to find area of rectangle.
3. Develop a Java program to add two matrices using command line arguments.
4. Write a Java program to perform linear search on an array elements accepted from
keyboard and key element also accepted from keyboard.
5. Develop a program to find an average among the elements {1,2,3,4,5} using for-each
loop in Java.

You might also like