0% found this document useful (0 votes)
96 views

1 Basics

Java Basics

Uploaded by

Bhuvana Gowtham
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)
96 views

1 Basics

Java Basics

Uploaded by

Bhuvana Gowtham
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/ 152

JAVA

What is Java?

 General-purpose, class-based, object-oriented programming language


 Developed by James Gosling in Sun Microsystems in 1995
 In 2010, Oracle acquired Sun Microsystems
Features of Java
 Simple
 Object-Oriented
 Portable
 Platform independent
 Robust
 Architecture neutral
 High Performance
 Multithreaded
 Distributed
Types of Java Applications

1) Standalone Application
2) Web Application
3) Enterprise Application
4) Mobile Application
Desktop GUI Applications

 We use APIs like AWT, Swing, JavaFX to build these applications.


 Examples of desktop GUI applications are Acrobat Reader,Media Player,
Antiviruses, etc.
Web-based Applications

 Java support for web development through Servlet, JSP, and Struts.
 Also known as a server-side programming language.
 frameworks Spring, Hibernate, Spring Boot, used for developing web-
based applications.
 LinkedIn, AliExpress, web.archive.org, IRCTC, etc. are the popular
websites that are written using Java programming language.
Enterprise Applications of Java

 Java EE (Java Enterprise Edition) is used to provide the tools to develop


large-scale,scalable, reliable, distributed and secured network applications
in enterprises.
 JavaEE is considered as the backbone for a variety of banking applications
 Companies like Naukri, Jabong, Google, Myntra, Flipkart, Trivago, ibibo,
TCS, Infosys, HCL, Wipro, Pinterest, eBay, etc use Java.
Mobile Applications

 Most of the android applications build using Java.


 Popular android app development IDE Android Studio also uses Java for
developing android applications.
 The most popular android applications Spotify and Twitter are developed
using Java
Gaming Applications

 Android games can be built with Java.


 Java supports jMonkeyEngine which is the most powerful open-source
3D-Engine and has the capacity to design 3-Dimensional games.
 some popular Frameworks and Libraries available for Game Development,
like - LibGDX and OpenGL.
 games developed in Java are Minecraft, Mission Impossible III, etc
Java Platforms / Editions
1) Java SE (Java Standard Edition)
2) Java EE (Java Enterprise Edition)
3) Java ME (Java Micro Edition)
4) JavaFX
Java Platform, Standard Edition (Java SE):

 Java SE’s API offers the Java programming language’s core functionality.
 Defines all the basis of type and object to high-level classes.
 Used for networking, security, database access, graphical user interface
(GUI) development.
Java Platform, Enterprise Edition (Java EE):
• Offers an API and runtime environment for developing and running highly
scalable, large-scale, and secure network applications.

Java Programming Language Platform, Micro Edition (Java ME):


• Offers an API and a small-footprint virtual machine running Java
programming language applications on small devices, like mobile phones.
Java FX:
Platform for developing rich internet applications using a lightweight user-
interface API.
Java Architecture
Java Architecture

• Step 1 - Create a java source code with .java extension


• Step2 - Compile the source code using java compiler, which will create
bytecode file with .class extension
• Step3 - Class loader reads both the user defined and library classes into
the memory for execution
• Step4 - Bytecode verifier validates all the bytecodes are valid and do not
violate Java’s security restrictions
• Step5 - JVM reads bytecodes and translates into machine code for
execution. While execution of the program the code will interact to the
operating system and hardware
Java JVM, JDK and JRE
Java virtual Machine(JVM)

• Java virtual Machine(JVM) provides runtime environment to execute java byte


code.

• Is an abstract machine.

• The JVM doesn't understand normal English lang, that's why we compile our
*.java files to obtain *.class files that contain the bytecodes understandable by the
JVM.
Important features of JVM are

• It enables to run applications in a cloud environment or in our device.

• Converts byte code to machine-specific code.

• Provides basic java functions like memory management, security, garbage


collection, and more.

• JVM runs the program by using libraries and files given by the Java Runtime
Environment.
• JDK and JRE both contain Java Virtual Machine.

• It can execute the java program line by line hence it is also called an interpreter.

• JVM is easily customizable for example, we can allocate minimum and maximum
memory to it.

• It is independent of hardware and the operating system. So, we can write a java
program once and run it anywhere.
The JVM performs following operation:

• Loads code

• Verifies code

• Executes code

• Provides runtime environment( in which a program or application is executed)


JVM ARCHITECTURE
• Class Loader : Class loader loads the Class for execution.

• class area : Stores pre-class structure as constant pool.

• Heap : Heap is a memory area in which objects are allocated.

