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

Java Set1

Uploaded by

Jiju Abutelin Ja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Set1

Uploaded by

Jiju Abutelin Ja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 119

Java

Java - Introduction part1


FROM
Genesis coding School

Genesis Coding School An initiative by IT Professionalss


Java

Table of Contents

Java Introduction

............................................................................................................................................................................ 5
Introduction to Java....................................................................................................................................5
JDK,JRE and JVM in Java.................................................................................................................................9
Java Execution Environment......................................................................................................................9
JVM...........................................................................................................................................................10
JRE.............................................................................................................................................................11
JDK............................................................................................................................................................12
JDK vs JRE vs JVM......................................................................................................................................13
Java Installation In Windows........................................................................................................................14
Install Java in Windows............................................................................................................................14
Java Hello World*.........................................................................................................................................26
My First Java Program..............................................................................................................................27
Step1:Creating the program.....................................................................................................................29
Step2:Compiling the program..................................................................................................................31
Step3:Executing the program...................................................................................................................33
Common Errors & Solutions.....................................................................................................................34
Java Hello World - Explained*......................................................................................................................36
My First Java Programme.........................................................................................................................36
Number systems.......................................................................................................................................39
Decimal Number System..........................................................................................................................40
Binary number system..............................................................................................................................41
Importance of binary numbers in computers..........................................................................................43
..................................................................................................................................................................43
Octal Numbering System..........................................................................................................................43
Hexadecimal Number System..................................................................................................................44

1
Genesis Coding School An initiative by IT Professionals
Java

Conversion of Number System.................................................................................................................46


Understanding Variables*

......................................................................................................................................................................46
Introduction to Java Variables..................................................................................................................47
Java Variables...............................................................................................................................................53
Variables...................................................................................................................................................53
Types of variables.....................................................................................................................................55
Literals in Java...........................................................................................................................................56
Q: Literal can be of which of these data types? a) integer b) float c) boolean d) all of the mentioned.....58
Java Data Types............................................................................................................................................58
Data Types................................................................................................................................................58
Primitive data types......................................................................................................................................60
Primitive data types..................................................................................................................................61
Non-primitive data types..............................................................................................................................67
Non-primitive data types..........................................................................................................................67
Java User Input and Output..........................................................................................................................70
Java Output...............................................................................................................................................71
Java Input..................................................................................................................................................73
Java Packages and API..................................................................................................................................76
Packages and API in Java..........................................................................................................................77
Types of packages in Java.........................................................................................................................78
Built-in Packages.......................................................................................................................................78
User Defined Packages.............................................................................................................................80
Java Comments.............................................................................................................................................83
Comments.................................................................................................................................................83
Single – line comments.............................................................................................................................85
Multi – line comments..............................................................................................................................85
Documentation comments.......................................................................................................................86
Java Operators..............................................................................................................................................87

2
Genesis Coding School An initiative by IT Professionals
Java

Operators Operators are special symbols (characters) that carry out operations on operands
(variables and values). There are many types of operators in Java which are given below:..................87
Java Operators 1...........................................................................................................................................89
Arithmetic Operators................................................................................................................................90
Unary Operator.........................................................................................................................................91
Shift Operator...........................................................................................................................................92
Java Operators 2...........................................................................................................................................94
Logical Operators......................................................................................................................................94
Bitwise Operators.....................................................................................................................................95
Relational Operator..................................................................................................................................97
Assignment Operators..............................................................................................................................97
Java Arrays....................................................................................................................................................99
Arrays......................................................................................................................................................100
Single-dimension Array..............................................................................................................................101
Single-dimension Array..........................................................................................................................102
Multi-dimension Array...............................................................................................................................106
Multi-dimension Array...........................................................................................................................107
Type Casting in Java....................................................................................................................................112
Type Casting in Java................................................................................................................................113
Widening Type Casting...........................................................................................................................114
................................................................................................................................................................114
Narrowing Type Casting..........................................................................................................................115
Type promotion While evaluating expressions, the intermediate value may exceed the range of
operands and hence the expression value will be promoted. Some conditions for type promotion are:
................................................................................................................................................................117
Type Casting : More Examples................................................................................................................118

3
Genesis Coding School An initiative by IT Professionals
Java

Java Introduction

 Introduction to Java

Introduction to Java

Java is a high-level programming language originally developed by James Gosling at Sun


Microsystems in 1995, Now java is owned by Oracle Corporation.Java Programming Language is
a platform independent language, which means it is not tied to any particular hardware or
operating system. The idea is to write once, run anywhere which means that compiled Java code
can run on all platforms that support Java without the need for recompilation.Java language is
supported by almost every operating system such as Sun Solaris, RedHat, Windows, Linux
etc.. The latest version of Java is Java 20 or JDK 20 released on March, 21st 2023. The other
features of java are :

4
Genesis Coding School An initiative by IT Professionals
Java

 Object Oriented - Everything in java is an Object.which makes it a true object-oriented


language. All program code and data reside within objects and classes.

5
Genesis Coding School An initiative by IT Professionals
Java

 Platform Independent - when Java program is compiled, it is not compiled into platform
independent byte code. This byte code is interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.

 Secure - In Java, you cannot access out-of-bound arrays, and you don't have pointers, and
thus several security flaws like stack corruption or buffer overflow is impossible to exploit
in Java.
 Simple - Any with basic concepts of oops can easily learn java
 Architecture-neutral - When java code is compiled it generates an architecture-neutral
object file format, which makes the compiled code executable on many processors, with
the presence of Java runtime system.

6
Genesis Coding School An initiative by IT Professionals
Java

 Portable - Translating a Java program into bytecode makes it much easier to run a program
in a wide variety of environments because only the JVM needs to be implemented for each
platform.
 Robust - Java makes an effort to eliminate error situations through compile time error
checking and runtime checking.
 Multithreaded - It is possible to write programs that can perform many number of tasks
simultaneously.
 High Performance - Java programming performance is very impressive considering the fact
that is an interpreted language, mainly because of the bytecodes. Java architecture is
designed to reduce overheads.
 Distributed - Java programming provides sharing of data and programs. Java applications
can open and access remote objects on Internet.
 Dynamic - Java is a dynamic language, it is capable of dynamically linking in new class
libraries, methods, and objects.

7
Genesis Coding School An initiative by IT Professionals
Java

JDK,JRE and JVM in Java

 Java Execution Environment


 JVM
 JRE
 JDK
 JDK vs JRE vs JVM

Java Execution Environment

Java is a high level programming language. A program written in high level language cannot be run
on any machine directly. First, it needs to be translated into that particular machine language. The
javac compiler does this thing, it takes java program (.java file containing source code) and
translates it into machine code (referred as byte code or .class file).

8
Genesis Coding School An initiative by IT Professionals
Java

