0% found this document useful (0 votes)
23 views55 pages

WINSEM2024-25 BCSE103E ETH VL2024250506070 2025-01-02 Reference-Material-I

The document provides an overview of Java programming basics, focusing on the Object-Oriented Programming (OOP) paradigm, features of the Java language, and the structure of Java programs. It details the types of literals in Java, including integral, floating-point, char, string, boolean, and null literals, along with variable declaration, initialization, and naming conventions. Additionally, it explains the types of variables (local, instance, and static) and introduces operators in Java.

Uploaded by

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

WINSEM2024-25 BCSE103E ETH VL2024250506070 2025-01-02 Reference-Material-I

The document provides an overview of Java programming basics, focusing on the Object-Oriented Programming (OOP) paradigm, features of the Java language, and the structure of Java programs. It details the types of literals in Java, including integral, floating-point, char, string, boolean, and null literals, along with variable declaration, initialization, and naming conventions. Additionally, it explains the types of variables (local, instance, and static) and introduces operators in Java.

Uploaded by

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

JAVA Basics-3

Dr. Ramesh Babu Vemuluri,


SMEC,
VIT Vellore
Contents
• OOP Paradigm
• Features of Java Language
• JVM, JRE and JDK
• Bytecode
• Java Program Structure
• Basic Programming Constructs
• Data Types
• Keywords
• Variables
• Java naming conventions
• Operators
Literals in Java
• Any constant value which can be assigned to the variable is called
literal/constant.
• Literals are number, text, or anything that represent a value.
• They are represented directly in the code without any computation.
• In lexical analysis, literals of a given type are generally known as tokens.
• Literals can be assigned to any primitive type variable.
byte a = 68;
char a = 'A'
Literals in Java cont…
• Literals in Java can be classified into six types, as below:
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals
• These literals are again specified in different sub-types, let us see one by one
in the article.
Literals in Java cont…
Literals in Java cont…
1. Integer Literals
• Integer literals are sequences of digits.
• For Integral data types (byte, short, int, long).
• Integral literals are specified in four different ways, as follows:
• Decimal(Base 10) :
• It has base 10, and digits from 0 to 9.
• It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted.
• For example, 5678, +657, -89, etc.
Int x = 108;
Literals in Java cont…
• Octal (Base 8)
• It has base eight and allows digits from 0 to 7.
• While assigning, a number must have a prefix 0.
• For example, 045, 026, etc.
int x = 0146;
• Hexa-Decimal (Base 16)
• The sequence of digits preceded by 0x or 0X is considered as hexadecimal
integers.
• It may also include a character from a to f or A to F that represents numbers
from 10 to 15, respectively.
• Furthermore, both uppercase and lowercase characters can be used, Java
provides an exception here.
Literals in Java cont…
• For example, 0xd, 0xf,
int x = 0X123Face;
int hexa = 0x64;
• Binary
• A literal in this type should have a prefix 0b and 0B, from 1.7 one can also
specify in binary literals, i.e. 0 and 1.
int x = 0b1111;
• Refer Litint.java
• Refer Litint1.java
Literals in Java cont…
2. Floating-Point Literals in Java
• The vales that contain decimal are floating literals.
• In Java, float and double primitive types fall into floating-point literals.
• Not be specified in octal or hexadecimal form.
• Here, datatypes can Floating-point literals can indicate a positive or negative
value, leading + or – sign respectively.
• If not specified, the value is always considered positive.
• Floating-point literals for float type end with F or f.
• It is a 32-bit float literal.
• For example, 6f, 8.354F, etc.
float length = 155.4f;
Literals in Java cont…
• Floating-point literals for double type end with D or d.
• It is optional to write D or d.
• It is a 64-bit double literal.
• For example, 6d, 8.354D, etc.
decimalNumber = 89d;
double interest = 99658.445;
• It can also be represented in the form of the exponent.
• Integer digits (representing digits 0 through 9) followed by either a suffix or an
exponent to distinguish it from an integral literal.
decimalNumber = 3.14159e0;
decimalNumber = 1.0e-6D; double val= 1.234e2;
Literals in Java cont…
• Refer Litflw.java
• Refer Litflw1.java
• By default, every floating type is a double type and this the reason why we
cannot assign it directly to float variable, that’s why for
• Single precision (4 bytes) floating-point number indicating either f or F
• Double precision (8 bytes) floating-point number indicating d or D
• Of course this convention is not required.
Literals in Java cont…
3. Char Literals
• Character (Char) literals have the type char and are an unsigned integer
primitive type.
• They are constant value character expressions in the Java program.
• These are sixteen-bit Unicode characters that range from 0 to 65535.
• Char literals are expressed as a single quote, a single closing quote, and the
character in Java.
• Char literals are specified in four different ways, as given below:
• Single quote: Java literal is specified to a char data type as a single character
enclosed in a single quote.
• For example,
char ch = ‘a’;
Literals in Java cont…
• Char Literal: Java literal is specified as an integer literal representing the
Unicode value of a char.
• This integer can be specified in octal, decimal, and hexadecimal, ranging from 0
to 65535.
• For example,
char ch = 062;
• Escape Sequence: Every escape char can be specified as char literal.
• For example,
char ch = ‘\n’;
Literals in Java cont…
• Unicode Representation: Java literal is specified in Unicode representation ‘\
uzzz’, where zzzz are four hexadecimal numbers.
• For example,
char ch = ‘\u0061’;