• Stack : It holds local variables and partial results, and plays a part in method

invocation and return.


• Program register : Program register holds the address of JVM instruction currently
being executed.

• Native method stack : It contains all the native methods used in the application.

• Executive Engine : Execution engine controls the execute of instructions contained


in the methods of the classes.

• Native Method Interface : Native method interface gives an interface between java
code and native code during execution.

• Native Method Libraries : Native Libraries consist of files required for the
execution of native code.
native method

• A native method in Java is a method whose implementation is written in other


languages such as c and c++.

• The ‘native’ keyword is used before a method to indicate that it is implemented in


other language.
We can use native method to

• Implement an interface with system calls or libraries written in other


programming languages

• Access system or hardware resources that are only reachable from the other
language

• Integrate already existing code written in C/C++ into a java application


JRE (Java Runtime Environment)
JRE (Java Runtime Environment)

• Used to provide a runtime environment.

• Is the implementation of JVM.

• Contains a set of libraries + other files that JVM uses at runtime


JDK( Java Development Kit)
JDK( Java Development Kit)

• Is a software development environment which is used to develop java applications

and applets.

• It contains jre + development tools.


The workflow of JDK, JVM, and JRE :
• Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter .
Differences between interpreter and compiler
Interpreter Compiler

Interpreter translates just one statement of the program Compiler scans the entire program and translates the
at a time into machine code. whole of it into machine code at once.

An interpreter takes very less time to analyze the A compiler takes a lot of time to analyze the source
source code. However, the overall time to execute the code. However, the overall time taken to execute the
process is much slower. process is much faster.

It does not convert source code into object code It converts the source code into object code.
instead it scans it line by line

Keeps translating the program continuously till the A compiler generates the error message only after it
first error is confronted. If any error is spotted, it stops scans the complete program and hence debugging is
working and hence debugging becomes easy. relatively harder while working with a compiler.

Interpreters are used by programming languages like Compliers are used by programming languages like C
Ruby and Python for example. and C++ for example.
Java Code Conventions
Code /Naming convention

• Is a rule to follow when we are naming identifiers such as class, package,


variable, constant, method, etc.
• But, it is not forced to follow.
• So, it is known as convention not rule.
Advantage of Code/Naming Conventions

• By using standard Java naming conventions, we make our code easier to read

for ourself and other programmers.

• Readability of Java program is very important.

• It indicates that less time is spent to figure out what the code does.
Classes and interfaces

• First letter should be uppercase.


• If the name is created from several words, the first letter of the inner words
should be capitalized (a "camelCase" format).
• Class names must be nouns: Cat, Exam, PrintReader.
• Interface names must be adjectives: Comparable, Iterable, Navigable.
Methods

• First letter must be lowercase, and then normal camelCase rules are used.

• Names should be verb-noun pairs: getName, doJob, setLastName.


Variables

• First letter must be lowercase, and then normal camelCase rules are used.

• It is recommended to use short, understandable names: firstName,

buttonHeight.
Constants

• Constants are created by declaring variables final and static.

• Names of the constants should have uppercase letters separated with

underscore characters: MAX_WEIGHT.


Java Bean Standards In Java
JavaBean Standards in Java
• JavaBeans are Java classes that have properties
• For our purposes, think of properties as private instance variables
• Since they’re private, the only way they can be accessed from outside of their
class is through methods in the class
• The methods that change a property’s value are called setter methods, and
the methods that retrieve a property’s value are called getter methods.
JavaBean Standards in Java
• If the property is not a boolean, the getter method’s prefix must be get. For
example, getSize()is a valid JavaBeans getter name for a property named
“size”.
• If the property is a boolean, the getter method’s prefix is either get or is. For
example, getStopped() or isStopped() are both valid JavaBeans names for a
boolean property.
• The setter method’s prefix must be set. For example, setSize() is the valid
JavaBean name for a property named size.
Examples of JavaBean Standards

• public void setMyValue(int v)

• public int getMyValue()

• public boolean isMyStatus()


Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
} javac
To compile:
Simple.java
To execute: java Simple
Compilation Flow
Valid java main method signature

•public static void main(String[] args)


•public static void main(String []args)
•public static void main(String args[])
•public static void main(String... args)
•static public void main(String[] args)
•public static final void main(String[] args)
•final public static void main(String[] args)
Invalid java main method signature

• public void main(String[] args)


• static void main(String[] args)
• public void static main(String[] args)
• abstract public static void main(String[] args)
Can you save a java source file by other name than the
class name?

To compile: javac Simple.java