JDK is a software development kit whereas JRE is a software bundle that allows Java program to
run, whereas JVM is an environment for executing bytecode. The full form of JDK is Java
Development Kit, while the full form of JRE is Java Runtime Environment, and the full form of JVM
is Java Virtual Machine.

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode
can be executed.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code (using JIT)
o Provides runtime environment

When you run the Java program, Java compiler first compiles your Java code to bytecode. Then,
the JVM translates bytecode into native machine code (set of instructions that a computer's CPU
executes directly).

So, When we write a Java code, it's ultimately written for JVM, not for the physical machine
(computer). JVM is the reason why Java is platform-independent(Since JVM ?executes the Java
bytecode).

9
Genesis Coding School An initiative by IT Professionals
Java

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used
to provide the runtime environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.

JRE is a piece of a software which is designed to run other software. It contains the class libraries,
loader class, and JVM. In simple terms, if you want to run Java program you need JRE. If you are
not a programmer, you don't need to install JDK, but just JRE to run Java programs. Though, all
JDK versions comes bundled with Java Runtime Environment, so you do not need to download
and install the JRE separately in your PC. The full form of JRE is Java Runtime Environment.

10
Genesis Coding School An initiative by IT Professionals
Java

JDK

Java Development Kit is the core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program. JDK is a
platform-specific software and that’s why we have separate installers for Windows, Mac, and Unix
systems. We can say that JDK is the superset of JRE since it contains JRE with Java compiler,
debugger, and core classes. The current version of JDK is 14 also known as Java 14.

11
Genesis Coding School An initiative by IT Professionals
Java

JDK vs JRE vs JVM

12
Genesis Coding School An initiative by IT Professionals
Java

Exercise

Q: Which component is used to compile, debug and execute java program?


a) JVM
b) JDK
c) JIT
d) JRE

Java Installation In Windows

 Install Java in Windows

Install Java in Windows

To install java into your system, visit Oracle JDK download page and click JDK Download link

13
Genesis Coding School An initiative by IT Professionals
Java

Select the 64 bit installer from the list of downloads

14
Genesis Coding School An initiative by IT Professionals
Java

Accept the licenses by ticking the checkbox and click the download button.

After download open the installer and click next.

In this window select the directory in which you want to install Java. We prefer to select the
default installation directory. After selecting the directory click next.

15
Genesis Coding School An initiative by IT Professionals
Java

Check if the installation was successful and close the installer after successful installation of Java.

16
Genesis Coding School An initiative by IT Professionals
Java

So now Java is installed into our pc. Let's check if it works or not. To check if Java is able to run in
our computer, open command prompt and type java -version

java -version

17
Genesis Coding School An initiative by IT Professionals
Java

Since java is not recognized as a operable program we need to change the class path in order to
make java operable.

To set Java classpath open your pc's properties by right clicking my pc >> properties

18
Genesis Coding School An initiative by IT Professionals
Java

then >> Advanced system settings

19
Genesis Coding School An initiative by IT Professionals
Java

From the System properties window select Environment Variables

Then a new tab Environment Variables will be opened, it have a User variable for
name_of_current_user and System variables. If you only want to set class path for the currently
running user then we only need to set classpath for User variable for name_of_current_user. If
you want to set classpath for all users in the machine then you need System variables. Here we
are setting classpath for a particular user with username acer. Double click the path inside User
variable for name_of_current_user.

20
Genesis Coding School An initiative by IT Professionals
Java

Click new to create/add our class path to the use variable.

21
Genesis Coding School An initiative by IT Professionals
Java

Now goto the directory that you've installed JDK and copy the path upto bin.

22
Genesis Coding School An initiative by IT Professionals
Java

Paste the copied file directory into the new field and click ok. Now the classpath is added as a user
variable. Which means Java is now operable in our system.

23
Genesis Coding School An initiative by IT Professionals
Java

We can verify the Java installation by running the version check command again.
COPY

24
Genesis Coding School An initiative by IT Professionals
Java

java -version

Java Hello World*

 My First Java Program


 Creating the program
 Compiling the program
 Executing the program
25
Genesis Coding School An initiative by IT Professionals
Java

 Common Errors & Solutions

My First Java Program

The process of Java programming can be simplified in three steps:

 Creating the program


 Compiling the program
 Executing the program

26
Genesis Coding School An initiative by IT Professionals
Java

Java File Execution -

steps
Let me explain in detail about these steps.

27
Genesis Coding School An initiative by IT Professionals
Java

Step1:Creating the program

your first java program


Creating the program is very easy. All you need to do is
1. Open your notepad and create a file called HelloWorld.java
2. Copy paste the following code

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

And your program is ready.


It is OKAY if you do not understand the meaning of the above code.
For now, just understand that this code will print "Hello world" as the output when it is executed.

Also, it is not mandatory to create the code in Notepad.

28
Genesis Coding School An initiative by IT Professionals
Java

You could also use other text editors such as Sublime, Atom, VS Code etc. Any text editor is
enough to create the Java Program. See the following images:-

Ja
va program created in Sublime Text Editor

Ja
va program created in Eclipse editor

29
Genesis Coding School An initiative by IT Professionals
Java

All of these editors are good and are okay.


As long as the code you created is correct, it will work fine.
For beginners, I personally prefer Sublime Text/VSCode. It is fast and easy to work with.
But as you start creating large applications, you will need to move to Eclipse and Netbeans and
similar larger editors.

Step2:Compiling the program

To compile the program,


1. Open the command prompt and go to the directory where you have saved the
file HelloWorld.java
2. Type the following command

javac HelloWorld.java

This will compile the java file and create a new class file called HelloWorld.class
Output:-
HelloWorld.class will be created

Note: If there are any errors in the file that you have created, the file will NOT compile.
Errors could be anything such as

 spelling mistakes
 missed semicolon
30
Genesis Coding School An initiative by IT Professionals
Java

 missed brackets etc..

Behind the Scenes


Now let's try to understand what happens when we try to compile this java file.

You all know that, we write Java in plain English. This is called as High Level Language. ( java, c, c+
+, python, php etc..) are all examples of such high level languages. While compiling, this gets
converted (encoded) into an intermediate format called the ByteCode. This process is called
as compiling and the software that does this is called as a compiler

The advantage of ByteCode is that, this makes the code capable of being run in any machine
where Java in installed. This no longer depends on the operating system or machine.

So when we install java jdk, we are actually installing a java compiler also along with it which can
be accessed by the javac command.

Test Your Understanding:


You created a java file and tried to compile it with the javac command.
However, you get the following error. Why is it so?

javac is not a recognised command

Ans:This happens mostly because the system is unable to find the javac command. That could
mean that the java JDK has not been installed properly. So the solution is to reinstall java JDK.

31
Genesis Coding School An initiative by IT Professionals
Java

Step3:Executing the program

This is the step where the program is actually run to get the output.

To do it,

 open the terminal


 Go to the file location
 Run the following command

