1.introduction To Java
1.introduction To Java
DATE : 13.02.2025
Contents
01
Introduction
to Java
02
Java Tokens
03
Read User
Input
What is Java?
• It is a platform – Has a runtime environment (JRE) and a comprehensive set of APIs that allow
developers to build and run Java applications across different hardware and operating systems.
History
• Java’s initial work started in 1990 by Sun Microsystems engineer Patrick Naughton as a part of the
Stealth Project.
• The Stealth Project soon changed to the Green Project, with Mike Sheridan and James Gosling
joining the ranks, and the group began developing new technology for programming next-generation
smart appliances.
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
• Gosling attempted to modify and extend C++ but quickly abandoned this approach in favor of creating an
entirely new language.
History
• Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt. After that, it was called
Oak, named after the tree that stood outside his office.
• Originally designed for small, embedded systems in electronic appliances like set-top boxes. Then
incorporate some changes based on emergence of World Wide Web, which demanded portable
programs.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
• The first publicly available version of Java (Java 1.0) was released in 1995.
• In 2006 Sun started to make Java available under the GNU General Public License (GPL). Sun
Microsystems was acquired by the Oracle Corporation in 2010. Oracle continues this project called
OpenJDK.
Where it is used?
• Java is almost everywhere and more than 60 billion devices run Java.
• It is used create desktop Applications, Web Applications, Enterprise Applications such as banking
• Embedded System
• Games etc.,
Editions
Version
Version
Version
Environment
• The classes and methods are part of Java Standard Library (JSL), also known as Application
• It includes hundreds of classes and methods grouped into several packages according to their
functionality.
Environment - JDK
• Java Development Kit(JDK) : It is a software development kit used by Java developers for building Java
applications.
• JDK consists of :
• Java Runtime Environment (JRE): Includes a version of the JRE, which provides the runtime environment for
executing Java applications. The JRE consists of the JVM and libraries required for running Java bytecode.
Environment - JDK
• JDK consists of :
• Java Archive (JAR) tool: A utility for creating and managing JAR files, which are compressed archives that
contain Java classes and resources.
• JavaDoc tool: A tool for generating HTML documentation from Java source code comments
Environment - JRE
• JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine
(JVM), and other components that are required to run Java applications.
Environment - JVM
• Java Virtual Machine(JVM) : It's a virtual machine that allows a computer to run Java programs.
• JVM is a runtime environment that loads, verifies, and executes Java bytecode, and converts bytecode to
machine-specific code.
1.Class Loader
3.Execution Engine
Environment - JVM
• Class loader:
• When you run a Java program, the class loader searches for the necessary classes and loads them into the
runtime data area.
• JVM stores data in the runtime data area during program execution.
Environment - JVM
• Execution engine :
• Responsible for executing the bytecode (compiled Java code) with the help of Java interpreter and JIT
compiler that is loaded into the JVM.
• The JVM also includes a garbage collector, which automatically frees up memory that is no longer being used by the
program.
Environment - JVM
Interpreter
• The interpreter reads and executes the bytecode instructions line by line. Due to the line-by-line execution, the
interpreter is comparatively slower.
• Another disadvantage of the interpreter is that when a method is called multiple times, every time a new
interpretation is required.
JIT Compiler
• The JIT Compiler overcomes the disadvantage of the interpreter. The Execution Engine first uses the
interpreter to execute the byte code, but when it finds some repeated code, it uses the JIT compiler.
• The JIT compiler then compiles the entire bytecode and changes it to native machine code. This native machine
code is used directly for repeated method calls, which improves the performance of the system.
Environment
JVM
(Java Interpreter + Just-In-Time
Compiler )
Note
• JVM, JRE and JDK are ported to different platforms to provide hardware and operating system-
independence.
22 Java Introduction | © SmartCliff | Internal | Version 1.0
Introduction to Java
Full From Java Development Kit Java Runtime Environment Java Virtual Machine
Features
• Simple – Java syntax based on earlier languages like C and C++. Designed considering the pitfalls of
earlier languages
• Secured – No explicit pointer support, run inside the java virtual machine sandbox. The class
loader, byte code verifier and security manager component of JVM enable the secured environment.
Java also supports application developer to use other security mechanism like SSL, JAAS,
Cryptography, etc.
Features
• Robust – Java have strong memory management, lack of pointers that avoids security problems,
• Platform Independent - Once compiled ,code will be run on any platform without recompiling or any kind
of modification -“Write Once Run Anywhere(WORA)”. This is made possible by making use of a Java
Virtual Machine(JVM).
Note
• JVM, JRE and JDK are ported to different platforms to provide hardware and operating system-
independence.
Features
• Distributed – Java enable to create distributed application with the help of RMI and EJB
Environmental Setup
• To run Java applications, we need to prepare the environmental setup. For installing Java we need
the following:
• The Java Runtime Environment (JRE) (Includes Java Virtual Machine (JVM))
• A text editor
Environmental Setup
Eclipse IDE
• Using a text editor is the basic way of creating a Java program, but there are tools available to make it
Eclipse IDE
Eclipse IDE
Other Versions to
download from
here
Eclipse IDE
Eclipse IDE
Eclipse IDE
Once the workspace is chosen, you will get the welcome page
Eclipse IDE
After closing the welcome screen ,the project explorer and other options will be shown up.
Now you are ready to start working.
Eclipse IDE
Eclipse IDE
Create First Java Program with file extension .java Example: HelloworldApp.java
Eclipse IDE
After creating the application, run the application with a run command
Eclipse IDE
/**
*/
class HelloWorldApp {
}
40 Java Introduction | © SmartCliff | Internal | Version 1.0
Introduction to Java
• Code conventions are important to the programmer for the following reasons
• Readability: Describe the code with comments and name the Identifiers relative to the objective of
the code and ensure other people can understand the code.
• Modularity: When there is a need to redo the small fraction of code then practice using the existing
or reusing the code.
• Efficiency: The code should be fast and economical. When using data files, read a value once and
store it in a variable – don’t go back and forward for the same value. Close connections if they are
not required. Do not hold onto references to variables if not required, so as not to impose a memory
leak.
• Source file of java can be saved with the extension or suffixes “Filename.java”.
• Comments
Indentation
• When the statement is not fit in a single line, then wrap the lines based on the following principles.
Example:
public void Cart(string product_name, double cost,
int quantity, string description)
Indentation
Example: //Breaking an arithmetic expression before an operator and outside the parenthesized
expression at a high level.
Calculation = a*(b + c - d)
+4*b
• Align the new line with the beginning of the expression at the same level on the previous line.
• If the above rules lead to confusing code or to code that's squished up against the right margin, just
Indentation
Indentation
Blank Lines:
- Between methods
Indentation
Blank Spaces:
• Black Spaces are used to improve the reliability of the code and can be used in the following
circumstances
Example:
while (false){
}
• It should not be used between a method name and its opening parenthesis. This helps to
distinguish keywords from method calls.
Indentation
• Except ‘.’ and unary operators all the binary operators should be separated their operands by spaces.
Comments
• Block comments:
• Block comments (/***/) are used to provide descriptions of files, methods, data structures,
and algorithms.
• Block comments may be used at the beginning of each file and before each method and also
within methods.
• Block comments inside a function or method should be indented to the same level as the
code they describe.
Example:
/*
*Here is a block comment
*/
Comments
• Single-Line comments:
• A short description of a block of code can be given using single-line comments (/*..*/).
• If a comment can't be written in a single line, it should follow the block comment format.
Example:
if(condition) {
/* Description about bock of code in a single line */
}
Comments
• Trailing comments:
• Trailing comments (/*..*/) are very short comments that describe the statements.
• These comments can be included in the same line of the statement but should be separated
• If more than one short comment appears in a code, they should all be indented to the same tab.
Example:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); /* Display the Hello World! */
}
}
Comments
• This comment line (//) can be used as a single-line comment or a short comment for a statement.
• These comments can be included in the same line of the statement but should be separated from the
• This can be used in consecutive multiple lines for commenting out sections of code.
Example:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the Hello World!
}
}
Documentation Comments
• Documentation comments are generally used when writing code for a project/software package.
• It helps to generate a documentation page for reference, which can be used for getting information
• The JavaDoc tool is used to process the doc comments that come with JDK and it is used for generating
Java code documentation in HTML(HyperText Markup Language) format from Java source code, which
Documentation Comments
Javadoc Tag:
• These doc tags enable you to autogenerate a complete, well-formatted API from your source code.
• The tags start with an "at" sign (@) and are case-sensitive (i.e).,they must be in upper and lowercase
• A tag must start at the beginning of a line (after any leading spaces and an optional asterisk) or it is
Documentation Comments
• Block tags - Can be placed only in the tag section that follows the main description.
- Example: @tag
• Inline tags - Can be placed anywhere in the main description or in the comments for block tags and
- Example: {@tag}
Documentation Comments
Javadoc Tags:
• Below table describe the Javadoc tag that is used in documentation comments.
Documentation Comments
@return Adds a "Returns" section with the description text. @return description
Documentation Comments
@throws The @throws and @exception tags are synonyms. @throws class-name description
Documentation Comments
Documentation Comments
• Each line above is indented to align with the code below the comment.
• Write the first sentence as a short summary of the method, as Javadoc automatically
• The inline tag can be used anywhere that a comment can be written, such as in the text
Documentation Comments
• If we have more than one paragraph in the doc comment, separate the paragraphs with a <p>
paragraph tag.
• Insert a blank comment line between the description and the list of tags.
• The first line that begins with an "@" character ends the description.
• There is only one description block per doc comment; we cannot continue the description following
block tags.
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
* Doc comment
* @author SmartCliff
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the Hello World!
}
}
• public keyword is an access modifier which represents visibility, it means it is visible to all.
• The core advantage of static method is that there is no need to create object to invoke the static
method.
• The main method is executed by the JVM, so it doesn't require to create object to invoke the main
• void is the return type of the method, it means it doesn't return any value.
64 Java Introduction | © SmartCliff | Internal | Version 1.0
Introduction to Java
System.out.println();
Package: Introduction
Java Package
Sub-Packages (lang, io, util, etc.,) interfaces
Package: Introduction
1. Built-in Packages: The already defined package in Java API like java.io.*, java.lang.* etc. are known
2. User-defined Packages: The package created by user and use based on application needs is called
user-defined package.
Note:
• Programmers typically use packages to organize classes belonging to the same category or providing
similar functionality.
67 Java Introduction | © SmartCliff | Internal | Version 1.0
Introduction to Java
Package: Introduction
System.out.println();
Note:
• As per Java 1.8 standard version, Java have 14 predefined packages, 150 sub packages, 7000
classes and 7 lakh methods.
• The source code of Java will be created with file extension .java, Example: HelloworldApp.java
• The java Compiler compiles a java file and convert into bytecode / classfile.
• The .class file is interpreted by the JVM and morphed into machine specific code.
• The Just-In-Time (JIT) compiler is one of the integral parts of the Java Runtime Environment.
• It improves the performance of Java applications by compiling byte codes to native machine code at
run time.
• The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled
• Theoretically, if compilation did not require processor time and memory usage, compiling every method
could allow the speed of the Java program to approach that of a native application.
Introduction
• The tokens are the small building blocks of a Java program that are meaningful to the Java compiler.
• The Java compiler breaks the line of code into text (words) is called Java tokens.
• These tokens are separated by the delimiters and delimiters are not part of the Java tokens.
Example: In program, we will be using many statements and expressions to perform the operation. These
Introduction
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Special symbols
Keywords
• Keywords are predefined or reserved words that have special meaning to the Java compiler.
• Each keyword is assigned a special task or function and cannot be changed by the user.
• We cannot use keywords as variables or identifiers as they are a part of Java syntax itself.
Keywords
Keywords
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
76 Java Introduction | © SmartCliff | Internal | Version 1.0
Java Tokens
Identifiers
• An identifier is the name given by the user for the various programming elements like variables,
classes, methods, interface, etc.
• Allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign)
and ‘_‘ (underscore).
Identifiers
• There is no limit on the length of the identifier, but it is advisable to use an optimum length of 4 – 15
letters only.
• All the identifiers such as classes, interfaces, packages, methods, and fields of Java programming
• By using this naming convention, we can achieve readability and can also easily understand the code.
• In programming, we often remove the spaces between words because programs of different sorts
• Because the space character is reserved, we cannot use it to represent a concept that we express in
Example
• That is in programming we cannot refer, user login count=5.
• We can represent as userLoginCount=5.
• Java follows the CamelCase for identifiers naming conventions.
CamelCase
- Combines the compound words and removes the space between the words.
- Two types: UpperCamelCase and lowerCamelCase.
- UpperCamelCase: The first letter of each word is capitalized.
Example: Product, ProductDescription, CountValue.
- LowerCamelCase: The first letter of the compound words is lowercase.
Example: product, iPad, countValue, productDescription
• A variable's name can be any legal identifier i.e., begins with a letter, the dollar sign "$", or the
underscore character “_“.
• The variable name should be short and meaningful.
• The choice of a variable name should be mnemonic- that is, designed to indicate to the casual
observer the intent of its use.
• One-character variable names should be avoided except for temporary variables.
• The temporary variables can be i,j,k,m, and n for integer and c,d,e for characters.
• Apart from its name and its type, the scope of a variable is its most important feature.
• Indicating class scope by using underscore makes it easy to distinguish class variables from local
scratch variables.
• This is important because class variables are considered to have higher significance than method
variables, and should be treated with special care by the programmer
Example:
class Login{
private String _userName;
…
}
Constants:
• If we specify the constant with two words, then separated by underscores ("_").
Example:
static final int MAX_HEIGHT = 70;
static final int MAX_WIDTH = 100;
static final int LENGTH = 20;
Methods
Example:
void calculateTax()
String getSurname()
void draw()
• The first non-comment line of the java source file is a package followed by import statements.
• The prefix of a unique package name is always written in all-lowercase ASCII letters.
Example:
package java.util.*;
import java.util.Scanner;
Example:
class Customer
class CustomerAccount
class Login
• Interface tends to have a name that describes an operation that a class can do.
Example:
interface Enumerable
interface CompEnumerable
interface Login
Data Types
• Data types defines the type data a variable can hold. It specify the different sizes and values that can be
stored in the variable.
Data Types
• byte: (1 byte):
–It has a minimum value of -128 and a maximum value of 127 (inclusive).
–Default value : 0
• short: (2byte)
–It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).As byte ,can use
a short to save memory in large arrays
–Default value : 0
Data Types
• int: (4 byte)
– By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of
-231 and a maximum value of 231 -1.
– Default value : 0
• long: (8 byte)
– The long data type is a 64-bit two's complement integer.
– The signed long has a minimum value of -263 and a maximum value of 263-1
– Default value : 0L
• float: (4 byte)
– The float data type is a single-precision 32-bit IEEE 754 floating point.
– Default value : 0.0f
Data Types
• double: (8 byte)
– The double data type is a double-precision 64-bit IEEE 754 floating point
– Default value : 0.0d
• boolean: (1 bit)
– The boolean data type has only two possible values: true and false
– Default value : false
• char: (2 byte)
– single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value
of '\uffff‘
– Default value : '\u0000'
Variables
• A symbolic name associated with a value and whose associated value may be changed.
• All variables have a scope, which defines their visibility, and a lifetime.
1.Local Variables
Variables
Local Variables
• Other methods in the class aren't even aware that the variable exists.
Variables
• A variable declared inside the class but outside the body of the method, is called instance
variable.
• Instance variables are created when the objects are instantiated and therefore they are associated
Variables
• A variable which is declared as static is called static variable. It is also called as a class variable
• It cannot be local.
• You can create a single copy of static variable and share among all the instances of the class.
• Memory allocation for static variable happens only once when the class is loaded in the memory.
Variables
/**
* The VariableApp class implements an application that
* illustrate different Java variable
* @author Smartcliff
*/
class VariableApp {
int mark = 95 ;//instance variable
static char grade = ‘S’; // static variable
public static void main(String[] args) {
float average=95.0 // local variable
}
}
Literals
Literals
• In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits
in a numerical literal.
• Enables to separate groups of digits in numeric literals, which can improve the readability of your
code.
Example:
Literals
• You can place underscores only between digits; you cannot place underscores in the following
places:
–Prior to an F or L suffix
Unicode
• It is Computing industry standard designed to encode characters of the world's written languages.
• Unicode System?
–ASCII (American Standard Code for Information Interchange) for the United States.
Unicode
• Problems:
–A particular code value corresponds to different letters in the various language standards.
–The encodings for languages with large character sets have variable length.
– Some common characters are encoded as single bytes, other require two or more byte.
• Solution:
–To solve these problems, a new language standard was developed i.e. Unicode System.
–In Unicode, character holds 2 byte, so java also uses 2 byte for characters.
Operators
• An operator in Java is a special symbol that signifies the compiler to perform some specific
Expression
• An expression in Java is any valid combination of tokens like variables, constants and operators.
• An expression may consist of one or more operands, and zero or more operators to produce a value.
Examples:
-a+b*c
- (a * b) / (c + d)
- 10 – 4 * 5
- Etc.,
• Below table we have listed down all the operators, along with their expressions:
Type Operators Expressions
Unary Operator ++,--,+(unary),-(unary), ~,! a++,--a, -a, ~a, !a
Precedence
• Operator precedence determines the order in which the operators in an expression are evaluated.
To evaluate the above expression Java, consider the precedence of the operator. Here, Multiplication (*) has the
highest precedence over subtraction (-). So multiplication will be performed before the subtraction.
Associativity
• If an expression has two operators with similar precedence, the expression is evaluated according
to its associativity.
= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=
Expression Evaluation
Example 1 : 10 – 3 % 8 + 6 / 4 Example 2: 6 - ( 5 – 3 ) + 10 Example 3 : 3+4*4>5*(4+3) -1
Introduction
• Bitwise operators are used to perform operations at the bit level and help to manipulate data at the
• These can be done by first converting a decimal value to its binary form. This binary form is nothing
Types
Operator Meaning
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
Types : AND(&)
Types : AND(&)
• Example: Let's take a look at the bitwise AND operation of two integers 12 and 25.
• Now move from left to right, and perform logical AND operations on the bits, and store the result
in the corresponding position.
00001100
& 00011001
____________
Types : AND(&)
// Bitwise AND
class Main { Output: 8
public static void main(String[] args) {
Types : OR(|)
AND, i.e. if at least any one of the operands has 1, then Result=Num1 |
Num1 Num2
Num2
the result will also have 1 in the corresponding position,
0 0 0
Types : OR(|)
• Example: Let's take a look at the bitwise OR operation of two integers 12 and 25.
• Now move from left to right, and perform logical OR operations on the bits, and store the result in
the corresponding position.
00001100
| 00011001
____________
Types : OR(|)
// Bitwise OR
Output: 29
class Main {
public static void main(String[] args) {
Types : XOR(^)
that they perform logical XOR on the bit level, i.e., if Result=Num1 ^
Num1 Num2
Num2
exactly one of the operands has 1 and the other has 0
0 0 0
Types : XOR(^)
• Example: Let's take a look at the bitwise OR operation of two integers 12 and 25.
• Now move from left to right, and perform logical AND operations on the bits, and store the result
in the corresponding position.
00001100
^ 00011001
____________
Types : XOR(^)
// Bitwise XOR
Output: 21
class Main {
public static void main(String[] args) {
• The bitwise complement operator takes a single value Truth table for Bitwise Complement
operator
and returns the one’s complement of the value.
• It is important to note that the bitwise complement of any integer N is equal to - (N + 1).
• For example :Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 +
1) = -36. Now let's see if we get the correct answer or not.
~ 00100011
__________
11011100
• In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we
convert the result into decimal we get 220.
• However, it is important to note that we cannot directly convert the result into decimal and get the
desired output. This is because the binary result 11011100 is also equivalent to -36.
2's Complement
• In binary arithmetic, we can calculate the binary negative of an integer using 2's complement.
• 1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1's complement, we get
the 2's complement of the original number. Example as Follows
2's complement:
11011011
+ 1
_________
11011100
• Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise
complement of 35.Hence, we can say that the bitwise complement of 35 is -(35 + 1) = -36.
// Bitwise Complement
class Main { Output: -36
• The left shift operator (<<) is a bitwise operator that shifts the bits of a binary number to the left by
• In other words, it multiplies the number by 2 raised to the power of the shift count.
– Each bit in the binary representation of the number is shifted to the left by the specified number of
positions.
– The leftmost bits that are shifted out (if any) are discarded.
filled bit
• The right shift operator (>>) is a bitwise operator that shifts the bits of a binary number to the right
by a specified number of positions.
• In other words, it divides the number by 2 raised to the power of the shift count, discarding the
remainder.
– Each bit in the binary representation of the number is shifted to the right by the specified number
of positions.
– The vacant positions on the left are filled with the sign bit (for signed integers) or with zeros (for
unsigned integers).
– The rightmost bits that are shifted out (if any) are discarded.
filled bit
• In the example, the value of num is 12, and the result of num >> 2 is 3.
• The binary representation of 12 is 0000 1100, and after right-shifting by 2 positions, it becomes
0000 0011, which is 3 in decimal.
131 Java Introduction | © SmartCliff | Internal | Version 1.0
Bitwise Operator
Bit Masking
• BIT MASKING: Bit masking is a technique in programming used to test or modify the states of the bits of
a given data.
• Here we have to decide what should be the Mask_value, and then take that Mask_value and do a
bitwisewise operation with a given data to get the output.
Bit Masking
• Bit fields in programming are used to pack multiple data fields within a single word or byte, allowing for
more efficient use of memory.
• Bitwise operators are particularly useful when working with bit fields because they enable manipulation
and extraction of specific bits within a bit field.
1.Setting and Clearing Bits: Bitwise OR (|) is commonly used to set specific bits within a bit field. You
can create a mask with the desired bit set to 1 and perform a bitwise OR with the existing value.
Bitwise AND (&) with the complement of a mask can be used to clear specific bits within a bit field.
2. Checking Bit Values: Bitwise AND (&) can be used to check the value of a specific bit within a bit
field. If the result is non-zero, the bit is set; otherwise, it is clear.
Bit Masking
3.Toggle Bits: Bitwise XOR (^) can be used to toggle specific bits within a bit field. XORing with a mask
4.Extracting Bit Fields: Right shifting (>>) can be used to extract a specific bit field from a larger bit field.
By creating a mask with the relevant bits set to 1 and using it in a bitwise AND operation, you can obtain the
5.Combining Bit Fields: Bitwise OR (|) can be used to combine multiple bit fields into a single value. This
is useful when you have separate values for different attributes packed into a single variable.
Bit Masking
TESTING OF BITS:
• Testing a bit refers to checking the value of a specific bit within a binary representation of a number
or data.
• In the context of programming and bitwise operations, testing a bit typically involves checking whether a
particular bit is set (equal to 1) or clear (equal to 0) within a binary value.
Write a program to find out whether a user entered a number is even or odd. Print an appropriate message on
Bit Masking
LOGIC:
• How this works is, let’s consider a number an integer, let’s say 46.
• If you write 46 in binary form, you get 00101110, and here the least significant bit is 0.
• Let’s consider the odd number 47. 00101111 is a binary form of 47. Here the least significant bit is 1.
• That’s why by checking or by testing the least significant bit(LSB) of a number, we can find out
whether a number is even or odd.
Bit Masking
Bit Masking
and in area 2 we can determine with the LSB bit we set the 46 00101110
Bit Masking
Bit Masking
SETTING OF BITS:
• Setting a bit means changing the value of a specific bit within a binary representation of a number or data
to 1.
Write a program to set(make bit state to 1), 4th and 7th-bit position of a given number and print the result.
Bit Masking
• we have to use a mask value.,where the 4th and 7th bits are
set(1).
Bit Masking
10111110. Here you can see that the un-affected data portion Mask_value 10010000
is not affected at the output. They are safe. So, only 4th and 10111110
Bit Masking
CLEARING OF BITS:
• Clearing a bit means changing the value of a specific bit within a binary representation of a number
or data to 0.
• In the context of programming and bitwise operations, clearing a bit involves using bitwise operations to
turn a particular bit off.
Write a program to clear(make bit state to 0) the 4th, 5th, 6th, bit positions of a given number and print the result.
Bit Masking
• First, which bitwise operation do you use to clear the given bit position of data? Do you use the bitwise
& or bitwise | operator?
• In this case, certainly, we cannot use bitwise OR (|) because that is used to SET. So, you have to
use bitwise & operator. So, bitwise ‘&’ is used to ‘TEST and CLEAR’.
Bit Masking
• The data is 10111110, and the 4th, 5th, and 6th portions must Mask_value 10001111
be zeroed out here.
10001110
• That’s why we keep this portion of the mask value as zero’s,
and the remaining bit positions of the given data should not
be affected.
• That’s why let’s mask those data portions with 1’s. So, in this
case, 10001110 ( the mask value) turns out to be 0x8F.
145 Structure, Unions & Bitfields | © SmartCliff | Version 2.0
Bitwise Operator
Bit Masking
• Observe the output. Only the 4th, 5th and 6th portions are
zeroed out,
76543210
• so the 7th portion and 0 to 3 portion are not affected, as Data 10111110
• So, the takeaway from this post is bitwise & is used to both 10001110
Bit Masking
• In this case, negate the mask value first and then perform 76543210
the bitwise &. Data 10111110
• Here, 01110000 is the mask value, and you negate that. Mask_value 01110000
When you negate that, the final output is 10001110.
10001110
Bit Masking
• The bitwise operators work at the bit level, manipulating binary representations of numbers, while
logical operators work with boolean values, evaluating conditions and controlling program flow.
• The bitwise AND, and OR use ‘&’ and ‘|’ as their operators, while the logical AND, and OR use ‘&&’
Type Conversions
• Widening or Automatic Type Conversion – lower data types are automatically convert into higher data
• Automatic type conversion will take place if the following two conditions are met:
Type Conversions
float → double
• Generally safe because they tend to go from a small data type to a larger one
Type Conversions
/**
* The ConversionAutomatic class implements an application that
* Illustrate the automatic type conversion
*/
class ConversionAutomatic {
public static void main(String[] args) {
int i = 100;
long l = i; // automatic type conversion
float f = l; // automatic type conversion
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
152 Java Introduction | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
• Narrowing or Explicit Conversion - If we want to assign a value of larger data type to a smaller data
type we perform explicit type casting or narrowing.
• Useful for incompatible data types where automatic conversion cannot be done.
• Here, target-type specifies the desired type to convert the specified value to.
Type Conversions
/**
* The ConversionExplicit class implements an application that
* Illustrate the explicit type conversion
*/
class ConversionExplicit {
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; //convert double into long
int i = (int)l; // long convert into int
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
154 Java Introduction | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
• Type promotion in Expressions - While evaluating expressions, the intermediate value may exceed
the range of operands and hence the expression value will be promoted.
1.Java automatically promotes each byte, short, or char operand to int when evaluating an
expression.
2.If one operand is a long, float or double the whole expression is promoted to long, float or double
respectively.
Type Conversions
/**
* The TypePromotion class implements an application that
* Illustrate the type promotion
* @author Smartcliff
*/
class TypePromotion{
public static void main(String[] args){
byte b = 50;
b = (byte)(b * 2); //promote into int
System.out.println(b);
}
}
156 Java Introduction | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
/**
* The TypePromotion1 class implements an application that
* Illustrate the type promotion
*/
class TypePromotion1{
public static void main(String[] args){
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s); //promote into double
System.out.println("result = " + result);
}
}
Special Symbols
• Special symbols in Java are a few characters which have special meaning known to Java compiler
• In the below table we have listed down the special symbols supported in Java along with their
description.
Special Symbols
Symbols Description
These are used as an array element reference and also indicates single and
brackets []
multidimensional subscripts
These indicate a function call along
Parentheses()
with function parameters
The opening and ending curly braces indicate the beginning and end of a block
Braces{}
of code having more than one statement
Comma ( , ) This helps in separating more than one statement in an expression
Semi-Colon (;) This is used to invoke an initialization list
Introduction
• There are three different ways to read input from the user:
2. Scanner Class
• Scanner Class: It is a class in java.util package used for obtaining the user input of the primitive
types like int and double. It is the easiest way to read input in a Java program.
• Scanner object is constructed from Scanner Class and System.in (input stream) object is passed
as a parameter while creating a scanner object.
Methods
• After creating the scanner object, we can use below Scanner class methods for reading the
respective primitive data types from the console.
Method Description
boolean nextBoolean() This method reads the boolean value from the user.
double nextDouble() It accepts the input in double datatype from the user.
Methods
Method Description
String nextLine() This method reads the String value from the user.
long nextLong() This method reads the long type of value from the user.
short nextShort() It reads the short type of value from the user.
Note:
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) function returns the first character in
that string.
163 Java Introduction | © SmartCliff | Internal | Version 1.0
Read User Input
Example: #1
/** Output:
Enter your Name : Arun
* The ReadSomeInput class implements an application that
Hi, Arun . Welcome to the Training Program
* Illustrate reading a console input */
}}
164 Java Introduction | © SmartCliff | Internal | Version 1.0
Read User Input
Introduction
InputStream
System.in BufferedReader
Reader
Quiz
a) int b) float
c) double d) boolean
Quiz
a) Class b) Method
c) Block d) Object
b) & c)
Quiz
a) Variable b) int
c)Identifiers d) Constant
d) Constant
Quiz
a) Identifier b) Keyword
b) Keyword
Quiz
a) Widening b) Narrowing
a) Widening
Quiz
a) L b) l
c) D d) 0x
a) & b)
Quiz
b) Instance variables
Quiz
a) double b) switch
c) instanceof d) then
d) then
Quiz
a) & b) |
c) ^ d) <=
d) <=
Quiz
a) ~ b) <<
c) ^ d) >>>
a) ~
Quiz
Quiz
a) true b) false
b)false
Quiz
a) num1>>2 b) num1<<<2
c) num1%=2; d) num1<<2;
b) num1<<<2
Quiz
14) In Java, after executing the following code what are the
values of x, y, and z?
x = y++ + z++;
Quiz
a)next() b) nextInt()
c) nextInteger() d) readInt()
b) nextInt()
Quiz
Quiz
c) Reference to Computer
d)None of these
System
b) Reference to Input
stream