0% found this document useful (0 votes)
3 views35 pages

Java Assignment 1

The document covers various fundamental concepts in Java, including lexical issues, data types, operators, and object-oriented principles. It explains the syntax for declaring arrays, control statements, and provides examples of different operators and their usage. Additionally, it discusses the significance of encapsulation, abstraction, inheritance, and polymorphism in object-oriented programming.

Uploaded by

pranavshekarc
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)
3 views35 pages

Java Assignment 1

The document covers various fundamental concepts in Java, including lexical issues, data types, operators, and object-oriented principles. It explains the syntax for declaring arrays, control statements, and provides examples of different operators and their usage. Additionally, it discusses the significance of encapsulation, abstraction, inheritance, and polymorphism in object-oriented programming.

Uploaded by

pranavshekarc
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 ASSIGNMENT 1

[Link] different lexical issues in JAVA


Ans: Java is a collection of whitespaces, identifiers, literals, comments, operators, separators
and keywords.
➢ Whitespace: It is a space, tab, or newline.
➢ Identifiers:
Names given to variables, methods, classes, etc.
Rules:
• Must start with a letter, _, or $.
• Cannot be a keyword.
• Case-sensitive.
Example – sum, StudentName.
➢ Literals (Constants):
Fixed values that do not change during execution.
Examples –
Integer: 10
Float: 3.14f
Character: 'A'
String: "Hello"
Boolean: true, false
➢ Separators:
It is used to separate tokens and terminate statements
Examples – (), {}, [], ;, ,.
➢ Comments:
Used to describe code. Ignored by compiler.
Single-line: // comment
Multi-line: /* comment */

2. Discuss the different data types supported by Java along with the default values and literals.

Ans: DONT KNOW


[Link] the statement "Compile once and run anywhere" in Java.

Ans: The statement “Compile Once, Run Anywhere” (CORA) means that a Java program, once
compiled, can run on any system without modification.

Explanation:

1. Compilation Process:
a. Java source code (.java) is compiled by the Java Compiler (javac) into bytecode
(.class file).
b. This bytecode is not machine-dependent.
2. Execution Process:
a. The Java Virtual Machine (JVM) on any platform reads and executes the
bytecode.
b. JVM converts bytecode into machine code suitable for that system.
3. Platform Independence:
a. Since each platform has its own JVM implementation, the same bytecode can run
on Windows, Linux, or macOS without recompilation

[Link] Array. Write a Java program to implement the addition of two matrixes

Ans: Array is linear data structure which is used to store homogenous type of data which is of the
same data type.

It allows us to store many values in a single variable which can be accessed using indexing which
starts form 0 to n-1.
[Link] the syntax of declaration of 1D and 2D arrays with examples.
Ans: Array is a linear data structure which is used to store homogenous type of data which is of the
same data type.
There are two types of:
❖1D ARRAY: It is an array which only one index or which holds values in horizontal or vertical manner
is known as 1D array
Syntax: datatype array-name[]; // Declaration
Array-name = new datatype[size]; // Memory allocation
Or
dataType arrayName[] = new dataType[size];

•In the above syntax, it declares the datatype of the array which determines the data type of element in
the array.
•array-name is the name of the array.
•new it is used in memory allocation of an array
•[size] it is used to declare the size of the array it is fixed and can’t be changed during execution.
Ex:-
int numbers[] ;
number= new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

❖2D ARRAY: It is an array which has 2 index, or which holds data in 2 dimensions in horizontal
and vertical space.
Syntax:
dataType arrayName[][]; // Declaration
arrayName = new dataType[rows][cols]; // Memory allocation
Or
dataType arrayName[][] = new dataType[rows][cols];

•In the above syntax, it declares the datatype of the array which determines the data type of element in
the array.
•array-name is the name of the array.
•new it is used in memory allocation of an array.
• [rows][cols]: it determines the size of the rows and columns in the array
Ex:
int matrix[][] = new int[2][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;

[Link] the following operator with examples a. Unary b. Arithmetic c. Shift d. Relational e. Bitwise f.
Logical g. Ternary h. Assignment
Ans:
An operator is a symbol that performs a specific operation on one, two, or three operands and
produces a result.
Java supports various types of operators, as discussed below.

a) Unary Operators

Unary operators operate on a single operand.