To execute: java Simple
Can you have multiple classes in a java source file ?
Java Variables
Java Variables

 Variable is a name of memory location.

 Is a combination of "vary + able" that means its value can be changed.

 There are three types of variables in java:

1. local variable

2. instance variable

3. static variable
1. Local Variable:
• Variable declared inside the body of the method.

• We can use this variable only within that method

• Cannot be defined with "static" keyword

2. Instance Variable
•Variable declared inside the class but outside the body of the method.

•It is not declared as static.

3. Static variable
• Variable which is declared as static is called static variable.
• It cannot be local
• Memory allocation for static variable happens only once when the class is
loaded in the memory
Example to understand the types of variables in java

class A
{
int data=50; //instance variable
static int m=100;
//static variable
void method()
{
int n=90; //local variable
}
}
Java Variable Example: Widening

class Simple{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a); OUTPUT:
System.out.println(f); 10
10.0
}}
Java Variable Example: Narrowing

class Simple {
public static void main(String[] args) {
float f=10.5f;
int a=f;
int a=(int)f;
OUTPUT:
System.out.println(f);
System.out.println(a); 10.5
10
}}
Data Types in Java
Integer

This group includes byte, short, int, long

byte :

• It is 1 byte(8-bits) integer data type.

• Value range from -128 to 127.

• Default value zero.

• example: byte b=10;

short :

• It is 2 bytes(16-bits) integer data type.

• Value range from -32768 to 32767.

• Default value zero.


int :
• It is 4 bytes(32-bits) integer data type.
• Value range from -2147483648 to 2147483647.
• Default value zero.
• example: int i=10;

long :
• It is 8 bytes(64-bits) integer data type.
• Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
• Default value zero. example:
• long l=100012;
// byte type
byte b = 20;
System.out.println("b= "+b);

// short type
short s = 20;
System.out.println("s= "+s);

// int type
int i = 20;
System.out.println("i= "+i);

// long type
long l = 20;
System.out.println("l= "+l);
Floating-Point Number
This group includes float, double

float :
• It is 4 bytes(32-bits) float data type.

• Default value 0.0f.

• example: float ff=10.3f;

double :
• It is 8 bytes(64-bits) float data type.
• Default value 0.0d.
• example: double db=11.123;
Characters

• Data types used to store characters are char.


• Uses unicode to represent characters.
• Unicode defines a fully international character set that can represent all of the
characters found in all human languages like, latin, greek, arabic, and many
more.
• This data type is a single 16-bit(2bytes) unicode character and its value-ranges
between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).
• The \u in your example is for Unicode, we can store unicode characters that
take up to 16 bits, from \u0000 to \uFFFF.
public class Demo {
public static void main(String[] args)
{
char ch = 'S';
System.out.println(ch);

char ch2 = '&';


System.out.println(ch2);

char ch3 = '$'; Output:


System.out.println(ch3);
S
&
} } $
Boolean

• Is used to store two possible values i.e. true or false.


• Default value is false.
• Basically used for simple flags that track true/false conditions.
public class Demo {

public static void main(String[] args) {

boolean t = true;

System.out.println(t);

boolean f = false;

System.out.println(f);

} }
Type casting in java
Type Casting in Java

• Process of converting the value of one data type (int, float, double, etc.)
Into another data type is known as type casting.
There are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger


type size
byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size


type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f); Output:
} Int value 100
Long value 100
Float value 100.0
}
Narrowing Casting

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


Output:
System.out.println("Long value "+l); Double value 100.04
Long value 100
System.out.println("Int value "+i); Int value 100
} }
Example 2:
byte b;
int i = 257;
double d = 323.142;

System.out.println("Conversion of int to byte.");

// i % 256
b = (byte)i;

System.out.println("i = " + i + " b = " + b);


System.out.println(

// d % 256
b = (byte)d;

System.out.println("d = " + d + " b= " + b);


Output

Conversion of int to byte.


i = 257 b = 1

Conversion of double to byte.


d = 323.142 b= 67
Java int to char

public class IntToCharExample1{


public static void main(String args[])
{
int a=65;
char c=(char)a;
System.out.println(a);
}}
Output:
A
Convert char to int

char a = '5';

char b = 'c';

// convert char variables to int // ASCII value of characters is assigned

int num1 = a;

int num2 = b;

System.out.println(num1); // 53

System.out.println(num2); // 99
char to int using getNumericValue() method

char a = '5';

char b = '9';

// convert char variables to int // Use getNumericValue()

int num1 = Character.getNumericValue(a);

int num2 = Character.getNumericValue(b);

System.out.println(num1); // 5

System.out.println(num2); // 9
char to int using parseInt() method

char a = '5';
char b = '9';
// Use parseInt()
int num1 = Integer.parseInt(String.valueOf(a));
int num2 = Integer.parseInt(String.valueOf(b));

System.out.println(num1); // 5
System.out.println(num2); // 9
Tokens
Tokens

• Token as the smallest individual element.


• For example, we cannot create a sentence without using words;
• Similarly, we cannot create a program without using tokens.
• Tokens is the building block or the basic component for creating a program.
Keywords in Java
keywords
• keyword is a reserved word.

• We cannot use it as a variable name, constant name, etc.


Identifiers
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:
The general rules for naming variables are:

• Names can contain letters, digits, underscores, and dollar signs


• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain whitespace
• Names can also begin with $ and _ (but we will not use it)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or boolean) cannot be used
as names
valid identifiers in Java:
• TestVariable

