Java Set1
Java Set1
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
......................................................................................................................................................................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
4
Genesis Coding School An initiative by IT Professionals
Java
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
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.
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
12
Genesis Coding School An initiative by IT Professionals
Java
Exercise
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
14
Genesis Coding School An initiative by IT Professionals
Java
Accept the licenses by ticking the checkbox and click the download button.
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
19
Genesis Coding School An initiative by IT Professionals
Java
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
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
26
Genesis Coding School An initiative by IT Professionals
Java
steps
Let me explain in detail about these steps.
27
Genesis Coding School An initiative by IT Professionals
Java
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
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
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
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.
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
This is the step where the program is actually run to get the output.
To do it,
java MyFirstProgram
Hello World!
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.
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.
35
Genesis Coding School An initiative by IT Professionals
Java
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
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.
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:
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
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.
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.
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.
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
40
Genesis Coding School An initiative by IT Professionals
Java
41
Genesis Coding School An initiative by IT Professionals
Java
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.
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
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
44
Genesis Coding School An initiative by IT Professionals
Java
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*
45
Genesis Coding School An initiative by IT Professionals
Java
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
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!
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?
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
System.out.println("Benz")
System.out.println("Hello World!")
System.out.println("5")
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")
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
49
Genesis Coding School An initiative by IT Professionals
Java
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:-
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..
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.
51
Genesis Coding School An initiative by IT Professionals
Java
1. int
2. float
3. strings
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.
53
Genesis Coding School An initiative by IT Professionals
Java
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
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.
Note: Always suffix float value with the “f” else compiler will consider it as double.
char ch = 'Z';
String str = “GenesisAcademy";
56
Genesis Coding School An initiative by IT Professionals
Java
Exercise
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:
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
59
Genesis Coding School An initiative by IT Professionals
Java
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:
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:
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:
class JavaExample {
public static void main(String[] args)
{
float num = 19.98f;
System.out.println(num);
}
}
Output:19.98
Boolean:
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
65
Genesis Coding School An initiative by IT Professionals
Java
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
68
Genesis Coding School An initiative by IT Professionals
Java
c) int
d) byte
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.
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
class GenesisExample {
public static void main(String[] args) {
int number = 10;
System.out.println(5);
System.out.print(number);
}
}
output :
5
10
class GenesisExample {
public static void main(String[] args) {
71
Genesis Coding School An initiative by IT Professionals
Java
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.
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
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);
Output :
Enter an integer: 23
You entered 23
73
Genesis Coding School An initiative by IT Professionals
Java
Exercise
a) AB
b) 195
c) 131
d) Error
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
Reusability
Better Organization
Name Conflicts
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 java.util.Scanner;
import java.util.*;
import java.util.Scanner;
class GenesisExample{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
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.
package packone;
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
package packtwo;
Follow the two steps that have mentioned above to create the second package
import packone.ClassOne ;
import packtwo.ClassTwo ;
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
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
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*/
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
86
Genesis Coding School An initiative by IT Professionals
Java
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Exercise
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.
88
Genesis Coding School An initiative by IT Professionals
Java
Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.
89
Genesis Coding School An initiative by IT Professionals
Java
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
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
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
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
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
95
Genesis Coding School An initiative by IT Professionals
Java
Example :
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
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.
Single-dimension Array
Multi-dimension Array
99
Genesis Coding School An initiative by IT Professionals
Java
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
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName - it is an identifier
int[] number;
101
Genesis Coding School An initiative by IT Professionals
Java
In Java, we can declare and allocate memory of an array in one single statement. For example,
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.
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
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
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];.
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.
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
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
110
Genesis Coding School An initiative by IT Professionals
Java
b) int arr[[]];
c) int[][]arr;
d) int[[]] arr;
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.
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.
class GenesisExample{
public static void main(String[] args) {
112
Genesis Coding School An initiative by IT Professionals
Java
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.
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.
class GenesisExample{
public static void main(String[] args) {
Output :
The double value: 66.66
The integer value: 66
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
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
class GenesisExercise{
public static void main(String[] args) {
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
Output :
Int value 100
Long value 100
Float value 100.0
Example : 3
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
Output :
Double value 100.04
Long value 100
Int value 100
Exercise :
118
Genesis Coding School An initiative by IT Professionals