• Refer Litcha.java
Literals in Java cont…
4. String Literals
• A sequence of (zero or more including Unicode characters) characters within
double quotes is referred to as string literals.
• For example,
String s = “Hello”;
String text = "This is a String literal\n" +
"which spans not one and not two\n" +
"but three lines of text.\n";
• String literals may not have unescaped line feed or newline characters, but the
Java compiler always evaluates compile-time expressions.
Literals in Java cont…
• Unicode escape sequences or special characters can be used within the string
and character literal as backlash characters to escape special characters
Name Character ASCII Hex

Single quote \’ 39 0x27

Double quote \” 34 0x22

Carriage control \r 13 0xd

Backlash \\ 92 0x5c

Newline \n 10 0x0a

NUL character \0 0 0x00

Backspace \b 8 0x08

TAB \t 9 0x09
Literals in Java cont…
• Refer Litstr.java
Literals in Java cont…
5. Boolean Literals
• Boolean literals allow only two values and thus are divided into two literals:
• True: it represents a real boolean value
• False: it represents a false boolean value
• For example,
boolean b = true;
boolean d = false;
• Refer Litboo.java
Literals in Java cont…
6. Null Literals
• Null literal is a particular literal in Java representing a null value.
• This value refers to no object.
• Java throws NullPointerException.
• Null often describe the uninitialized state in the program.
• It cannot be cast to a primitive type such as int. float etc. but can be cast to a
reference type.
• Also, null does not have the value 0 necessarily.
• Refer Litnul.java
Literals in Java cont…
Real Literals
• The numbers that contain fractional parts are known as real literals.
• We can also represent real literals in exponent form.
• For example, 879.90, 99E-3, etc.
Backslash Literals
• Java supports some special backslash character literals known as backslash
literals.
• They are used in formatted output.
• For example:
\n: It is used for a new line
\t: It is used for horizontal tab
Literals in Java cont…
\b: It is used for blank space
\v: It is used for vertical tab
\a: It is used for a small beep
\r: It is used for carriage return
\': It is used for a single quote
\": It is used for double quotes
Literals in Java cont…
Restrictions to Use Underscore (_)
• It can be used at the beginning, at the end, and in-between of a number.
• It can be adjacent to a decimal point in a floating-point literal.
• Also, can be used prior to an F or L suffix.
• In positions where a string of digits is expected.
• Refer Litall.java
Variables in Java
• Variables are the basic requirements in JAVA program.
• It is the basic unit of storage.
• It acts as a container and is used to hold data values.
• The values held by the variable can be changed during the execution of the
program.
• Every variable is assigned a data type.
• Variable, in simpler terms, is a name given to a memory location.
Variables in Java cont…
Variables in Java can be of Different Types:
• String: Used to store textual matter such as “Welcome”.
• int: Used to store integer values such as 567.
• float: Stores floating-point numbers such as 29.99.
• char: Stores single characters, such as ‘s’, ‘R’.
• boolean: Stores values that pertain to two states-“True or False”
Variables in Java cont…
Variable Declaration and Initialization
• A variable is declared by specifying the following parameters:
• Datatype: The type of data that is stored in the variable.
• Variable name: The unique name given to the variable.
• Value/Literal: The initial value stored in the variable.
data_type variable_name = value;
• Declaring (Creating) Variables
int num; //declaration of variable
Variables in Java cont…
• Similarly, you can assign the values to the variables while declaring them,
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
Variables in Java cont…