java MyFirstProgram

and it will show the following output.


Output:-

Hello World!

Behind the Scenes


So what happens in the background when we run the command?
In simple terms, the bytecode that was created earlier gets converted to machine code which
then, gets executed to show the output.

Let me explain it a bit more detail.

The class file (ByteCode) that was created in the earlier step ( compilation ) is NOT dependent on
32
Genesis Coding School An initiative by IT Professionals
Java

any operating system or machine. This means that we can execute this class file in ANY machine
that we like where Java has been installed ( ie. JRE and JDK has been installed )

When we try to run this code this class file is given to the JVM ( java virtual machine ) and three
things happen:-
1. The main class file is loaded into the system memory. This is done by ClassLoader
2. The bytecode is verified in detail to check for errors. This is called as ByteCode Verifier
3. The Just-in-time (JIT) compiler will run the code by converting this loaded ByteCode into
Machine code which the machine can understand. This is called as Just in Time Compilation. This
JIT compiler will then run this machine code to show the output to the user.

Common Errors & Solutions

The following are some of the common errors that you will come across trying to run this code

Error #1
Output:-
one.java:4: error: ';' expected
System.out.println("Hello World!")
^
1 error

Solution: This error is self explanatory. It says one.java:4: error: ';' expected
It means, The error happened in one.java file in Line number 4.
Java compiler is expecting a semicolon ; but is unable to find it.

33
Genesis Coding School An initiative by IT Professionals
Java

So just provide that semi colon and the compile again and the error will be fixed.

Error #2

Output:-
one.java:4: error: unclosed string literal
System.out.println("Hello World!);
^
1 error

Solution: This error is also self explanatory. It says one.java:4: error: unclosed string literal
It means, The error happened in one.java file in Line number 4.
Java compiler finds some unclosed stuff. Remember that single/double quotes almost always
comes in pairs ( even number of them ). In our case, here there is only one double quote when
java compiler is expecting two of them. So you have somehow forgot to write the second double
quote.
So just provide that double quote and the compile again and the error will be fixed. We will learn
more on these double quotes in coming chapters.

Error #3

Output:-
one.java:5: error: reached end of file while parsing
}
^
1 error

34
Genesis Coding School An initiative by IT Professionals
Java

Solution: This error is a bit different. It says one.java:5: error: reached end of file while parsing
It means, The error happened in one.java file in Line number 5.
Java compiler has reached the end of the file when it feels that it should NOT have. So chance is
that a bracket is missing. We will learn on how to decide where to start and end brackets in
coming chapters. Dont wory about it.
So just provide that missing bracket and the compile again and the error will be fixed.

Java Hello World - Explained*

 My First Java Programme

My First Java Programme

35
Genesis Coding School An initiative by IT Professionals
Java

The process of Java programming can be simplified in three steps:

 Create the program by typing it into a text editor and saving it to a file : (file_name.java)
 Compile it by typing “javac file_name.java” in the terminal window
 Execute (or run) it by typing “java file_name” in the terminal window

Hello World Programme

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output :
Hello, World!

Explanation :
1. class HelloWorld { ... }

In Java, every application begins with a class definition. In the program, HelloWorld is the name of
the class, and the class definition is:

class HelloWorld {
... .. ... }

36
Genesis Coding School An initiative by IT Professionals
Java

For now, just remember that every Java application has a class definition, and the name of the
class should match the filename in Java.

2. public static void main(String[] args) { ... }

This is the main method. Every application in Java must contain the main method. The Java
compiler starts executing the code from the main method.

For now, just remember that the main function is the entry point of your Java application, and it's
mandatory in a Java program. The signature of the main method in Java is:

public static void main(String[] args) {


... .. ...
}

3. System.out.println("Hello, World!");

The following code prints the string inside quotation marks Hello, World! to standard output (your
screen). Notice, this statement is inside the main function, which is inside the class definition.

Just copy paste the Hello World programme and try to run it before you get into the world
of JAVA Programming.

Number systems

37
Genesis Coding School An initiative by IT Professionals
Java

 Number systems
 Decimal Number System
 Binary number system
 Octal Numbering System
 Hexadecimal Number System
 Conversion of Number System

Number systems

A number is a mathematical object used to count, label and measure. A number system is a
systematic way to represent numbers. The number system we use in our day to day life is the
decimal number system that uses 10 symbols or digits. The number 289 is pronounced as two
hundred and eighty nine and it consists of the symbols 2, 8 and 9. Similarly there are other
number systems. Each has its own symbols and method for constructing a number. A number
system has a unique base, which depends upon the number of symbols. The number of symbols
used in a number system is called base or radix of a number system.

38
Genesis Coding School An initiative by IT Professionals
Java

Let us discuss some of the number systems.

Decimal Number System

The decimal number system involves ten symbols 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 to form a number.
Since there are ten symbols in this number system, its base is 10. Therefore, the decimal number
system is also known as base-10 number system.

Consider two decimal numbers 654 and 456


654 : six hundred + five tens+ four ones (6x10 2 + 5x101+ 4x100)
456 : four hundreds + five tens + six ones (4x10 2 + 5 x101+ 6x100)

Let's see another example 2179


Weight 103 102 101 100

Decimal Number 2 1 7 9

In the above example, the digit 2 has the maximum place value, 10 3=1000 and 9 has the minimum
place value, 100=1. The digit with most weight is called Most Significant Digit(MSD) and the digit
with least weight is called Least Significant Digit (LSD). So in the above number MSD is 3 and LSD is
0.
So far we have discussed a number system which uses 10 symbols. Now let us see the
construction of other number systems with different bases.

Binary number system

As you know Computers, mobile phones etc. are electronic products. Number systems are
39
Genesis Coding School An initiative by IT Professionals
Java

essential in softwares.

But the problem is these products cannot implement base 10 number system. They only have two
voltage levels either 1(on) or 2(off), So base 2 is the only implementation that can be done.

In mathematics and digital electronics, a binary number is a number expressed in the base-2
numeral system or binary numeral system, which uses only two symbols: typically "0" (zero) and
"1" (one). The base-2 numeral system is a positional notation with a radix of 2. Each digit is
referred to as a bit.

eg: (1101)2, (101010)2, (1101.11)2


Each digit of a binary number is called bit. A bit stands for binary digit.

The binary number system is also a positional number system just like the Decimal Number
System, where place value of each binary digit is power of 2. Consider an example (1101),. his
binary number can be written in expanded form as shown below:
Weight 23 22 21 20
Decimal Number 1 1 0 1
MSB LSB

(1101)2 = 1x23 + 1x 22 + 0x21 + 1x20


= 1x8+ 1x4 + 0x2 + 1x1
= 8+4+0+1
= 13

40
Genesis Coding School An initiative by IT Professionals
Java

Consider another example : (111.011) 2


