Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

UNIT-II Overview of Java Language

Unit-II provides an overview of the Java programming language, covering essential topics such as comments, Java tokens, reserved keywords, identifiers, literals, operators, variables, data types, and arrays. It explains the structure of a Java program, the types of comments, and the classification of data types into primitive and non-primitive. Additionally, it discusses how to declare variables, use operators, and work with arrays in Java.

Uploaded by

mrmayurffyt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

UNIT-II Overview of Java Language

Unit-II provides an overview of the Java programming language, covering essential topics such as comments, Java tokens, reserved keywords, identifiers, literals, operators, variables, data types, and arrays. It explains the structure of a Java program, the types of comments, and the classification of data types into primitive and non-primitive. Additionally, it discusses how to declare variables, use operators, and work with arrays in Java.

Uploaded by

mrmayurffyt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

2025 Unit-II Overview of JAVA BSc CS Sy

UNIT-II
Overview of Java Language
1. Introduction,
2. Types of Comment ,
3. Java Tokens
4. Reserve Keywords
5. Identifiers
6. Literals
7. Operators,
8. Variables,
9. final variable,
10. Data Types,
11. Array ,
12. Type Casting ,
13. Control Statement - Branching statement - Looping statement

1. Introduction
 A Java program is basically a collection of classes.
 A class is defined by a set of declaration statements and methods
containing executable statements. Most statements contain expressions, which
describe the actions carried out on data.
2. Types of Comment

There are three types of comments defined in java.


1. Single Line
- The Single line comment begins with a //. It is used in application program.
2. Multiline
- The Multiline comment begins with a /* and end with a */. It is used in application
program.
3. Documentation comment
- A documentation comment starts with /** and ends with */. It is used to create an
HTML file that documents your program. The javadoc tool extracts this information
and generates documentation in HTML format.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 1


2025 Unit-II Overview of JAVA BSc CS Sy

For example:
If you have three @see tags, put them one after the other.
/**
* This class draws a bar chart.
*@author Herbert Schildt
* @version 3.2
*/
3. Java Tokens
- Smallest individual units in a program are known as tokens.
- The compiler recognizes them for building up expressions and statements.
- A Java program is a collection of tokens, comments and white spaces.
Java language includes following types of tokens.
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Variable
7. Datatypes
4. Reserve Keywords
- Java has reserved words called keywords, which follow specific syntax rules.
- There are 50 keywords in Java.
- Keywords have fixed meanings and cannot be used as variable, class, or
method names.
- All keywords must be written in lowercase.
abstract continue for new switch
assert *** default goto * package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp ** volatile
const * float native super while

Note: we should also not attempt to use the Boolean values true and false or null as names
in our program.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 2


2025 Unit-II Overview of JAVA BSc CS Sy

5. Identifiers
- Identifiers are programmer-designed tokens.
- They are used for naming classes, methods, variables, objects, labels, packages and
interfaces in a program.
Example: average, sum, length etc.
Java identifiers follow these rules:
1. Can include letters, digits, _ (underscore), and $ (dollar sign).
2. Cannot start with a digit.
3. Case-sensitive (uppercase and lowercase are different).
4. Cannot use keywords as identifiers.
5. No spaces allowed in identifiers.
6. Can be of any length.
6. Literals
- Literals in Java are fixed values (digits, letters, or symbols) assigned to
variables.
- They represent boolean, character, numeric, or string data.
Java has five main types of literals:

 Integer literals:
- By default, all integer literals are of int type.
- Integer literals can be written in different number systems:
1. Decimal (Base 10): Uses digits 0-9 (e.g., int x = 101;).
2. Octal (Base 8): Uses digits 0-7, prefixed with 0 (e.g., int x = 0146;).
3. Hexadecimal (Base 16): Uses digits 0-9 and letters a-f, prefixed with 0x or 0X
(e.g., int x = 0X123Face;).
4. Binary (Base 2): Uses digits 0 and 1, prefixed with 0b or 0B (e.g., int x =
0b1111;).
 Floating point literals:
- By default, floating-point literals are of double type.
- Floating-point literals can only be written in decimal form (not in octal or
hexadecimal).
 Character literals:
- A character literal is a single character or escape sequence enclosed in single
quotes (' '). It is always of char type. For Example: 'a', '%', '\u000d'

Mr Sambhaji V Deshmukh COCSIT, Latur Page 3


2025 Unit-II Overview of JAVA BSc CS Sy

 String literals:
- A string literal is a sequence of characters enclosed in double quotes (" ").
- It can include letters, numbers, special characters, spaces, etc.
- Example: "Jack", "12345", "\n"..
 Boolean literals:
- Boolean literals represent values that are either true or false,
Example: true, false

7. Operators,
- Operators constitute the basic building block of any programming language.
- An operator is a symbol that tells the computer to perform certain mathematical
and logical manipulation.
- An operator is a symbol that takes one or more arguments are operates on them to
produce a result.
- Operators are used in program to manipulate data and variables.
Java operators can be classified into a number of related categories as below:.
Arithmetic operators
- Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
The following table lists the arithmetic operators:

Increment and decrement operator:


 These Operators are used to increase or decrease a variable's value by 1.
 Increment Operators:
o Prefix: ++x (increases before using the value).

Mr Sambhaji V Deshmukh COCSIT, Latur Page 4


2025 Unit-II Overview of JAVA BSc CS Sy

o Postfix: x++ (increases after using the value).


 Decrement Operators:
o Prefix: --x (decreases before using the value).
o Postfix: x-- (decreases after using the value).

The Bitwise Operators


- Java defines several bitwise operators which can be applied to the integer
types, long, int, short, char, and byte.

- These operators act upon the individual bits of their operands. They are
listed in the following table:

Relational Operators
- Relational operators compare two operands to determine their relationship, such
as equality or order.
- The result is always a boolean value (true or false).
- These operators are commonly used in if statements and loops.
- The relational operators are:

Mr Sambhaji V Deshmukh COCSIT, Latur Page 5


2025 Unit-II Overview of JAVA BSc CS Sy

Operators Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Boolean Logical Operators


The boolean logical operators operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.
Operator Result
&& Logical AND
|| Logical OR
! Logical NOT

A logical expression yields a value of true or false, according to the truth table show
below:
A B A || B A && B

False False False False


True False True False
False True True False
True True True True

Assignment Operator
- The assignment operator is the single equal sign, =.
- The assignment operator works in Java much as it does in any other
computer language. It has this general form:
var = expression;

Mr Sambhaji V Deshmukh COCSIT, Latur Page 6


2025 Unit-II Overview of JAVA BSc CS Sy

Here, the type of var must be compatible with the type of expression. For example,
the statement,
x=y=z=100;
sets the variables x, y, and z to 100 using a single statement.

The ? Operator (Condition operator)


Java has a ternary operator (? :) that replaces some if-else statements.
 Its format is: expression1 ? expression2 : expression3.
 If expression1 is true, expression2 is evaluated; otherwise, expression3 is
evaluated.
 The result is the value of the evaluated expression.
 expression2 and expression3 must return the same type, and it cannot be void.
For example,
int
b=10,c=20;
a = b > c ?
b : c;
The value of a will be the value of c.

8. Variables,

A variable is a name that represents a storage location for data.


 In Java, variables must be declared before use.
 The basic syntax for declaring a variable is:
type identifier [= value] [, identifier [= value] …];
 The type is a Java data type or a class/interface name.
 The identifier is the variable's name, and you can initialize it with a value using =.
 You can declare multiple variables of the same type, separated by commas.
Example:
int a, b, c; // declare three integers a, b, and c.
int d = 4, e, f = 8; // declare three int and initialize
d and e.
byte z = 22; // initialize z
char ch = „X‟;

Mr Sambhaji V Deshmukh COCSIT, Latur Page 7


2025 Unit-II Overview of JAVA BSc CS Sy

9. final variable:
- When a variable is declared as final, its value cannot be changed after initialization.
- This is useful for creating constants or values that should remain unchanged.
public class ConstantExample {
public static void main(String[] args) {
final double PI = 3.14159;
System.out.println("Value of PI: " + PI); }
}
Output:
Value of PI: 3.14159

10. Data Types:

1. Primitive Data Types (8 Types)

• A primitive data type in Java is a basic data type that directly holds values, not
references to objects.

• These types are predefined by Java and stored in memory for fast access.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 8


2025 Unit-II Overview of JAVA BSc CS Sy

Numbers
Primitive number types are divided into two groups:
1. Integer
2. Floating point
Integer Types
- Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
1. Byte
- The byte data type can store whole numbers from -128 to 127.
- This can be used instead of int or other integer types to save memory.
- It occupied 1 byte, means 8 bits.
2. Short
- The short data type can store whole numbers from -32768 to 32767.
- It occupied 2 bytes, means 16 bits.
3. Int
- The int data type can store whole numbers from -2147483648 to 2147483647.
- It required 4 bytes means 32 bits.
4. Long
- The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807.
- Note that you should end the value with an "L":
- Occupied 8 bytes means 64 bits.
Floating Point Types
- There two types of floating point: 1. Float 2. Double
- Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double
- The float and double data types can store fractional numbers.
- Note that you should end the value with an "f" for floats and "d" for doubles.
- Float occupied 4 bytes and double occupied 8 bytes.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 9


2025 Unit-II Overview of JAVA BSc CS Sy

2. Non-Primitive (Reference) Data Types

• A non-primitive data type in Java is a data type that stores references to objects
instead of actual values.

• These types are more complex than primitive data types and can hold multiple
values or behaviors.

Characteristics of Non-Primitive Data Types:

1. Created by the programmer (not predefined like primitives)

2. Stores references to objects in memory, not the actual value

3. Can have methods for operations

4. Can be null (unlike primitive types)

5. Can grow dynamically in memory

Data Type Description


String Stores a sequence of characters.
i.e. String name=”Java”
Arrays Collection of elements of the same type
i.e. int[]arr={1,2,3};
Class A blueprint for objects
i.e. class car{ }
interface Defines a contract for implementing classes
i.e interface Vehicle{ }

11. Array :
- An array in Java is a collection of elements of the same data type
stored in contiguous memory locations.
- Arrays allow storing multiple values under a single variable name.
- Once created, its size cannot change.
- Elements are accessed using an index (start from 0).
- Arrays can store int, float, char, String, or user-defined objects.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 10


2025 Unit-II Overview of JAVA BSc CS Sy

Types of Arrays in Java


1. Single-Dimensional Array (1D Array)
- A one-dimensional array is a data structure that stores elements of the same type in a
continuous block of memory.
- Each element is accessed using a single index.
- Once created, the size of the array cannot be changed.
- It allows fast data access using indexes and is memory efficient.
-  One-dimensional arrays are useful for storing and working with large
datasets.Syntax:
arrayName = new dataType[size];
Example:
numbers = new int[5]; // Allocates memory for 5 integer elements

Declaration & Initialization in One Step:


int[] numbers = new int[5]; // Combines declaration and memory allocation

Initializing a One-Dimensional Array(Using Index-Based Assignment)


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Using Inline Initialization:

int[] numbers = {10, 20, 30, 40, 50}; // Declares, allocates, and initializes

This method automatically determines the size based on the provided elements.

Accessing Elements of an Array:

System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[4]); // Output: 50

Mr Sambhaji V Deshmukh COCSIT, Latur Page 11


2025 Unit-II Overview of JAVA BSc CS Sy

Example:
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (i + 1) * 10;
}
System.out.println("Array elements: ");
for (int num : numbers) {
System.out.print(num+” “);
}
}
}
Output:
Array elements: 10 20 30 40 50

2. Multi-Dimensional Array (2D, 3D, etc.)


- A multidimensional array is an array of arrays.
- Multidimensional arrays are useful when you want to store data as a tabular form,
like a table with rows and columns.
- To create a two-dimensional array, add each array within its own set of curly
braces:
Example:
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
Access Elements
To access the elements of the myNumbers array, specify two indexes:
Example:
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7

Example

Class MDemo{
Static public void main(String args[]){
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for (int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
} } } }

Mr Sambhaji V Deshmukh COCSIT, Latur Page 12


2025 Unit-II Overview of JAVA BSc CS Sy

