[go: up one dir, main page]

0% found this document useful (0 votes)
5 views21 pages

Unit 1 Notes

Introduction to java programming and object oriented programming through java.

Uploaded by

sunhithsirigudi
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)
5 views21 pages

Unit 1 Notes

Introduction to java programming and object oriented programming through java.

Uploaded by

sunhithsirigudi
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
You are on page 1/ 21

UNIT 1 NOTES

I - DATA TYPES IN JAVA


In Java, data types specify the size and type of values that can be stored in variables. Java
is a statically-typed language, meaning each variable must be declared with a data type.
Java data types are broadly classified into two main categories: Primitive Data Types and
Non-Primitive (Reference) Data Types.

1. Primitive Data Types


Java has eight built-in primitive data types, which are the most basic types and directly store
values.

Data Size Default Description


Type (bits) Value
byte 8 0 Stores whole numbers from -128 to 127. Useful for
saving memory in large arrays where memory
savings are essential.
short 16 0 Stores whole numbers from -32,768 to 32,767. Used
for saving memory in large arrays.
int 32 0 Stores whole numbers from -2^31 to 2^31 - 1. Most
commonly used integer data type.
long 64 0L Stores whole numbers from -2^63 to 2^63 - 1. Use
for values larger than int . Needs an "L" suffix (e.g.,
1234L ).
float 32 0.0f Stores fractional numbers with up to 6-7 decimal
digits of precision. Use an "f" suffix (e.g., 12.34f ).
double 64 0.0d Stores fractional numbers with up to 15 decimal
digits of precision. Default for decimal values. Use
"d" suffix (optional).
char 16 \u0000 Stores a single 16-bit Unicode character (e.g., 'A', 'b',
'1', '$').
boolean 1 false Represents one of two values: true or false .
(logical) Typically used for flags or conditional logic.

Example of Primitive Data Types in Java:


public class PrimitiveTypesExample {
public static void main(String[] args) {
byte byteVar = 100;
short shortVar = 1000;
int intVar = 100000;
long longVar = 100000L;
float floatVar = 10.5f;
double doubleVar = 20.99;
char charVar = 'A';
boolean boolVar = true;

System.out.println("Byte value: " + byteVar);


System.out.println("Short value: " + shortVar);
System.out.println("Int value: " + intVar);
System.out.println("Long value: " + longVar);
System.out.println("Float value: " + floatVar);
System.out.println("Double value: " + doubleVar);
System.out.println("Char value: " + charVar);
System.out.println("Boolean value: " + boolVar);
}
}

2. Non-Primitive (Reference) Data Types


Non-primitive data types are created by the progr
ammer and are not predefined by Java. They are also known as reference types because
they refer to objects rather than directly holding a value. These include arrays , strings ,
classes, interfaces .

String: Used to represent a sequence of characters. In Java, strings are objects and
belong to the String class.
Arrays: Collections of elements of a single type. For example, int[] numbers = {1,
2, 3, 4}; represents an array of integers.

Example of Non-Primitive Data Types in Java:

public class ReferenceTypesExample {


public static void main(String[] args) {
// String example
String greeting = "Hello, Java!";

// Array example
int[] numbers = {1, 2, 3, 4, 5};

System.out.println("String value: " + greeting);


System.out.print("Array values: ");
for (int number : numbers) {
System.out.print(number + " ");
}

}
}

II - Java Operators
Operators in Java allow you to perform various computations and control the flow of your
program.

1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.

Operator Description Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b

Example:

int a = 10, b = 5;
System.out.println("Addition: " + (a + b)); // 15
System.out.println("Subtraction: " + (a - b)); // 5
System.out.println("Multiplication: " + (a * b)); // 50
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 0

2. Relational Operators
Relational operators compare two values and return a boolean result ( true or false ).

Operator Description Example


== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or equal a >= b
<= Less or equal a <= b

Example:

int a = 10, b = 5;
System.out.println("Equal to: " + (a == b)); // false
System.out.println("Not equal to: " + (a != b)); // true
System.out.println("Greater than: " + (a > b)); // true
System.out.println("Less than: " + (a < b)); // false
System.out.println("Greater or equal: " + (a >= b)); // true
System.out.println("Less or equal: " + (a <= b)); // false

3. Logical Operators
Logical operators are used to perform logical AND , OR , and NOT operations on boolean
expressions.

Operator Description Example


&& Logical AND (a > b) && (a > c)
|| Logical OR (a > b) || (a > c)
! Logical NOT !(a > b)

Example:

boolean x = true, y = false;


System.out.println("Logical AND: " + (x && y)); // false
System.out.println("Logical OR: " + (x || y)); // true
System.out.println("Logical NOT: " + (!x)); // false
4. Assignment Operators
Assignment operators assign values to variables. The basic assignment operator is = , but
there are also compound assignment operators.

Operator Description Example


= Assign a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b

Example:

int a = 10;
a += 5; // Equivalent to a = a + 5
System.out.println("a after += 5: " + a); // 15
a *= 2; // Equivalent to a = a * 2
System.out.println("a after *= 2: " + a); // 30

5. Bitwise Operators
Bitwise operators perform operations on binary representations of integers.

Operator Description Example


& Bitwise AND a & b
| Bitwise OR a|b
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
<< Left shift a << 1
>> Right shift a >> 1
>>> Unsigned right shift a >>> 1

Example:
int a = 5, b = 3; // a = 0101, b = 0011 in binary
System.out.println("Bitwise AND: " + (a & b)); // 1 (0001)
System.out.println("Bitwise OR: " + (a | b)); // 7 (0111)
System.out.println("Bitwise XOR: " + (a ^ b)); // 6 (0110)
System.out.println("Bitwise NOT of a: " + (~a)); // -6
System.out.println("Left shift a by 1: " + (a << 1)); // 10 (1010)
System.out.println("Right shift a by 1: " + (a >> 1)); // 2 (0010)

6. Unary Operators (Increment & Decrement)


Unary operators operate on a single operand. They include increment ( ++ ) and decrement
( -- ) operators.

Operator Description Example


++ Increment ++a or a++
-- Decrement --a or a--

Pre-Increment ( ++a ): Increments a before using it.


Post-Increment ( a++ ): Uses a and then increments it.
Pre-Decrement ( --a ): Decrements a before using it.
Post-Decrement ( a-- ): Uses a and then decrements it.

Example:

int a = 5;
System.out.println("Pre-Increment: " + (++a)); // 6
System.out.println("Post-Increment: " + (a++)); // 6, then a becomes 7
System.out.println("a after Post-Increment: " + a); // 7
System.out.println("Pre-Decrement: " + (--a)); // 6
System.out.println("Post-Decrement: " + (a--)); // 6, then a becomes 5

7. Ternary Operator
The ternary operator ( ? : ) is a shorthand for if-else conditions. It evaluates a boolean
expression and returns one of two values based on the result.

Syntax:
result = (condition) ? valueIfTrue : valueIfFalse;

Example:

int a = 5, b = 10;
int max = (a > b) ? a : b;
System.out.println("Max value is: " + max); // 10

This code evaluates a > b . If true, it assigns a to max ; otherwise, it assigns b .

III - Java Conditional Statements


Conditional statements in Java are used to perform different actions based on specific
conditions. These statements enable branching and control the flow of the program.

1. Simple if Statement
The if statement evaluates a condition inside its parentheses. If the condition is true, the
code block within the if statement is executed.

Syntax:

if (condition) {
// code to execute if condition is true
}

Example:

int age = 18;


if (age >= 18) {
System.out.println("You are eligible to vote.");
}

In this example, the program checks if age is greater than or equal to 18. If true, it prints the
eligibility message.