Weight 22 21 20 2-1 2-2 2-3
Decimal Number 1 1 1 0 1 1
MSB LSB

(111.011)2 = 1x22 + 1x 21 + 1x20 + 0x2-1+ 1x2-2+ 1x2-3


= 1x4 + 1x2 + 1x1 + 0x½ + 1x¼ + 1x⅛
= 4 + 2 + 1 + 0 + 0.25 + 0.125
= 7.375

41
Genesis Coding School An initiative by IT Professionals
Java

Importance of binary numbers in computers

We have seen that binary number system is based on two digits 1 and 0. The electric state ON can
be represented by 1 and the off state by 0. Because of this, computer uses binary number system
as the basic number system for data representation.

Octal Numbering System

The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to
7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into
groups of three (starting from the right). For example, the binary representation for decimal 74 is
1001010. It is commonly used as a shorter representation of binary numbers by grouping binary
digits into threes. The chmod command in Linux or UNIX uses octal to assign file permissions.

42
Genesis Coding School An initiative by IT Professionals
Java

Base of this number system is 8 and hence it is also called base-8 number system. Consider an
example (236)8. Weight of each digit is power of 8 (8", 8', 8°, 8°, ...). The number (236), can be
written in expanded form as :
Weight 82 81 80

Octal Number 2 3 6

(236)8 = 2x82 + 3x 81 + 6x80


= 2x64 + 3x8 + 6x1
= 128+ 24+6
= 158

Hexadecimal Number System

In mathematics and computing, hexadecimal (also base 16, or hex) is a positional system that
represents numbers using a base of 16. ... For example, a single byte can have values ranging from
00000000 to 11111111 in binary form, which can be conveniently represented as 00 to FF in
hexadecimal.

In this system, the symbols A, B, C, D, E and F are used to represent the decimal
numbers 10, 11, 12, 13, 14 and 15 respectively. The hexadecimal digit and their equivalent
decimal numbers are shown below.

Hexa Decimal 0 1 2 3 4 5 6 7 8 9 10 A B C D E F
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
43
Genesis Coding School An initiative by IT Professionals
Java

Let's Consider an example : (12AF) 16


Weight 163 162 161 160
Decimal Number 1 2 A F
MSB LSB

(12AF)16 = 1x163+ 2x162 + 10x161+ 15x160


= 1x4096 + 2x256 + 10x16 + 15x1
= 4096 + 512+ 160+ 15
= 4783

44
Genesis Coding School An initiative by IT Professionals
Java

Conversion of Number System

It is good to know the number system conversions, Take a look at the videos provided below to
know more about conversion between number systems.

Decimal to Binary

This video will explain you how Decimal is converted into Binary.

Binary to Decimal

This video will explain you how Binary is converted into Decimal.

Understanding Variables*

 Introduction to Java Variables

45
Genesis Coding School An initiative by IT Professionals
Java

Introduction to Java Variables

Imagine you have a page and you need to print the value '5' in that page. What would you do?
You would write some code to print it. Isn't it?
Yes!

Now imagine, what if you need to print the value '5' ten times in different parts of that particular
page?
You would write the same code that you wrote earlier, 10 times

I hope that is also clear for you.


Okay. so far so good.

Now, what if, you decide that, you needn't print '5'. Instead you need to print the value '7'
instead.
You will start changing the value of '5' to '7' in ALL the above 10 places within the page.

46
Genesis Coding School An initiative by IT Professionals
Java

And what if there were not just 10 places, but 100 places to change the value? or maybe a 1000
places?
It would become extremely difficult to do the job!

So what if, we could reduce this effort.

What if you have to change the value from 5 to 7 in only one place and it will get automatically
reflected in all those 10 places ( or 100 places or 1000 places as the case maybe). That would be
great. Isn't it?

This is basic concept of variable.

The basic idea is to store this value '5' somewhere and use that instead of writing the value '5'
directly.

Confused?

47
Genesis Coding School An initiative by IT Professionals
Java

Let me explain a bit more in detail.

First of all, you need to understand that writing

System.out.println("Benz")

will output Benz


And writing

System.out.println("Hello World!")

will output "Hello World!"


And

System.out.println("5")

will output "5"

So let's consider two scenarios:-


Scenario #1 - Without using Variable. You hardcode the value everywhere
Scenario #2 - Using Variable. Here there's no hardcoding of value.

Scenario #1

In this first scenario, we will be writing this 10 times likes this in different parts of the page.
Writing this value directly is called as Hardcoding the value. Note that we are NOT using any
variable here.

System.out.println("5")
System.out.println("5")

48
Genesis Coding School An initiative by IT Professionals
Java

System.out.println("5")
System.out.println("5")
System.out.println("5")
System.out.println("5")
System.out.println("5")
System.out.println("5")
System.out.println("5")

And when we want to change the value to 7, what will we do?


We will MANUALLY change it in ALL the 10 places so that it would look like this

System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")
System.out.println("7")

Scenario #2

We store the value of '5' somewhere and we use it.

49
Genesis Coding School An initiative by IT Professionals
Java

int myNumber = '5';


System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);

Here, the output is the same. But, we are not hard coding the value directly.
Instead, we save the value to a word and we print that word instead.
This word is called as variable. So now that variable will have the value '5' in it.

The advantage in this second scenario is that, to change the value from '5' to '7' we need to
change it in JUST ONE PLACE.

See this:-

int myNumber = '7';


System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);

50
Genesis Coding School An initiative by IT Professionals
Java

System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);
System.out.println(myNumber);

So basically, variables are containers for storing values ( words to store values )
And these values can be words, alphabets, numbers, decimals etc..

words are called as strings


numbers are called as int
decimals are called as float or double

The main thing about these variables is that, while creating the variable we need to tell whether it
will store number or words or decimals.

Accordingly these variables can be of different types such as:-

51
Genesis Coding School An initiative by IT Professionals
Java

1. int
2. float
3. strings

We will study more on this in the coming chapters.

Java Variables

 Variables
 Types of variables
 Literals in Java

Variables

What is a variable?

52
Genesis Coding School An initiative by IT Professionals
Java

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. The Variable simply is a name of memory location. It is the basic unit of
storage in a program. There are three types of variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive. We will discuss Data
types in the next chapter.

Important properties of JAVA :

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before use.

We can declare variables in java as follows:

53
Genesis Coding School An initiative by IT Professionals
Java

 type: Type of data that can be stored in this variable


 name: Name given to the variable.

Types of variables

Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
A local variable cannot be defined with "static" keyword.

54
Genesis Coding School An initiative by IT Professionals
Java

Instance Variable

A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static. It is called instance variable because its value is instance
specific and is not shared among instances.

Static variable

A variable which is declared as static is called static 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.

Example:

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

Literals in Java

A literal is a fixed value that we assign to a variable in a Program.


55
Genesis Coding School An initiative by IT Professionals
Java