int myNum = 15;


myNum = 20; // myNum is now 20
System.out.println(myNum);

• Final Variables
• However, you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the variable as "final"
or "constant", which means unchangeable and read-only):
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final
variable
Variables in Java cont…

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

• Display Variables
• The println() method is often used to display variables.
• To combine both text and a variable, use the + character:
String name = “Ram";
System.out.println("Hello " + name);
Variables in Java cont…

• You can also use the + character to add a variable to another variable:
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);

• For numeric values, the + character works as a mathematical operator


(notice that we use int (integer) variables here):
• int x = 5;
• int y = 6;
• System.out.println(x + y); // Print the value of x + y
Variables in Java cont…
Declare Many Variables
• To declare more than one variable of the same type, use a comma-separated
list:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Java Identifiers
• All Java variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Variables in Java cont…

// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
Variables in Java cont…
The general rules in java for naming variables
1. Variables naming cannot contain white spaces,
for example: int num ber = 100; is invalid because the variable name has
space in it.
2. Names can contain letters, digits, underscores, and dollar signs.
3. Names must begin with a letter.
4. Names should start with a lowercase letter and it cannot contain
whitespace
5. Variable name can begin with special characters such as $ and _
6. Names are case sensitive ("myVar" and "myvar" are different variables)
7. Reserved words (like Java keywords, such as int or boolean) cannot be
used as names.
Variables in Java cont…
Variable naming convention in java
• There are particular conventions to be followed when naming variables to
enhance the readability of the program.
1. Its convention to start the names of a variable with an alphabet rather than
an underscore or a dollar sign.
2. Variable names can have any alphabets or numbers after the first letter.
However, spaces are not allowed.
3. The reserved words such as int, static, void and so on cannot be used as
variable names.
4. Constant values can be stored in variables which are named in “ALL_CAPS”.
5. Variables which need two distinct words can be written together using
camelCase.
• Example– int amountOfWater=1000; //This preserves the meaning of variable.
Variables in Java cont…
Types of Variables in Java
• There are three types of variables:
1. Local Variables
2. Instance Variables
3. Static or Class Variables
1) Local Variables
• Local Variables are a variable that are
declared inside the body of a method.
• Local variables are declared in methods,
constructors, or blocks.
Variables in Java cont…
• Their scope is limited to the method which means that You can’t change their
values and access them outside of the method.
• Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or
block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
• Refer Var1.java
• Refer Var2.java
Variables in Java cont…
2) Instance or Non-Static Variables
• Instance variables are defined without the STATIC keyword.
• They are defined Outside a method declaration.
• They are Object specific and are known as instance variables.
• Instance variables are declared in a class, but outside a method, constructor
or any block.
• When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
• Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
• Refer Employee.java
• Refer InstanceVarExample.java
Variables in Java cont…
3) Class or Static Variables
• Static variables are also known as class variable because they are associated
with the class and common for all the instances of class.
• As soon a class loads, the static variables get their initialization.
• Class variables are declared with the static keyword in a class, but outside a
method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
• Static Variables are declared in the following way:
static <variable_name> =<variable_value>
• Refer Employee1.java
• Refer StaticVarExample.java
Operators
• Operators are special symbols that perform specific operations on one, two,
or three operands, and then return a result.
• The operators in the following table are listed according to precedence
order.
• The closer to the top of the table an operator appears, the higher its
precedence.
• Operators with higher precedence are evaluated before operators with
relatively lower precedence.
• Operators on the same line have equal precedence.
• When operators of equal precedence appear in the same expression, a rule
must govern which is evaluated first.
• All binary operators except for the assignment operators are evaluated from
left to right; assignment operators are evaluated right to left.
Operatorscont…
Precedence of Java Operators
• Operator precedence determines the grouping of terms in an expression.
• This affects how an expression is evaluated.
• Certain operators have higher precedence than others;
• for example, the multiplication operator has higher precedence than the
addition operator −
• For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator *
has higher precedence than +, so it first gets multiplied with 3 * 2 and then
adds into 7.
• Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom.
• Within an expression, higher precedence operators will be evaluated first.
Operators cont…
Operators Precedence Associativity
postfix expr++ expr-- Left to right
unary ++expr --expr +expr -expr ~ ! Right to left
multiplicative */% Left to right
additive +- Left to right
shift << >> >>> Left to right
relational < > <= >= instanceof Left to right
equality == != Left to right
bitwise AND & Left to right
bitwise exclusive OR ^ Left to right
bitwise inclusive OR | Left to right
logical AND && Left to right
logical OR || Left to right
Ternary/Conditional ?: Right to left
= += -= *= /= %= &= ^= |= <<=
assignment Right to left
>>= >>>=
Operatorscont…
• Java Operators are mainly of the following types:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators
Operatorscont…
Arithmetic Operators