2. if-else Statement
The if-else statement provides an alternative action if the condition is false. The if block
executes if the condition is true, and the else block executes if it’s false.

Syntax:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

Example:

int age = 16;


if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}

In this example, if age is less than 18, it displays a message indicating ineligibility.

3. else if Ladder
The else if ladder is used to test multiple conditions sequentially. Once a condition is true,
its corresponding block is executed, and the ladder stops.

Syntax:

if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if none of the conditions are true
}

Example:

int marks = 85;


if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
} else if (marks >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}

Here, marks is checked against multiple conditions, and only the first true condition’s block
executes.

4. Nested if Statement
A nested if is an if statement within another if or else block, allowing multiple levels
of conditions.

Syntax:

if (condition1) {
if (condition2) {
// code if both condition1 and condition2 are true
}
}

Example:

int age = 25;


int weight = 70;
if (age >= 18) {
if (weight >= 50) {
System.out.println("You are eligible for the competition.");
} else {
System.out.println("You are not eligible due to weight.");
}
} else {
System.out.println("You are not eligible due to age.");
}

In this example, eligibility is checked based on both age and weight . Only if both are true
does the program print that the person is eligible.

5. switch Statement
The switch statement is used when multiple conditions are based on a single variable or
expression, usually an integer, string, or enum. It allows checking several values in a clear,
concise manner.

Syntax:

switch (variable) {
case value1:
// code if variable == value1
break;
case value2:
// code if variable == value2
break;
// other cases
default:
// code if none of the cases are matched
}

Example:

int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}

Here, day is checked against the case values. Since it matches 3 , it prints "Wednesday".

IV - Java Iteration (Looping) Statements


Iteration statements, or loops, allow executing a block of code multiple times. Java supports
several types of loops that fit different needs.
1. while Loop
The while loop continues executing a block of code as long as a specified condition is true.
It’s useful when the number of iterations is unknown beforehand.

Syntax:

while (condition) {
// code to execute while the condition is true
}

Example:

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

In this example, the loop prints numbers 1 to 5. The condition checks if i is less than or
equal to 5, incrementing i each time.

2. do-while Loop
The do-while loop is similar to while , but it guarantees at least one execution of the code
block, as the condition is evaluated at the end of the loop.

Syntax:

do {
// code to execute at least once
} while (condition);

Example:

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

Here, the loop prints numbers 1 to 5, with i incremented after each iteration. Since the
condition is evaluated after the block, the loop executes at least once, even if the condition is
initially false.

3. for Loop
The for loop is typically used when the number of iterations is known beforehand. It
initializes a variable, checks a condition, and updates the variable in one line.

Syntax:

for (initialization; condition; update) {


// code to execute while the condition is true
}

Example:

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


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

This example prints numbers 1 to 5. The for loop initializes i , checks the condition, and
increments i after each iteration.

4. Nested for Loop


A nested for loop is a loop within another loop. It’s often used to work with matrices or to
generate patterns.

Syntax:

for (initialization1; condition1; update1) {


for (initialization2; condition2; update2) {
// code to execute
}
}

Example:

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


for (int j = 1; j <= 3; j++) {
System.out.print("* ");
}
System.out.println();
}

This example prints a 3x3 grid of asterisks. The outer loop manages rows, and the inner
loop manages columns.

5. for-each Loop
The for-each loop (enhanced for loop) is specifically designed to iterate over arrays or
collections. It’s simpler than a for loop, especially when you don’t need to track the index.

Syntax:

for (dataType item : arrayOrCollection) {


// code to execute for each item
}

Example:

int[] numbers = {1, 2, 3, 4, 5};


for (int num : numbers) {
System.out.println("Number: " + num);
}

This loop iterates through each element in the numbers array and prints it.

6. break Statement
The break statement is used to exit a loop immediately, regardless of the loop’s condition.
It’s commonly used in situations where a certain condition requires stopping the loop early.

Example:

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