int num=10;//Here value 10 is a Integer literal.

char ch = 'A';//Here A is a char literal

Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.

byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;

Float Literals
Used for data type float and double.

double num1 = 22.4;


float num2 = 22.4f;

Note: Always suffix float value with the “f” else compiler will consider it as double.

Char and String Literal


Used for char and String type.

char ch = 'Z';
String str = “GenesisAcademy";

56
Genesis Coding School An initiative by IT Professionals
Java

Exercise

Q: Literal can be of which of these data types?


a) integer
b) float
c) boolean
d) all of the mentioned

Java Data Types

 Data Types

Data Types

57
Genesis Coding School An initiative by IT Professionals
Java

Data type defines the values that a variable can take, for example if a variable
has int(integer) data type, it can only take integer values. In java we have two categories of data
type:

1. Primitive data types


2. Non-primitive data types

Java is a statically typed language. A language is statically typed, if the data type of a variable is
known at compile time. This means that you must specify the type of the variable (Declare the
variable) before you can use it. So in most of the cases the first step of writing a code will be
started with declaration of a variable with a specific Datatype.

58
Genesis Coding School An initiative by IT Professionals
Java

For example, if we want to store or print a variable num in our program, we must declare it first
as shown below:

int num;

It is a good programming practice to declare all the variables ( that you are going to use) in the
beginning of the program.
We will be studying more about data types in the coming chapters.......

Exercise

Q: Which of these coding types is used for data type characters in Java?
a) ASCII
b) ISO-LATIN-1
c) UNICODE
d) None of the mentioned

Primitive data types

 Primitive data types

59
Genesis Coding School An initiative by IT Professionals
Java

Primitive data types

In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double.
Java developers included these data types to maintain the portability of java as the size of these
primitive data types do not change from one operating system to another.

 byte, short, int and long data types are used for storing whole numbers.
 float and double are used for fractional numbers.
 char is used for storing characters(letters).
 boolean data type is used for variables that holds either true or false.

60
Genesis Coding School An initiative by IT Professionals
Java

byte:

This can hold whole number between -128 and 127. Mostly used to save memory and when you
are certain that the numbers would be in the limit specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:

class JavaDataType {
public static void main(String[] args)
{
byte num;
num = 113;
System.out.println(num);
}
}

Output: 113

short:

This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767.
Default size of this data type: 2 byte
Example:

short num = 15678;

61
Genesis Coding School An initiative by IT Professionals
Java

int:

Used when short is not large enough to hold the number, it has a wider range: -2,147,483,648 to
2,147,483,647
Default size: 4 byte
Default value: 0
Example:

class JavaExample {
public static void main(String[] args)
{
int num;
num = 150;
System.out.println(num);
}
}

Output:150

long:

Used when int is not large enough to hold the value, it has wider range than int data type, ranging
from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:

62
Genesis Coding School An initiative by IT Professionals
Java

class JavaExample {
public static void main(String[] args)
{
long num = -12332252626L;
System.out.println(num);
}
}

Output:-12332252626

double:

Sufficient for holding 15 decimal digits


size: 8 bytes
Example:

class JavaExample {
public static void main(String[] args)
{
double num = -42937737.9d;
System.out.println(num);
}
}

Output:-4.29377379E7

63
Genesis Coding School An initiative by IT Professionals
Java

float:

Sufficient for holding 6 to 7 decimal digits


size: 4 bytes
Example:

class JavaExample {
public static void main(String[] args)
{
float num = 19.98f;
System.out.println(num);
}
}

Output:19.98

Boolean:

holds either true of false.


Example:

class JavaExample {
public static void main(String[] args)
{
boolean b = false;
System.out.println(b);
}
}
64
Genesis Coding School An initiative by IT Professionals
Java

Output:false

char:

holds characters.
size: 2 bytes
Example:

class JavaExample {
public static void main(String[] args) {
char ch = 'Z';
System.out.println(ch);
}
}

Output: Z

Exercise

Q: How many Primitive data types are there in Java?


a) 6
b) 7
c) 8
d) 9

65
Genesis Coding School An initiative by IT Professionals
Java

Q: Which of the following are legal lines of Java code?


1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;
a) 1 and 2
b) 2 and 3
c) 3 and 4
d) All statements are correct

Non-primitive data types

 Non-primitive data types

Non-primitive data types

The Non-primitive data types will contain a memory address of variable value because the
reference types won’t store the variable value directly in memory. They are strings, objects,
arrays, etc.
Just go through these in brief, we will be discussing Non-primitive data types in detail after a
while.

66
Genesis Coding School An initiative by IT Professionals
Java

String:

Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a special character ‘\0’.

Class:

A class is a user-defined blueprint or prototype from which objects are created. It represents the

67
Genesis Coding School An initiative by IT Professionals
Java

set of properties or methods that are common to all objects of one type.

Object:

It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical
Java program creates many objects.

Interface:

Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).

Array:

An array is a group of like-typed variables that are referred to by a common name.Arrays in Java
work differently than they do in C/C++.

Exercise

Q: Which of the following is a Non-primitive data type ?


a) short
b) String

68
Genesis Coding School An initiative by IT Professionals
Java

c) int
d) byte

Java User Input and Output

 Java Output
 Java Input

Java Output

In Java, you can simply use these to send output to standard output (screen).

69
Genesis Coding School An initiative by IT Professionals
Java

System.out.println(); or
System.out.print(); or
System.out.printf();

Here,
System is a class
out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class, public, and static in later chapters.

Difference between println(), print() and printf()

 print() - It prints string inside the quotes.


 println() - It prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
 printf() - It provides string formatting

Example : print() and println()

class GenesisExample {
public static void main(String[] args) {
System.out.println("1. This is println ");
System.out.println("2. This is println ");
System.out.print("1. This is print ");
System.out.print("2. This is print");
}
}
70
Genesis Coding School An initiative by IT Professionals
Java

Output :
1. This is println
2. This is println
1. This is print 2. This is print

Example : Printing Variables and Literals

class GenesisExample {
public static void main(String[] args) {
int number = 10;
System.out.println(5);
System.out.print(number);
}
}

output :
5
10

Example : Print Concatenated Strings

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

71
Genesis Coding School An initiative by IT Professionals
Java

Double number = -4.2;

System.out.println("Java from " + "Genesis.");


System.out.println("Number = " + number);
}
}

Output :
Java from Genesis.
Number = -4.2
We can use the + operator to concatenate (join) the two strings: "Java from" and "Genesis.".

Java Input

Java Scanner class allows the user to take input from the console and it is found in
the java.util package.. It belongs to java.util package. It is used to read the input of primitive types
like int, double, long, short, float, and byte. It is the easiest way to read input in Java program.
To use the Scanner class, create an object of the class and use any of the available methods found
in the Scanner class documentation such as nextLine(),nextInt() etc.

