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

Unit1 (Java)

The document provides an overview of Java programming, covering its structure, buzzwords, operators, command line arguments, control statements, primitive data types, and type casting. It includes examples for each concept, demonstrating how to write and execute Java programs effectively. Key topics include the Java program structure, the use of operators, control flow mechanisms, and data type handling.

Uploaded by

siddhardhar471
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)
3 views10 pages

Unit1 (Java)

The document provides an overview of Java programming, covering its structure, buzzwords, operators, command line arguments, control statements, primitive data types, and type casting. It includes examples for each concept, demonstrating how to write and execute Java programs effectively. Key topics include the Java program structure, the use of operators, control flow mechanisms, and data type handling.

Uploaded by

siddhardhar471
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

UNIT-1

[Link] and explain the Java program structure with a suitable example and, also discuss the
compilation and execution steps
A Java program follows a specific structure here are the main parts
[Link] declaration (optional):
Groups related classes together.
Example: package mypackage;

[Link] statements (optional):


Used to include other Java classes/packages into the program.
Example: import [Link];

[Link] declaration (mandatory):


Java is an Object-Oriented language; everything must be inside a class.
Example: public class MyProgram { ... }

[Link] method (mandatory):


The entry point of every Java program.
Signature:
public static void main(String[] args)

public → Accessible everywhere


static → No need to create an object to call it
void → Does not return anything
String[] args → Command-line arguments

[Link] inside :
Code to perform tasks like input, output, calculations etc..

Example program:

Package declaration (optional)


package mypackage;

// Import statements (optional)


import [Link];

// Class definition
public class MyProgram {
// Main method
public static void main(String[] args) {
// Statements / Code
[Link]("Hello, Java!");
}
}
2)Explain the Java buzz words
Java Buzzwords

Simple:
Java is easy to learn, write and understand.
It removed confusing features like pointers, operator overloading, multiple inheritance
(using classes).
Has a clean, simple syntax close to C/C++.

Object-Oriented:
Everything in Java is based on objects and classes.
Supports OOP principles: Encapsulation, Inheritance, Polymorphism, Abstraction.

Platform-Independent (Write Once, Run Anywhere – WORA):


Java programs are compiled into bytecode, which runs on the Java Virtual Machine (JVM).
The same program can run on Windows, Linux, or Mac without modification.

Secure:
No direct access to memory (unlike C/C++ pointers).
Provides a security manager and runtime checks.

Portable:
Java bytecode can be carried and run on any platform.

Robust (Strong & Reliable):


Strong memory management (Garbage Collection).
Exception handling (try-catch).
No memory leaks through pointers.

Multithreaded:
Supports multithreading (multiple tasks run in parallel).
Useful in animations, gaming, real-time apps.

Distributed:
Java provides libraries like RMI (Remote Method Invocation) and JDBC to build distributed
applications.
Makes it easier to share data and programs across networks.
Dynamic:
Java programs can load classes at runtime (Dynamic class loading).
Supports reflection and runtime polymorphism.

High Performance:
Although slower than C/C++, Java is fast because of JIT (Just-In-Time) Compiler.
Converts bytecode into native machine code during execution.

Interpreted:
Java bytecode is interpreted by the JVM line by line.
This allows immediate execution on any machine with JVM.

3) Explain Java Assignment and Relational Operators with examples


Assignment Operators: This operator can be used for assigning a value to a variable. The
assignment operator is =
The assignment operator will copy the value from right side to left side. On the right side we
can specify either a variable or a value or an expression but on the left side we must specify
only a variable.
Example: x = 5, y = x, z = x+y
If the assignment operator is combined with other operators then it is called as compound
assignment operator(+= -= *= /= %=).
Example:
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
[Link]("Initial value of a: " + a);

a += 5; // a = a + 5
[Link]("After a += 5: " + a);

a -= 3; // a = a - 3
[Link]("After a -= 3: " + a);

a *= 2; // a = a * 2
[Link]("After a *= 2: " + a);

a /= 4; // a = a / 4
[Link]("After a /= 4: " + a);

a %= 3; // a = a % 3
[Link]("After a %= 3: " + a);
}
}
Relational Operators: These operators can be used for comparing the values. These
operators are also called as comparison operators. The various relational operators are <, <=,
>, >=, ==, !=
The relational operators can be used for creating conditions.
Example: x<y x>y x>=y x==y
Example:
public class RelationalExample {
public static void main(String[] args) {
int x = 10, y = 20;

[Link]("x == y: " + (x == y));


[Link]("x != y: " + (x != y));
[Link]("x > y : " + (x > y));
[Link]("x < y : " + (x < y));
[Link]("x >= y: " + (x >= y));
[Link]("x <= y: " + (x <= y));
}
}

4) Discuss command line arguments in Java with a suitable example


What are Command Line Arguments?

In Java, command line arguments are values passed to the main() method when a program is
executed.
The main() method has a parameter:
public static void main(String[] args)
Here, args is an array of Strings (String[] args).
Each argument from the command line is stored as a string inside this array.

Rules:
Arguments are always received as Strings.
You may need to convert them to int, double, etc., using wrapper classes like
[Link]().
If no arguments are passed, [Link] = 0.

Example:
public class SumCommandLine {
public static void main(String[] args) {
// Check if two arguments are provided
if ([Link] >= 2) {
// Convert string arguments to integers
int num1 = [Link](args[0]);
int num2 = [Link](args[1]);

// Calculate sum
int sum = num1 + num2;
// Print result
[Link]("First Number: " + num1);
[Link]("Second Number: " + num2);
[Link]("Sum = " + sum);
} else {
[Link]("Please provide two numbers as command line arguments.");
}
}
}
5) Explain the following Java control statements with examples
i)if else ii) while