They are used to increment/decrement a value, negate an expression, or invert a boolean
value.

Operator Description Example Result

+ Unary plus +a Returns a

- Unary minus -a Negates the value

Increases value
++ Increment a++ or ++a
by 1

Decreases value
-- Decrement a-- or --a
by 1

True → False or
! Logical NOT !flag
False → True

Example:

int a = 10;

[Link](++a); // 11 (pre-increment)
[Link](a--); // 11 (then a becomes 10)

boolean flag = false;

[Link](!flag); // true

b) Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations such as addition,


subtraction, multiplication, etc.

Operator Description Example Result

+ Addition a+b Sum of a and b

- Subtraction a-b Difference of a and b

* Multiplication a*b Product of a and b

/ Division a/b Quotient of a divided by b

Remainder of a divided by
% Modulus a%b
b

Example:

int a = 10, b = 3;

[Link](a + b); // 13

[Link](a % b); // 1

c) Shift Operators

Shift operators are used to shift bits of a number to the left or right.

Operator Description Example Result

Multiplies a by
<< Left shift a << 2

>> Right shift a >> 2 Divides a by 2²

Shifts right with


>>> Unsigned right shift a >>> 2
zero fill

Example:
int a = 8; // Binary: 1000

[Link](a << 1); // 16 (10000)

[Link](a >> 1); // 4 (0100)

d) Relational Operators

These operators compare two values and return a boolean (true or false).

Operator Description Example Result

== Equal to a == b True if a equals b

True if a not equal


!= Not equal to a != b
to b

> Greater than a>b True if a > b

< Less than a<b True if a < b

>= Greater than or equal to a >= b True if a ≥ b

<= Less than or equal to a <= b True if a ≤ b

Example:

int a = 5, b = 10;

[Link](a < b); // true

[Link](a == b); // false

e) Bitwise Operators

These operators work on bits (binary representation) of numbers.

Operator Description Example Result

1 if both bits are


& Bitwise AND a&b
1