• testvariable

• a

• i

• Test_Variable

• _testvariable

• $testvariable

• sum_of_array

• TESTVARIABLE

• jtp123
Invalid identifiers

• Test Variable ( We can not include a space in an identifier)


• 123java ( The identifier should not begin with numbers)
• java+J2EE ( The plus (+) symbol cannot be used)
• a-java ( Hyphen symbol is not allowed)
• java_&_J2EE ( ampersand symbol is not allowed)
• Java’J2EE (we can not use an apostrophe symbol in an
identifier)
Difference Between Keyword and Identifier
Literals in java
What are Literals in Java?

• Have a constant value and a fixed data type and are often known as
constants in Java.
• Literals are assigned to a variable to provide a value to the variable.
• Example: int cost =340 ;
Types of Literals in Java
Integer Literals

• Integer literals are sequences of digits.


• 4 types of integer literals in Java:

1. binary (base 2)
2. decimal (base 10)
3. octal (base 8)
4. hexadecimal (base 16)
Decimal Integer:

• Integers having a base value of 10.


• Contains values between 0 to 9.
• Can be a positive value(+) or a negative value(-) but it cannot contain any
point in between them.
• Example: 1000, 1234, +78, -82, etc.
Octal Integer

• Integers having a base value of 8


• Contains values between 0 to 7.
• All octal numbers must start with a 0.
• Example: 012, 077,075, etc.

• int octal_int=077;
Hexadecimal Integer:

• Integers having a base value of 16.

• Containing values between 0 to 15.


• Contains both digits as well as characters.

• Digits range from 0 to 9 and the numbers 10 to 15 are replaced by characters a to


f.
• Any integer starting with 0x or 0X is considered to be a hexadecimal integer.
• Example: 0xff, 0x2a, 0xf1f2, etc.

• int hexadec_int=0x1ff2;
Binary Integer

• Integers with a base value of 2.


• Contains only two digits 0 and 1.
• Start with a 0b indicating that it is a binary digit.
• Example: 0b100101, 0b1010101, etc.

• int binary_int=0b1010101;
Example
int decimal_int=1234;
int octal_int=077;
int hexadec_int=0x1ff2;
int binary_int=0b1010101;
System.out.println("This is a Decimal Literal: "+decimal_int);
System.out.println("This is an Octal Literal: "+octal_int);
System.out.println("This is a Hexa Decimal Literal: "+hexadec_int);
System.out.println("This is a Binary Literal: "+binary_int);
Output

This is a Decimal Literal: 1234


This is an Octal Literal: 63
This is a Hexa Decimal Literal: 8178
This is a Binary Literal: 85
Floating Point Literal

• Floating-point literals are values that contain a decimal point in between


them.
• Floating-point literals are generally double data type by default.
• We can assign them to float data types by adding an f at the end of the
value.
• Example: float val_float=1.7732f;
Few points to remember while declaring floating-point literals are:

• If no suffix is present, the default data type is double.


• F or f suffix represents a floating data type.
• D or d suffix represents a double data type.
Few legal and illegal floating literals:

• 123.45 //Legal
• 122.32E5 //Legal
• 231.12F //Legal
• 1/4 // Illegal Symbol Used “/”
• 1.7.5 //Illegal, as two decimal points used.
• 1,234.56 // Illegal, as commas are not allowed
• 123.E4 //Illegal, as E cannot precede the point.
• 321E //Illegal, as the exponent part is incomplete.
Example

float val_float=1.7732f;

double val_double=1.7732d;

float val_exponent=123E4f;

System.out.println("This is a Floating Point Literal"+val_float);

System.out.println("This is a Decimal Literal"+val_double);

System.out.println("This is an Exponential Literal"+val_exponent);


Output

• This is a Floating Point Literal 1.7732

• This is a Decimal Literal 1.7732

• This is an Exponential Literal 1230000.0


Boolean Literal:

• Contains only two values true and false.


• Declared using the keyword boolean.
• It is a very useful literal to declare flag variables in different programs to
terminate a looping sequence.
Example

boolean flag1=true;

boolean flag2=false;

System.out.println("This is a boolean true flag variable "+flag1);

System.out.println("This is a boolean false flag variable "+flag2);


String Literal

• String is basically an array of characters.


• Anything written inside a double quote is a string “”.
• Example

String Company = “Atria”; //Valid String Literal


String Company = Atria; //Invalid as there is no double
quote.
Example

String company=“Atria”;
String null_Literal=null;
System.out.println("This is a String Literal: "+company);
System.out.println("This is a null Literal: "+null_Literal);

Output:
This is a String Literal: Atria
This is a null Literal: null
Character Literal

• Character Literals in java are represented with a single quote.


• Example: char ch = 'a';
Char literal as Integral literal:

• we can specify char literal as integral literal, which represents the Unicode

value of the character, and that integral literal can be specified either in

Decimal, Octal, and Hexadecimal forms.

• But the allowed range is 0 to 65535.

• char ch = 062;
Unicode Representation:

• We can specify char literals in Unicode representation ‘\uxxxx’.

• Here xxxx represents 4 hexadecimal numbers.

• char ch = '\u0061’; // Here /u0061 represent a.


• A single character (b, t, n, f, r)

• An octal number between 000 and 377

• A u followed by four hexadecimal digits specifying a Unicode character


Example

char ch = 'a';

// It is an Integer literal with octal form

char b = 0789;

// Unicode representation

char c = '\u0061';

System.out.println(ch);

System.out.println(b);

System.out.println(c);
Output

• a
• error:Integer number too large
• a
OPERATORS IN JAVA
Operators in java

Operator in java is a symbol that is used to perform operations


Java Operator
Operator Type Category Precedence
postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:

Assignment assignment = += -= *= /= %=
Java Unary Operator

class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++); 10
System.out.println(++x); 12
12
System.out.println(x--);
System.out.println(--x); 10

}}
SHIFT OPERATOR
Shift Operator

• Left Shift (<<)


• Right Shift (>>)
Left Shift Operator

• Left shift operator shifts all bits towards the left by a certain number of

specified bits.

• It is denoted by <<.
Java Left Shift Operator Example

class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}
Right Shift Operator

• Right shift operator shifts all bits towards the right by a certain number of
specified bits.
• It is denoted by >>.

• When we shift any number to the right, the least significant bits (rightmost) are
discarded and the most significant position (leftmost) is filled with the sign bit.
Java Right Shift Operator Example

class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}
Relation operators
Relation operators

• Used to test comparison between operands or values.


• Can be use to test whether two values are equal or not equal or less than or
greater than etc.
• Returns the Boolean results, i.e. true or false after the comparison
Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand


Example

int a, b;
a=40;
b=30;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
Bitwise operators
Bitwise operators

• Bitwise operators are used to perform operations bit by bit.


• Java defines several bitwise operators that can be applied to the integer types
long, int, short, char and byte.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise OR Operator

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
____________
00011101 = 29 (In Decimal)
Program 1

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 | number2;


System.out.println(result); // prints 29
}
}
Bitwise AND Operator

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

// Bitwise AND Operation of 12 and 25


00001100
& 00011001
____________
00001000 = 8 (In Decimal)
Program

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise AND between 12 and 25


result = number1 & number2;
System.out.println(result); // prints 8
}
}
Bitwise XOR Operator

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

// Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
____________
00010101 = 21 (In Decimal)
Program

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise XOR between 12 and 25


result = number1 ^ number2;
System.out.println(result); // prints 21
}
}
Bitwise Complement Operator

• Bitwise complement operator is a unary operator (works with only one


operand).
• It is denoted by ~.
• It changes binary digits 1 to 0 and 0 to 1.
• 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.
Program

class Main {
public static void main(String[] args) {

int number = 35, result;

// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Logical Operators
Logical operators

• Logical operators are used to check whether an expression is true or false.


• They are used in decision making.
Operator Example Meaning

&& (Logical expression1 && true only if both expression1


AND) expression2 and expression2 are true

expression1 || true if either expression1 or


|| (Logical OR)
expression2 expression2 is true

true if expression is false and


! (Logical NOT) !expression
vice versa
class Main {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Ternary Operator

•The ternary operator (conditional operator) is shorthand for the if-then-


else statement.
variable = Expression ? expression1 : expression2

• If the Expression is true, expression1 is assigned to the variable.


• If the Expression is false, expression2 is assigned to the variable.
Example

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result);

You might also like