12. Type Casting ,


Type casting in Java converts one data type to another.
Types of Type Casting:
1. Implicit Type Casting (Widening)
o Smaller data type → Larger data type (automatic, no data loss).
o Example: byte → short → int → long → float → double
2. Explicit Type Casting (Narrowing)
o Larger data type → Smaller data type (manual, possible data loss).
o Syntax: dataType variable = (dataType) value
Type Casting Between Primitive and Object Types:
 Boxing & Autoboxing: Converts primitive to wrapper class automatically
int num = 50;
Integer obj = num; // Autoboxing
 Unboxing: Converts wrapper class back to primitive
Integer obj = 100;
int num = obj; // Unboxing

Type Casting Between Objects (Upcasting & Downcasting):


Upcasting (Automatic): Converting a subclass object to a superclass type.

class Animal { }
class Dog extends Animal { }
public class UpcastingExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting (Dog → Animal)
} }
Downcasting (Explicit): Converting a superclass object back to a subclass type.

class Animal { }
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
public class DowncastingExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
d.bark(); // Output: Barking...
}
}
13. Control Statement - Branching statement - Looping statement

Mr Sambhaji V Deshmukh COCSIT, Latur Page 13


2025 Unit-II Overview of JAVA BSc CS Sy

Java’s Selection Statement


Branching in Java occurs when a program jumps to another part of the code.
 Conditional Branching: Happens based on a condition.
 Unconditional Branching: Occurs without any condition.
Java supports decision-making through control statements.
1. if statements
2. switch statement
3. Conditional operator statement ( ? : Operator as discuss above )
if statements
The if statement is a decision-making statement that controls program flow.
 It evaluates a condition and executes a statement if the condition is true.
 General form
if (test-expression) statement1;
 It allows conditional execution and can be used in different forms based on
complexity.
a) Simple if statement
b) If….else statement
c) Nested if…else statement
d) else if ladder
i) Simple if statement
The general form of simple if statement is
if (test-expression){
statement-block;
}
statement-X;
A statement block can be a single or multiple statements.
 If the condition is true, the block executes.
 If false, it is skipped, and execution moves to the next statement.
if ( perc >= 35 )
result=”Pass”;

Mr Sambhaji V Deshmukh COCSIT, Latur Page 14


2025 Unit-II Overview of JAVA BSc CS Sy

ii) The if..else statement


The general form of simple if statement is
if (test-expression) {
True-block statement(s);
}else {
False-block statement(s);
}
statement-X;

The if-else statement executes one of two blocks based on a condition.


 If the condition is true, the true block runs.
 If false, the false block runs.
 Only one block executes.
 Curly braces {} are needed for multiple statements but optional for a single
statement.
if ( a< b)
a = 0;
else
b = 0;

iii) The nested if..else statement


When a series of decisions are involved, we may have to use more that one if…else
statement in nested form as follows.
if (test-condition1) {
if (test-condition1) {
statement1;
}else {
statement2;
}}else {
statement-3;
}
statement-X;

If condition-1 is false, statement-3 executes.

 If condition-1 is true, it checks condition-2.


 If condition-2 is true, statement-1 runs.
 Otherwise, statement-2 runs.
After execution, control moves to statement-X.

Mr Sambhaji V Deshmukh COCSIT, Latur Page 15


2025 Unit-II Overview of JAVA BSc CS Sy

class ElseDemo {
public static void main(String args[]) {
int a = 10, b = 30, c = 20;
System.out.println(“Largest Value is : “);
if ( a > b) {
if (a > c)
System.out.println(a);
else
System.out.println(c);
}else {
if (c > b)
System.out.println(c);
else
System.out.println(b);
}}}

iii) The else if ladder


For multipath decisions, a chain of if-else statements is used.
if (condition1)
statement1;
else if (condition2)
statement2;
else
statement3;
}
statement-X;
The else-if ladder checks conditions from top to bottom.
 Once a true condition is found, its statement runs, and the rest are skipped.
 If all conditions are false, the else block (default statement) executes.