The if-else statement is a decision-making control statement.


It checks a condition:
If true, executes the if block.
If false, executes the else block.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int number = 7;

if (number % 2 == 0) {
[Link](number + " is Even");
} else {
[Link](number + " is Odd");
}
}
}
The while loop is an iteration control statement.
It repeatedly executes a block of code as long as the condition is true.
Syntax:
while (condition) {
// code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link]("Number: " + i);
i++; // increment
}
}
}

6) Explain Ternary operators with examples


Java has only one ternary operator (?:).
But we can use it in different ways:
Simple conditional assignment
Nested ternary (like multiple if-else)
With different data types
As a method return
The ternary operator is a shorthand form of the if-else statement.
It is called ternary because it takes three operands.
Syntax:
variable = (condition) ? expression1 : expression2;
If the condition is true, expression1 is executed.
If the condition is false, expression2 is executed.
Example:
public class TernaryExample1 {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b; [Link]("Maximum is: " + max);
}
}
7) Explain the following Java control statements with examples
i)switch ii) for each
The switch statement is a multi-way branch control statement.
It is used when we want to compare a variable against multiple values.
It works with:
byte, short, char, int
String (from Java 7 onwards)
enum types
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// code block
}
break is used to exit the switch after a match.
default executes if no case matches.
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day");
}
}
}
for-each Loop (Enhanced for loop):
Introduced in Java 5.
Simplifies iterating over arrays and collections (like ArrayList).
Eliminates the use of counters (i, j).
Syntax:
for (dataType variable : arrayOrCollection) {
// code block
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int numbers[] = {10, 20, 30, 40, 50};
[Link]("Array elements:");
for (int num : numbers) ;
[Link](num);
}
}
}

8) List and explain Java primitive data types and, also write a program to display
default values of all primitive data types.
Primitive data types: The primitive data types are designed to store a single value and they
are used to store the basic inputs required for a program. The primitive data types are also
called as fundamental data types.
The java language provides 8 primitive data types classified into 4 categories:
1. Integer Category
2. Floating-Point Category
3. Character Category
4. Boolean Category
Integer Category: This category can be used for storing numbers, either positive or negative
without a decimal point. Under the integer category we have 4 primitive data types and they
are:
1. byte – 8 bits(-128 to 127)
2. short – 16 bits(-32,768 to 32,767)
3. int – 32 bits(-2,147,483,648 to 2,147,483,687)
4. long – 64 bits(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
Floating-Point Category: This category used for storing numbers either positive or negative
with decimal point. Under the floating point category we have two primitive data types and
they are:
1. float – 32 bits(
2. double – 64 bits
Character Category: This category can be used for storing a single character. A character can
be represented by either one alphabet or one digit or one special symbol. Under the
character category there is only on primitive data type and it is char.(16 bits)
Boolean Category: This category is used for storing only 2 values and they are either true or
false. Under the boolean category we have only one primitive type i.e. Boolean(1 bit is
enough)
Example:
public class PrimitiveDefaults {
// Declare primitive data types as instance variables (default values)
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bool;
public static void main(String[] args) {
PrimitiveDefaults obj = new PrimitiveDefaults();
[Link]("Default values of Java primitive data types:");
[Link]("byte : " + obj.b);
[Link]("short : " + obj.s);
[Link]("int : " + obj.i);
[Link]("long : " + obj.l);
[Link]("float : " + obj.f);
[Link]("double : " + obj.d);
[Link]("char : '" + obj.c + "'"); // shows empty char
[Link]("boolean : " + [Link]);
}
}
9) With suitable examples explain Java break and continue statements.
BREAK:
The break statement is used to terminate the loop immediately.
Control comes out of the loop, and execution continues with the next statement after the
loop.
It is commonly used when you have found what you are looking for and don’t want to
continue further.
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Breaking the loop at i = " + i);
break; // loop stops here
}
[Link]("i = " + i);
}
[Link]("Loop ended.");
}
}
CONTINUE:
The continue statement skips the current iteration of the loop and moves to the next
iteration.
Unlike break, it does not terminate the loop, it just jumps to the next cycle.
Example:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Skipping i = " + i);
continue; // skip this iteration
} [Link]("i = " + i);
} [Link]("Loop completed.");
}
}
10) Write a Java program to swap two numbers using bitwise XOR.
We can swap two numbers without using a temporary variable by using the bitwise XOR (^)
operator.
Example:
public class SwapUsingXOR {
public static void main(String[] args) {
int a = 10;
int b = 20;
[Link]("Before swapping:");
[Link]("a = " + a + ", b = " + b);
// Swapping using XOR
a = a ^ b; // Step 1
b = a ^ b; // Step 2
a = a ^ b; // Step 3
[Link]("After swapping:");
[Link]("a = " + a + ", b = " + b);
}
}
11)Explain type casting and type conversion with an exam
Type Conversion (Widening / Implicit Casting):
Also called widening conversion.
Happens automatically when a smaller data type is converted into a larger data type.
No data loss, safe conversion.
Example:
public class TypeConversionExample {
public static void main(String[] args) {
int num = 100; // int (32-bit)
double d = num; // int → double (64-bit)
[Link]("Integer value: " + num);
[Link]("Converted double value: " + d);
}
}
Type Casting (Narrowing / Explicit Casting):
Also called narrowing conversion.
Done manually by the programmer using (type).
Might cause data loss if the target type is smaller.
Example:
public class TypeCastingExample {
public static void main(String[] args) {
double d = 99.99; // double (64-bit)
int num = (int) d; // Explicit cast double int
[Link]("Double value: " + d);
[Link]("Casted int value: " + num);
}
}

You might also like