In order to use the object of Scanner, we need to import java.util.Scanner package.

import java.util.Scanner;

Then, we have to create an object of the Scanner class so that we can use the object to take input

72
Genesis Coding School An initiative by IT Professionals
Java

from the user.

Scanner input = new Scanner(System.in); // create an object of Scanner


int number = input.nextInt(); // take input from the user

Example : Integer Input From the User

import java.util.Scanner;

class GenesisExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt(); //reading an integer from user
System.out.println("You entered " + number);

// closing the scanner object


input.close();
}
}

Output :
Enter an integer: 23
You entered 23

In the above example,

73
Genesis Coding School An initiative by IT Professionals
Java

 First we have created an object named input of the Scanner class.


 We then call the nextInt() method of the Scanner class to get an integer input from the
user.

Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next() methods to


get long, float, double, and string input respectively from the user.
We have used the close() method to close the object. It is recommended to close
the scanner object once the input is taken.

Exercise

Q: Which of these packages are used for input operation?


a) import java.util.Scanner;
b) import system.util.Scanner;
c) import java.util.Input;
d) import java.utility.Scanner;

Q: What will be the output of following program ?

public class GenesisExample {


public static void main(String args[]){
System.out.print('A' + 'B');
}
}
74
Genesis Coding School An initiative by IT Professionals
Java

a) AB
b) 195
c) 131
d) Error

Java Packages and API

 Packages and API in Java


 Types of packages in Java
 Built-in Packages
 User Defined Packages

Packages and API in Java

A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java

75
Genesis Coding School An initiative by IT Professionals
Java

we use packages to organize our classes and interfaces. We have two types of packages in Java:
built-in packages and the packages we can create (also known as user defined package). In this
guide we will learn what are packages, what are user-defined packages in java and how to use
them.

In java we have several built-in packages, for example when we need user input, we import a
package like this :

import java.util.Scanner

java is a top level package


util is a sub package
Scanner is a class which is present in the sub package util.

Advantages of using a package in Java

 Reusability
 Better Organization
 Name Conflicts

Types of packages in Java

1. Built-in package(packages from the Java API)


2. User defined package(create your own packages)

76
Genesis Coding School An initiative by IT Professionals
Java

Built-in Packages

The full form of API is Application Programming Interface. It is a document which gives you the list
of all the packages, classes, and interfaces, along with their fields and methods.

Built-in packages or predefined packages are those that come along as a part of JDK (Java
Development Kit) to simplify the task of Java programmer. Using these API’s, the programmer can
know how to use the methods, fields, classes, interfaces provided by Java libraries. They consist of
a huge number of predefined classes and interfaces that are a part of Java API’s. Some of the
commonly used built-in packages are java.lang, java.io, java.util, java.applet, etc.

The library contains components for managing input, database programming, and much much
more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/ .

The library is divided into packages and classes. Meaning you can either import a single class

77
Genesis Coding School An initiative by IT Professionals
Java

(along with its methods and attributes), or a whole package that contain all the classes that
belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax :

import package.name.Class; // Import a single class


import package.name.*; // Import the whole package

Example : Adding a Class

import java.util.Scanner;

Example : Adding a Package

import java.util.*;

Example : Using the Scanner class to get user input:

import java.util.Scanner;

class GenesisExample{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");

String userName = myObj.nextLine();


System.out.println("Username is: " + userName);
}
78
Genesis Coding School An initiative by IT Professionals
Java

User Defined Packages

User-defined packages are those which are developed by users in order to group related classes,
interfaces and sub packages. With the help of an example program, let’s see how to create
packages, compile Java programs inside the packages and execute them.

Example : Illustration of user-defined packages:

Creating our first package:

package packone;

public class ClassOne {


public void methodOne() {
System.out.println("Hello there its ClassOne");
}
}

You have to follow certain steps to create a package

Step 1
You have to compile the package first
79
Genesis Coding School An initiative by IT Professionals
Java

javac ClassOne.java

Step2
Then to create a package run this code

javac -d . ClassOne.java

Creating our second package:

package packtwo;

public class ClassTwo {


public void methodTwo(){
System.out.println("Hello there i am ClassTwo");
}
}

Follow the two steps that have mentioned above to create the second package

Making use of both the created packages:

import packone.ClassOne ;
import packtwo.ClassTwo ;

public class GenesisExample{


public static void main(String[] args){
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
80
Genesis Coding School An initiative by IT Professionals
Java

a.methodTwo();
b.methodOne();
}
}

Output :
Hello there i am ClassTwo
Hello there its ClassOne

Exercise

Q: Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages

Java Comments

 Comments
 Single – line comments
 Multi – line comments
 Documentation comments

81
Genesis Coding School An initiative by IT Professionals
Java

Comments

Comments in Java are often are non-executable statements, they take part in making the program
become more human readable by placing the detail of code involved. Proper use of comments
makes maintenance easier and finding bugs easily. Comments are ignored by the compiler while
compiling a code.

Basically, there are three types of comments in Java. They are as follows :

82
Genesis Coding School An initiative by IT Professionals
Java

 Single – line comments


 Multi – line comments
 Documentation comments

Single – line comments

A beginner level programmer uses mostly single-line comments for describing the code
functionality. Its the most easiest typed comments.

Syntax :

83
Genesis Coding School An initiative by IT Professionals
Java

//Comments here( Text in this line only is considered as comment )

Multi – line comments

To describe a full method in a code or a complex snippet single line comments can be tedious to
write, since we have to give ‘//’ at every line. So to overcome this multi line comments can be
used.

Syntax :

/*Comment starts
comment continues
comment continues
.
.
.
Commnent ends*/

Single or multi-line comments?


It is up to you which you want to use. Normally, we use // for short comments, and /* */ for
longer.

/*Writing single line comment using Multi line comments*/

84
Genesis Coding School An initiative by IT Professionals
Java

Documentation comments

This type of comments are used generally when writing code for a project/software package, since
it helps to generate a documentation page for reference, which can be used for getting
information about methods present, its parameters, etc.

Syntax :

/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h2>
*
*comment ends*/

Java Operators

 Operators

85
Genesis Coding School An initiative by IT Professionals
Java

Operators

Operators are special symbols (characters) that carry out operations on operands (variables and
values). There are many types of operators in Java which are given below:

 Arithmetic Operator
 Unary Operator
 Shift Operator
 Logical Operator
 Bitwise Operator
 Relational Operator
 Assignment Operators
 Ternary Operator

Commonly used Java operators and it's classification


The table below will explain the classifications of different Operators, go through the table. The
different type of operators will be explained after the table. We will be using most of these

86
Genesis Coding School An initiative by IT Professionals
Java

operators on the go. So study this chapter carefully.

Operator Type Category Precedence


Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-

Shift shift << >> >>>

Relational comparison < > <= >=

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Exercise

Q: Which of these have highest precedence?