` ` Bitwise OR `a

1 if bits are
^ Bitwise XOR a^b
different

~ Bitwise NOT ~a Inverts all bits


Example:

int a = 5, b = 3; // Binary: 0101, 0011

[Link](a & b); // 1 (0001)

[Link](a | b); // 7 (0111)

[Link](a ^ b); // 6 (0110)

f) Logical Operators

Logical operators are used to combine two or more conditions and return a boolean result.

Operator Description Example Result

True if both conditions


&& Logical AND (a > b) && (a > c)
true

` ` Logical OR

! Logical NOT !(a > b) Reverses result

Example:

int a = 10, b = 5, c = 15;

[Link]((a > b) && (a > c)); // false

[Link]((a > b) || (a > c)); // true

g) Ternary Operator

The ternary operator (?:) is a shorthand for an if–else statement.


It takes three operands.

Syntax:

variable = (condition) ? expression1 : expression2;


Example:

int a = 10, b = 20;

int max = (a > b) ? a : b;

[Link]("Maximum = " + max); // Output: 20

h) Assignment Operators

Assignment operators are used to assign values to variables.

Equivalent
Operator Example
To

Assign value
= a=b
of b to a

+= a += b a=a+b

-= a -= b a=a-b

*= a *= b a=a*b

/= a /= b a=a/b

%= a %= b a=a%b

Example:

int a = 10;

a += 5; // a = a + 5 → 15

a *= 2; // a = a * 2 → 30

[Link](a); // 30

7. Explain object-oriented principles.


Ans: The main principles (features) of Object-Oriented Programming are:
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1. Encapsulation

Definition:
Encapsulation is the process of wrapping data (variables) and methods (functions) that
operate on the data into a single unit (class).

It helps in data hiding — making data private and accessible only through public methods
(getters/setters).

* Protects data from unauthorized access.

* Improves code maintainability and flexibility.

2. Abstraction

Definition:
Abstraction means showing only essential features and hiding the implementation details
from the user.

It focuses on what an object does rather than how it does it.

Achieved by:

• Using abstract classes


• Using interfaces
3. Inheritance

Definition:
Inheritance is the process by which one class acquires the properties and behaviors (fields and
methods) of another class.

The existing class is called the superclass (parent), and the derived class is called the subclass
(child).

4. Polymorphism

Definition:
Polymorphism means one name, many forms — i.e., the ability of an object to behave in
multiple ways depending on the context.
There are two types of polymorphism in Java:

Type Description Example

Compile-time Achieved by method


Same method name with different parameter lists
(Static) overloading

Subclass provides specific implementation of superclass


Run-time (Dynamic) Achieved by method overriding
method
[Link] a Java program to sort the elements using a loop.
9. Explain different types of control, conditional, and looping statements in JAVA.
Ans:

Control Statements in Java

Definition:
Control statements in Java are used to control the flow of execution of a program.
They help in decision-making, looping, and jumping from one part of the code to another.

1. Conditional (Decision-Making) Statements

Conditional statements help in executing certain parts of code only when a condition is true.

(a) if Statement

Definition:
The if statement is a one-way branch statement.
It executes a block of code only when the specified condition is true.

Syntax:

if (condition) {
// statements
}

Example:

if (a > b) {
[Link]("a is greater");
}

(b) if-else Statement

Definition:
The if-else statement is a two-way branch statement.
It executes one block if the condition is true and another if it is false.

Syntax:

if (condition) {
// statements if true
} else {
// statements if false
}

Example:

if (marks >= 40)


[Link]("Pass");
else
[Link]("Fail");

(c) if-else-if Ladder

Definition:
It is used to check multiple conditions sequentially.
Only the first true condition’s block gets executed.
Syntax:

if (condition1)
// statements
else if (condition2)
// statements
else
// statements

Example:

if (marks >= 75)


[Link]("Distinction");
else if (marks >= 60)
[Link]("First Class");
else
[Link]("Fail");

(d) Nested if Statement

Definition:
A nested if means an if statement inside another if.
It allows multiple levels of decision-making.

Syntax:

if (condition1) {
if (condition2) {
// statements
}
}

Example:

if (a > 0) {
if (a < 10)
[Link]("a is between 1 and 9");
}

(e) switch Statement

Definition:
The switch statement is a multi-way branch statement.
It executes one case block depending on the value of a variable.

Syntax:

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

Example:

switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Invalid day");
}

2. Looping (Iteration) Statements

Definition:
Looping statements are used to execute a block of code repeatedly as long as a condition is
true.
They help in performing repetitive tasks efficiently.

(a) for Loop

Definition:
The for loop is used when the number of iterations is known in advance.
It repeats a block of code for a specified number of times.

Syntax:

for(initialization; condition; increment/decrement) {


// statements
}

Example:

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


[Link](i);
}

(b) while Loop

Definition:
The while loop is used when the number of iterations is not known beforehand.
It executes the block as long as the condition is true.

Syntax:

while(condition) {
// statements
}

Example:
int i = 1;
while(i <= 5) {
[Link](i);
i++;
}

(c) do-while Loop

Definition:
The do-while loop executes the block at least once before checking the condition.
It is a post-tested loop.

Syntax:

do {
// statements
} while(condition);

Example:

int i = 1;
do {
[Link](i);
i++;
} while(i <= 5);

(d) Enhanced for Loop (for-each Loop)

Definition:
The enhanced for loop is used to traverse arrays or collections easily.
It eliminates the need for counters or index variables.

Syntax:
for(datatype variable : arrayname) {
// statements
}

Example:

int arr[] = {10, 20, 30};


for(int x : arr) {
[Link](x);
}

3. Jump Statements

Definition:
Jump statements are used to alter the normal sequence of execution in a program.
They transfer control to another part of the program.

(a) break Statement

Definition:
The break statement is used to terminate the loop or switch immediately.
Control moves to the statement after the loop.

Syntax:

break;

Example:

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


if(i == 3)
break;
[Link](i);
}
(b) continue Statement

Definition:
The continue statement skips the current iteration of the loop.
The loop then continues with the next iteration.

Syntax:

continue;

Example:

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


if(i == 3)
continue;
[Link](i);
}

(c) return Statement

Definition:
The return statement is used to exit from the current method.
It can also return a value to the calling method.

Syntax:

return value;

Example:

int add(int a, int b) {


return a + b;
}
[Link] classes and objects with syntax and example program.
Ans:
Class

A class is a user-defined data type that contains data members (variables) and member
functions (methods) which operate on those data members.

Syntax:

Example:

Object

An object is an instance of a class.


It is created using the new keyword and represents real-world entities.
Syntax:

Example Program:

Output:
[Link] are constructors? Explain two types of constructors with an example program

A constructor in Java is a special method that is used to initialize objects of a class. It has the
same name as the class and does not have any return type, not even void.

When an object is created using the new keyword, the constructor is automatically invoked.

Syntax:

Types of Constructors:

Java supports two main types of constructors:

1. Default Constructor
2. Parameterized Constructor

1. Default Constructor : A constructor with no parameters is called a default constructor.


If no constructor is defined by the user, Java automatically provides one.
Syntax:

Example:

2. Parameterized Constructor

A constructor that accepts arguments to initialize data members with specific values.

Syntax:
Example:

[Link] the various access specifiers in Java with an example

Ans: Access Specifiers in Java

Access specifiers in Java are keywords used to control the visibility (scope) of classes,
methods, variables, and constructors.
They define from where these members can be accessed — within the same class, within the
package, by subclasses, or from other packages.

Java provides four types of access specifiers:

1. private
2. default (package-level)
3. protected
4. public
1. private

The private access specifier is the most restrictive level of access.


Members declared as private can be accessed only within the same class and are not visible
to any other class, even if it is in the same package or a subclass in another package.

2. default (package-level)

If no access specifier is mentioned, it becomes default (package-level).


Such members can be accessed within the same class and same package, but cannot be
accessed from classes of another package.
It provides package-level visibility.

3. protected

The protected access specifier allows members to be accessed within the same class, within
the same package, and also in subclasses (even if the subclass is in another package)
through inheritance.
It provides more accessibility than default, but still offers some level of security.

4. public

The public access specifier is the least restrictive level of access.


Members declared as public can be accessed from anywhere — within the same class, same
package, subclasses in different packages, and from any external package.
It provides global visibility.
13. Explain the use of this in JAVA with an example.

Ans: Use of this in Java

• The keyword this is used to refer to the current object of a class.


• It is mainly used to differentiate between instance variables and local variables when
they have the same name.
• this can also be used to call constructors or methods of the current class.
• It should be used only in non-static methods or constructors.
[Link] Java Garbage collection.
Ans: Java Garbage Collection
• Garbage Collection (GC) automatically frees memory by removing objects that are no
longer referenced.
• Helps prevent memory leaks and manages memory efficiently.

Key Points:

1. Unreferenced Objects: Objects with no references are eligible for GC.


2. Automatic Memory Management: JVM runs GC automatically, programmer need not
free memory manually.
3. Methods:
a. [Link]() : Suggests JVM to run garbage collection.
b. finalize() : Called before an object is destroyed.
[Link] a JAVA program to add TWO matrices of suitable order N (The
value of N should be read from command line arguments).
[Link] a stack class to hold a maximum of 10 integers with suitable
methods. Develop a JAVA main method to illustrate Stack operations

TOOOOOOO BIIIGGGG
ANS: import [Link];

class Stack {
private int[] arr = new int[10];
private int top = -1;

void push(int x) {
if(top == 9)
[Link]("Stack Overflow");
else
arr[++top] = x;
}
void pop() {
if(top == -1)
[Link]("Stack Underflow");
else
[Link](arr[top--] + " popped");
}

void peek() {
if(top == -1)
[Link]("Stack is empty");
else
[Link]("Top element: " + arr[top]);
}

void display() {
if(top == -1)
[Link]("Stack is empty");
else {
[Link]("Stack elements: ");
for(int i = 0; i <= top; i++)
[Link](arr[i] + " ");
[Link]();
}
}

int size() {
return top + 1;
}
boolean isEmpty() {
return top == -1;
}
}

public class StackDemo {


public static void main(String[] args) {
Stack s = new Stack();
Scanner sc = new Scanner([Link]);
int choice, value;

do {
[Link]("\[Link] [Link] [Link] [Link] [Link] [Link]
[Link]");
[Link]("Enter choice: ");
choice = [Link]();

switch(choice) {
case 1:
[Link]("Enter value to push: ");
value = [Link]();
[Link](value);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]();
break;
case 5:
[Link]("Stack size: " + [Link]());
break;
case 6:
[Link]("Is stack empty? " + [Link]());
break;
case 7:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice");
}
} while(choice != 7);

[Link]();
}
}

You might also like