if (i == 3) {
break; // exits loop when i equals 3
}
System.out.println("Count: " + i);
}

This example stops printing at 2 because the loop exits when i is equal to 3.
7. continue Statement
The continue statement skips the current iteration and moves to the next one. It’s often
used when certain conditions require skipping part of the loop’s code but not ending the loop
itself.

Example:

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


if (i == 3) {
continue; // skips printing 3
}
System.out.println("Count: " + i);
}

Here, the number 3 is skipped, but the loop continues to print 1, 2, 4, and 5.

V - REMAINING CONCEPTS (BASICS & SMALL


TOPICS)
1. Java Elements
Java is built on essential programming constructs. These elements include:

Classes: The blueprint for creating objects, containing attributes (fields) and behaviors
(methods).
Objects: Instances of classes that represent entities with specific properties.
Methods: Blocks of code performing specific tasks. Defined inside classes, they
operate on data and often return results.
Variables: Containers for storing data values.
Interfaces: Contracts defining a set of methods a class can implement.
Packages: Collections of classes and interfaces that help organize and modularize
code (e.g., java.util , java.io ).

In Java, code is organized into packages, classes, and methods, creating a clear and
structured approach to building applications.

2. Java Tokens
Tokens are the smallest individual elements in Java and include:

Keywords: Reserved words with specific meanings, like class , public , static .
Identifiers: Names given to variables, methods, classes, etc. They must start with a
letter, $ , or _ and cannot be keywords.
Literals: Constants directly assigned to variables, like 42 , 3.14 , 'a' , "Hello" .
Operators: Symbols that perform operations on values (e.g., + , - , * , && ).
Separators: Characters that separate code elements, like parentheses () , braces {} ,
and semicolons ; .

Java uses these tokens to create syntactically correct statements and expressions.

3. Statements
Java statements are individual instructions for the Java Virtual Machine (JVM) to execute.
They include:

Expression Statements: Evaluates an expression and ends in a semicolon (e.g., int


x = 5; ).
Declaration Statements: Used to declare variables and set types.
Control-Flow Statements: Directs the flow of execution with if , for , while , and
switch statements.
Block Statements: Groups of statements wrapped in curly braces {} , often used in
loops, methods, and control-flow constructs.

Example:

int x = 10; // Declaration statement


if (x > 5) { // Control-flow statement
System.out.println("x is greater than 5"); // Expression statement
}

4. Command-Line Arguments
Java allows programs to receive input from the command line, stored in the String[] args
parameter of the main method.

Example:
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (String arg : args) {
System.out.println(arg);
}
}
}
// To run: java CommandLineExample arg1 arg2 arg3

Command-line arguments are useful for running programs with custom inputs without
modifying the code.

5. User Input in Java


Java’s Scanner class enables reading user input from the console. System.in is used as
an input stream.

Example:

import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.println("Hello, " + name + ". You are " + age + " years
old.");

scanner.close();
}
}

6. Escape Sequences
Escape sequences allow us to represent special characters within strings. Some common
sequences:

Escape Sequence Description Example Usage


\n Newline System.out.println("Hello\nWorld");
\t Tab System.out.println("Hello\tWorld");
\" Double quote System.out.println("She said, \"Hello!\"");
\\ Backslash System.out.println("C:\\Program Files");

Escape sequences are essential for formatting output and displaying complex text.

7. Comments in Java
Java supports three types of comments:

Single-line comments ( // ): Used for brief, inline notes.


Multi-line comments ( /* ... */ ): Useful for longer explanations or to comment out
blocks of code.
Documentation comments ( /** ... */ ): Used to generate JavaDocs, providing
structured information about methods, classes, etc.

Example:

// This is a single-line comment

/* This is a
multi-line comment */

/**
* This is a documentation comment
* Used for generating JavaDocs.
*/

8. Variables and Scope


Variables: Named containers storing data.
Scope: The region of code where a variable is accessible.
Local scope: Inside methods or blocks.
Instance scope: Non-static, instance-level, available to the object.
Class scope: Static variables shared across instances.

Example:

public class VariableScopeExample {


static int classVar = 10; // Class scope
int instVar = 20; // Instance scope
public void methodExample() {
int localVar = 5; // Local scope
}
}

9. Type Casting
Java supports both implicit (automatic) and explicit (manual) casting:

Implicit casting (widening): Converts smaller types to larger types.


Explicit casting (narrowing): Requires casting from larger to smaller types.

Example:

int x = (int) 3.14; // Explicit cast from double to int


double y = 5; // Implicit cast from int to double

10. Literal Constants


Literals are fixed values assigned to variables directly. Examples:

Integer literals: 10 , 0xFF


Floating-point literals: 3.14 , 2.71f
Character literals: 'A'
String literals: "Hello"
Boolean literals: true , false

11. Symbolic Constants


Symbolic constants are variables whose values cannot change, declared with final .

Example:
final int MAX_SCORE = 100;

12. Formatted Output with printf()


The printf() method allows formatted output. Common format specifiers include:

%d for integers
%f for floating-point numbers
%s for strings

Example:

System.out.printf("Name: %s, Age: %d, Score: %.2f\n", "Alice", 20, 95.25);

13. Static Variables and Methods


Static variables: Shared among all instances of a class.
Static methods: Belong to the class rather than an instance.

Example:

public class StaticExample {


static int counter = 0;

static void incrementCounter() {


counter++;
}
}

14. Final Attribute


The final keyword in Java can be used with:

Variables: To create constants.


Methods: To prevent method overriding.
Classes: To prevent inheritance.

Example:
final int MAX = 100;

15. Operator Precedence & Associativity


In Java, precedence and associativity of operators determine the order in which
operations are evaluated in an expression. Operator precedence specifies which operator
will be evaluated first when multiple operators are present, while associativity determines the
direction in which an expression with operators of the same precedence level will be
evaluated.

1. Operator Precedence in Java


Operators in Java have different precedence levels, with higher-precedence operators
evaluated before lower-precedence operators. Here’s a list, from highest to lowest
precedence:

Precedence Operators Type


Level
1 () , [] , . Parentheses, Array Access,
Member Access
2 ++ , -- , + (Unary), - (Unary), ~ , Unary
!
3 *, /, % Multiplicative
4 +, - Additive
5 << , >> , >>> Shift
6 < , <= , > , >= , instanceof Relational
7 == , != Equality
8 & Bitwise AND
9 ^ Bitwise XOR
10 | Bitwise OR
11 && Logical AND
12 || Logical OR
13 ?: Ternary
14 = , += , -= , *= , /= , %= , &= , = , Assignment
^= , <<= , >>= , `>>>=
Higher precedence operators are evaluated first. For example, in the expression 3 + 5 *
2 , the multiplication 5 * 2 is evaluated first because * has higher precedence than + .

2. Operator Associativity in Java


Associativity defines the direction (left-to-right or right-to-left) in which an expression is
evaluated when multiple operators of the same precedence are present.

Associativity Operators
Direction
Left-to-Right * , / , % , + , - , << , >> , >>> , < , <= , > , >= , == , != , & , ^ ,
` , && ,
Right-to-Left = , += , -= , *= , /= , %= , &= , = , ^= , <<= , >>= , >>>= , ++ , -- ,
+ (Unary), - (Unary), ~ , ! , ?:

Left-to-Right Associativity: Operators with left-to-right associativity are evaluated


from left to right. For example, in 10 - 5 + 2 , subtraction is performed first ( 10 - 5 ),
then addition ( 5 + 2 ).
Right-to-Left Associativity: Operators with right-to-left associativity are evaluated
from right to left. For example, in a = b = 5 , the assignment happens from right to left,
so b is assigned 5 , and then a is assigned 5 .

You might also like