A. ()
B. ++
87
Genesis Coding School An initiative by IT Professionals
Java

C. *
D. >>

Java Operators 1

 Arithmetic Operators
 Unary Operator
 Shift Operator

Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. For example, + is an operator that performs addition.

The following table lists the arithmetic operators

88
Genesis Coding School An initiative by IT Professionals
Java

Assume integer variable A holds 10 and variable B holds 20

Operator Description Example

Adds values on either side of the operator.


+ (Addition) A + B will give 30

Subtracts right-hand operand from left-hand operand.


- (Subtraction) A - B will give -10

Multiplies values on either side of the operator.


* (Multiplication) A * B will give 200

Divides left-hand operand by right-hand operand.


/ (Division) B / A will give 2

Divides left-hand operand by right-hand operand and


% (Modulus) B % A will give 0
returns remainder.
Increases the value of operand by 1.
++ (Increment) B++ gives 21

Decreases the value of operand by 1.


-- (Decrement) B-- gives 19

Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.

 incrementing/decrementing a value by one


 negating an expression

89
Genesis Coding School An initiative by IT Professionals
Java

 inverting the value of a Boolean.

Take a look at this code snippet to see how increment/decrement operator works

int x=10;
System.out.println(x++);//after execution 11
System.out.println(++x);//after execution 12
System.out.println(x--);//after execution 11
System.out.println(--x);//after execution 10

Output :
10
12
12
10

~(negating an expression) and !(inverting the value of a boolean) Example :

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)

90
Genesis Coding School An initiative by IT Professionals
Java

System.out.println(!c);//false (opposite of boolean value)


System.out.println(!d);//true
}}

Shift Operator

Left Shift Operator :The Java left shift operator << is used to shift all of the bits in a value to the
left side of a specified number of times.
Right Shift Operator :The Java right shift operator >> is used to move left operands value to right
by the number of bits specified by the right operand.

Example :
Left Shift Operator :

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
}}

Example :
Right Shift Operator :

class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
91
Genesis Coding School An initiative by IT Professionals
Java

System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

Exercise

Q: With x = 0, which of the following are legal lines of Java code for changing the value of x to 1?
1. x++;
2. x = x + 1;
3. x += 1;
4. x =+ 1;
a) 1, 2 & 3
b) 1 & 4
c) 1, 2, 3 & 4
d) 3 & 2

Java Operators 2

 Logical Operators
 Bitwise Operators
 Relational Operator
 Assignment Operators

92
Genesis Coding School An initiative by IT Professionals
Java

Logical Operators

The following table lists the logical operators


Assume Boolean variables A holds true and variable B holds false, then

Operator Description Example


Called Logical AND operator. If both the operands are
&& (logical and) (A && B) is false
non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands
|| (logical or) (A || B) is true
are non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the
! (logical not) logical state of its operand. If a condition is true then !(A && B) is true
Logical NOT operator will make false.

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 :
93
Genesis Coding School An initiative by IT Professionals
Java

a = 0011 1100
b = 0000 1101
------------------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators

Assume integer variable A holds 60 and variable B holds 13

Operator Description Example


Binary AND Operator copies a bit to the result if
& (bitwise and) (A & B) will give 12 which is 0000 1100
it exists in both operands.

Binary OR Operator copies a bit if it exists in


| (bitwise or) (A | B) will give 61 which is 0011 1101
either operand.

Binary XOR Operator copies the bit if it is set in


^ (bitwise XOR) (A ^ B) will give 49 which is 0011 0001
one operand but not both.
(~A ) will give -61 which is 1100 0011 in
~ (bitwise Binary Ones Complement Operator is unary and
2's complement form due to a signed
compliment) has the effect of 'flipping' bits.
binary number.
Binary Left Shift Operator. The left operands
<< (left shift) value is moved left by the number of bits A << 2 will give 240 which is 1111 0000
specified by the right operand.
>> (right shift) Binary Right Shift Operator. The left operands A >> 2 will give 15 which is 1111
94
Genesis Coding School An initiative by IT Professionals
Java

value is moved right by the number of bits


specified by the right operand.
Shift right zero fill operator. The left operands
>>> (zero fill right value is moved right by the number of bits
A >>>2 will give 15 which is 0000 1111
shift) specified by the right operand and shifted values
are filled up with zeros.

Relational Operator

Relational operators determine the relationship between the two operands. It checks if an
operand is greater than, less than, equal to, not equal to and so on. Depending on the
relationship, it is evaluated to either true or false.
Operator Description Example
== equal to 5 == 3 is evaluated to false
!= not equal to 5 != 3 is evaluated to true
> greater than 5 > 3 is evaluated to true
< less than 5 < 3 is evaluated to false
>= greater than or equal to 5 >= 5 is evaluated to true
<= less than or equal to 5 <= 5 is evaluated to true

Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=

95
Genesis Coding School An initiative by IT Professionals
Java

num2 = num1 would assign value of variable num1 to the variable.


num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1

Example :

public class AssignmentOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);

num2 += num1;
System.out.println("+= Output: "+num2);

num2 -= num1;
System.out.println("-= Output: "+num2);

num2 *= num1;
System.out.println("*= Output: "+num2);

num2 /= num1;
System.out.println("/= Output: "+num2);
96
Genesis Coding School An initiative by IT Professionals
Java

num2 %= num1;
System.out.println("%= Output: "+num2);
}
}

Output :
= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

Exercise

Q: Boolean logical operators in Java work with?


A) true/false boolean data
B) 1 and 0 of individual Bits
C) characters of a String
D) None of the above

97
Genesis Coding School An initiative by IT Professionals
Java

Java Arrays

 Arrays

Arrays

Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a continuous memory location. It is a data structure where we store
similar elements. Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on. It makes the code optimized, we can retrieve
or sort the data efficiently.

98
Genesis Coding School An initiative by IT Professionals
Java

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.

Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

There are two types of arrays in Java:

 Single-dimension Array
 Multi-dimension Array

Q: Which of these best describes an array?


a) A data structure that shows a hierarchical behaviour
b) Container of objects of similar types

99
Genesis Coding School An initiative by IT Professionals
Java

c) Arrays are immutable once initialised


d) Array is not a data structure

Single-dimension Array

 Single-dimension Array

Single-dimension Array

An array is a collection of similar types of data. It is a container that holds data (values) of one
single type. For example, you can create an array that can hold 100 values of int type.
In Java, arrays are a fundamental construct that allows you to store and access a large number of
values conveniently.

100
Genesis Coding School An initiative by IT Professionals
Java

Syntax : declare an array

dataType[] arrayName;

 dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
 arrayName - it is an identifier

Let's take an example,

int[] number;

Here, number is an array that can hold values of type int.

Let's take another example, Declare and Instantiation of an Array in Java

int[] age; //Declaration


age = new int[5]; //Instantiation

101
Genesis Coding School An initiative by IT Professionals
Java