Operator Description
Additive operator (also used for
+ String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Operatorscont…
Operator Description Example
Arithmetic Operators
Adds values on either side
+ (Addition) A + B will give 30
• Refer Arth.java of the operator.
Subtracts right-hand
- (Subtraction) operand from left-hand A - B will give -10
operand.
Multiplies values on
* (Multiplication) either side of the A * B will give 200
operator.
Divides left-hand operand
/ (Division) by right-hand operand. B / A will give 2

Divides left-hand operand


by right-hand operand
% (Modulus) and returns remainder. B % A will give 0

Increases the value of


++ (Increment) operand by 1. B++ gives 21

Decreases the value of


-- (Decrement) operand by 1. B-- gives 19
Operatorscont…
Relational Operators
• The relational operators determine if one operand is greater than,
less than, equal to, or not equal to another operand.
• Refer Relt.java

Operator Description
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Operator
Operators cont…
Description Example
Relational Checks if the values of two operands are equal or not, if
== (equal to) yes then condition becomes true. (A == B) is not true.
Operators
Checks if the values of two operands are equal or not, if
!= (not equal to) values are not equal then condition becomes true. (A != B) is true.

Checks if the value of left operand is greater than the


> (greater than) value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the value
< (less than) of right operand, if yes then condition becomes true. (A < B) is true.

Checks if the value of left operand is greater than or


>= (greater than or equal to the value of right operand, if yes then condition
becomes true. (A >= B) is not true.
equal to)

Checks if the value of left operand is less than or equal


<= (less than or equal to the value of right operand, if yes then condition
becomes true. (A <= B) is true.
to)
Operatorscont…
• Assignment Operator Description Example
Simple assignment operator. Assigns values from C = A + B will assign
=
Operators right side operands to left side operand. value of A + B into C
Add AND assignment operator. It adds right operand
C += A is equivalent to
+= to the left operand and assign the result to left
operand. C=C+A
Subtract AND assignment operator. It subtracts right
-= operand from the left operand and assign the result C -= A is equivalent to C
to left operand. =C–A
Multiply AND assignment operator. It multiplies
*= right operand with the left operand and assign the C *= A is equivalent to
result to left operand. C=C*A
/= Divide AND assignment operator. It divides left
operand with the right operand and assign the C /= A is equivalent to
C=C/A
result to left operand.
Modulus AND assignment operator. It takes
C %= A is equivalent to
%= modulus using two operands and assign the result
C=C%A
to left operand.
Operatorscont…
• Assignment Operators Operator Description Example
Left shift AND assignment C <<= 2 is same
• Refer Assig.java <<= operator. as C = C << 2
Right shift AND assignment C >>= 2 is same
>>=
operator. as C = C >> 2
Bitwise AND assignment C &= 2 is same
&=
operator. as C = C & 2
bitwise exclusive OR and C ^= 2 is same as
^= assignment operator. C=C^2
bitwise inclusive OR and C |= 2 is same as
|= assignment operator. C=C|2
Operatorscont…
Unary Operators
• The unary operators require only one operand; they perform various
operations such as incrementing/decrementing a value by one, negating an
expression, or inverting the value of a boolean.
• Refer Unar.java

Operator Description
Unary plus operator; indicates positive value (numbers are positive without
+
this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
Operatorscont…
The Logical Operators
• The && and || operators perform Conditional-AND and Conditional-
OR operations on two boolean expressions.
• These operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.
Operatorscont…
The Logical Operators
• Refer Log.java Operator Description Example
Called Logical AND operator. If both
&& (logical the operands are non-zero, then the (A && B) is
and) condition becomes true. false

Called Logical OR Operator. If any of


|| (logical the two operands are non-zero, then (A || B) is
or) the condition becomes true. true

Called Logical NOT Operator. Use to


reverses the logical state of its
! (logical operand. If a condition is true then !(A && B) is
not) Logical NOT operator will make false. true
Operatorscont…
The Bitwise Operators
• Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.
• Bitwise operator works on bits and performs bit-by-bit operation.
• Assume if a = 60 and b = 13; now in binary format they will be as follows −
• a = 0011 1100
• b = 0000 1101
• -----------------
• a&b = 0000 1100
• a|b = 0011 1101
• a^b = 0011 0001
• ~a = 1100 0011
Operatorscont…
The Bitwise Operators
• The following table lists the bitwise operators −
• Assume integer variable A holds 60 and variable B holds 13 then −
• Refer Bit.java
Operator
Operatorscont… Description Example
Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is
& (bitwise and) exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is 0011
| (bitwise or) operand. 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
^ (bitwise XOR) operand but not both. 0001

Binary Ones Complement Operator is unary and (~A ) will give -61 which is 1100
~ (bitwise compliment) 0011 in 2's complement form
has the effect of 'flipping' bits. due to a signed binary number.

Binary Left Shift Operator. The left operands value A << 2 will give 240 which is
<< (left shift) is moved left by the number of bits specified by 1111 0000
the right operand.
Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by
>> (right shift) the right operand. A >> 2 will give 15 which is 1111

Shift right zero fill operator. The left operands


value is moved right by the number of bits A >>>2 will give 15 which is 0000
>>> (zero fill right shift) specified by the right operand and shifted values 1111
are filled up with zeros.
Operatorscont…
• Conditional Operator ( ? : )
• Conditional operator is also known as the ternary operator.
• This operator consists of three operands and is used to evaluate Boolean
expressions.
• The goal of the operator is to decide, which value should be assigned to the
variable.
• The operator is written as −
variable x = (expression) ? value if true : value if false

• Refer Cond.java
Operatorscont…
instanceof Operator
• This operator is used only for object reference variables.
• The operator checks whether the object is of a particular type (class type or
interface type).
• The operator is written as −
( Object reference variable ) instanceof (class/interface type)
• Refer Inst.java
• This operator will still return true, if the object being compared is the
assignment compatible with the type on the right.
• Refer Inst1.java

You might also like