For example :
if ( mark > 79)
grade = “Honors”;
else if (marks > 59)
grade = “First Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 49)
grade = “Third Division”;
else
grade = “Fail”;
System.out.println(“Grade : ” + grade);

Switch statements

Mr Sambhaji V Deshmukh COCSIT, Latur Page 16


2025 Unit-II Overview of JAVA BSc CS Sy

 For selecting one of many alternatives, if statements can be used, but they can make
the code complex.
Java provides the switch statement for multiway decisions.
 It tests a variable/expression against multiple case values.
 When a match is found, the corresponding block executes.
switch (expression){
case value-1:
block-1;
break;
case value-2:
block-2;
break;
<<<<<<..
<<<<<<..
default:
default-block;
break;
}
statement-X;

In a switch statement:
 The expression is an integer or character.
 value-1, value-2, etc., are unique constants known as case labels.
 Each block contains statements to execute if the case matches.
 The break statement ends a case and exits the switch, transferring control to the
next statement.
 The default case is optional. It runs if no case matches.
 Omitting break causes the execution to continue to the next case (fall-through
behavior).

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

Iteration Statements (Looping)

Mr Sambhaji V Deshmukh COCSIT, Latur Page 17


2025 Unit-II Overview of JAVA BSc CS Sy

The process of repeatedly executing a block of statements is known as looping. The


statements in the block may be executed any number of times. The Java language provides
for three constructs for performing loop operations. They are:
1. The while statement
2. The do statement
3. The for statement
while
The general form of while statement is
Initialization
while (test-condition){
Body of the loop;
}
The while statement is an entry-controlled loop.
 The loop checks the condition before each iteration.
 If the condition is true, the body of the loop runs.
 After each iteration, the condition is checked again.
 The loop continues until the condition becomes false, then control moves to the next
statement after the loop.
 If the body contains one statement, no braces are needed.
 For multiple statements, braces {} are required.
Consider the following program:
class CalcTotal {
public static void main(String args[ ] ) {
int i=1, sum=0;
while(i <= 10) {
sum = sum + i;
i++;
}
System.out.println(" Addition of numbers through
1...10 is : " + sum);
}}
The output of the program would be…..
Addition of numbers through 1...10 is : 55

Mr Sambhaji V Deshmukh COCSIT, Latur Page 18


2025 Unit-II Overview of JAVA BSc CS Sy

do
 In a while loop, the condition is tested before the loop runs.
 If you need to execute the loop body before the condition is tested, use the do
statement.
Initialization
do{
Body of the loop;
}while (test-condition);

In a do-while loop:
 The loop body is executed first, then the condition is checked.
 If the condition is true, the body runs again.
 This repeats as long as the condition remains true.
 When the condition is false, the loop ends and control moves to the next statement.
Since the condition is checked after the loop, the body is always executed at least once.
For example, in the following program test condition is false in the first attempt, still loop is
executed only once.

class CalcTotal {
public static void main(String args[ ] ) {
int i=100, sum=0;
do {
sum = sum + i;
i++;
} while(i <= 10);
System.out.println("Addition of numbers 1..10 is : " + sum);
}}
The output of the program would be…..
Addition of numbers through 1...10 is : 100

Mr Sambhaji V Deshmukh COCSIT, Latur Page 19


2025 Unit-II Overview of JAVA BSc CS Sy

for
The for loop is another entry controlled loop that provides a simple loop structure. The
general form of the for loop is:
for (initialization; test-condition; increment){
Body of the loop;
}

The for loop works as follows:


1. Initialization: The loop-control variable is set (e.g., i = 0).
2. Test Condition: The condition (e.g., i < 10) is checked. If true, the loop runs; if false,
the loop ends.
3. Execution: The loop body runs, then the control variable (e.g., i++) is updated. The
condition is checked again, and the process repeats until the condition is false.

Example:
class CalcTotal {
public static void main(String args[ ] ) {
int i, sum=0;
sum = 0;
for(i = 1; i <= 10; i++)
sum = sum + i;
System.out.println(" Addition of no: 1 to 10 is : " + sum);
}
}
The output of the program would be…
Addition of no: 1to 10 is : 55

Mr Sambhaji V Deshmukh COCSIT, Latur Page 20

You might also like