Here, age is an array. It can hold 5 values of int type.

In Java, we can declare and allocate memory of an array in one single statement. For example,

int[] age = new int[5];

Java Array Index

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on. The index is known as an array index. We can access elements of
an array by using those indices.

Look at this example,

int[] age = new int[5];

Here, we have an array of length 5. The array indices always start from 0.

Now, we can use the index number to access elements of the array. For example, to access the

102
Genesis Coding School An initiative by IT Professionals
Java

first element of the array is we can use age[0], and the second element is accessed
using age[1] and so on.

Example1 :

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=111;//initialization
a[1]=112;
a[2]=113;
a[3]=114;
a[4]=115;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output :
111
112
113
114
115

Example2 :

103
Genesis Coding School An initiative by IT Professionals
Java

class Testarray1{
public static void main(String args[]){
int a[]={11,2,3,4};//declaration, instantiation and initialization in a single line
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output :
11
2
3
4

Exercise

Q: What will be the output of the following Java code?

int arr[] = new int [5];


System.out.print(arr);

a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form

104
Genesis Coding School An initiative by IT Professionals
Java

Multi-dimension Array

 Multi-dimension Array

Multi-dimension Array

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Java. Multidimensional Arrays can be defined in simple words as array
of arrays. In Multi-dimension Array, data is stored in row and column based index (also known as
matrix form). The total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.

105
Genesis Coding School An initiative by IT Professionals
Java

2D-Array

Each element of a multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can
hold a maximum of 12 elements, See the image below to understand how system handles the
example array int[][] a = new int[3][4];.

Now lets see the visualisation of a 3 x 4 and 4 x 3

106
Genesis Coding School An initiative by IT Professionals
Java

3D-Array

Let's take another example of the multidimensional array. This time we will be creating a 3-
dimensional array.

String[][][] data = new String[4][3][2];

Here, data is a 3d array that can hold a maximum of 24 (4*3*2) elements of type String.

Visualisation of a 3d array

107
Genesis Coding School An initiative by IT Professionals
Java

initializing a 2d array :

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

initializing a 3d array :

int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{

108
Genesis Coding School An initiative by IT Professionals
Java

{-4, -5, 6, 9},


{1},
{2, 3}
}
};

Example : 2d Array

class GenesisExample {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}

System.out.println();
}
}
}

Output :
12
34

Example : 3d Array

109
Genesis Coding School An initiative by IT Professionals
Java

class GFG {
public static void main(String[] args)
{ int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
System.out.print(arr[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Output :
12
34

56
78

Q: Which of the following is a correct way to declare a multidimensional array in Java?


a) int[] arr;

110
Genesis Coding School An initiative by IT Professionals
Java

b) int arr[[]];
c) int[][]arr;
d) int[[]] arr;

Type Casting in Java

 Type Casting in Java


 Widening Type Casting
 Narrowing Type Casting
 Type promotion
 Type Casting : More Examples

Type Casting in Java

111
Genesis Coding School An initiative by IT Professionals
Java

When you assign value of one data type to another(variable a of integer type is assigned to a
variable b of long type), the two types might not be compatible with each other. If the data types
are compatible, then Java will perform the conversion automatically known as Automatic Type
Conversion or Implicit type Conversion, And if not then they need to be casted or converted
explicitly. For example, assigning an long value to a int variable.

Widening Type Casting

In Widening Type Casting, Java automatically converts one data type to another data type.
Implicitly done :

Take a look at the above figure. In the case of Widening Type Casting, the lower data type (having
smaller size) is converted into the higher data type (having larger size). Hence there is no loss in
data. This is why this Widening Type Casting happens automatically. See the example below to
have a good understanding.

Example: Converting int to double

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

112
Genesis Coding School An initiative by IT Professionals
Java

int number = 66; // creating int type variable


System.out.println("The integer value: " + number);

double data = number; //int number is converted into double type


System.out.println("The double value is: " + data);
}
}

Output :
The integer value is: 66
The double value: 66.0

In the above example, we are assigning the int type variable named number to a double type
variable named data. Here, the Java first converts the int type data into the double type. And then
assign it to the double variable.

Narrowing Type Casting

In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.
Explicitly done :

113
Genesis Coding School An initiative by IT Professionals
Java

In the case of Narrowing Type Casting, the higher data types (having larger size) are converted
into lower data types (having smaller size). Hence there is the loss of data. This is why this type of
conversion does not happen automatically. After reading this carefully go through the example
below.

Example: Converting double into an int

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

double number = 66.66; // creating double type variable


System.out.println("The double value is: " + number);

int data = (int)number; // converting double into int type


System.out.println("The integer value is: " + data);
}
}

Output :
The double value: 66.66
The integer value: 66

int data = (int)number;

Here, the int keyword inside the parenthesis indicates that that the variable number is converted
into the int type.

114
Genesis Coding School An initiative by IT Professionals
Java

Type promotion
While evaluating expressions, the intermediate value may exceed the range of operands and
hence the expression value will be promoted. Some conditions for type promotion are:

 Java automatically promotes each byte, short, or char operand to int when evaluating an
expression.
 If one operand is a long, float or double the whole expression is promoted to long, float or
double respectively

Example : Type promotion in Expressions

//Java program to illustrate Type promotion in Expressions


class GenesisExercise{
public static void main(String args[]) {
byte b = 50;
char c = 'a';
short s = 1024;
int i = 1234;
float f = 7.67f;
double d = .6921;
double result = (f / b) - (i / c) + (d * s); // The Expression

System.out.println("result = " + result); //Result after all the promotions are done

115
Genesis Coding School An initiative by IT Professionals
Java

}
}

Output :
result = 696.8638004211426

Type Casting : More Examples

Example 1 : Type conversion from int to String

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

int number = 10; // create int type variable


System.out.println("The integer value is: " + number);

String data = String.valueOf(number); // converts int to string type


System.out.println("The string value is: " + data);
}
}

Output :
The integer value is: 10
The string value is: 10

116
Genesis Coding School An initiative by IT Professionals
Java

Here, we have used the valueOf() method of the Java String class to convert the int type variable
into a string.

Example : 2

public class GenesisExercise{


public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required, int to long
float f = l; //no explicit type casting required, long to float
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

Example : 3

public class GenesisExercise{


public static void main(String[] args)
{

117
Genesis Coding School An initiative by IT Professionals
Java

double d = 100.04;
long l = (long)d; //explicit type casting required, double into long
int i = (int)l; //explicit type casting required, long into int

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


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

Output :
Double value 100.04
Long value 100
Int value 100

Exercise :

Q:Which of these is necessary condition for automatic type conversion in Java?


a) The destination type is smaller than source type
b) The destination type is larger than source type
c) The destination type can be larger or smaller than source type
d) None of the mentioned

118
Genesis Coding School An initiative by IT Professionals

You might also like