0% found this document useful (0 votes)
26 views14 pages

Chapter 2 - Java Basics

The document discusses Java data types and variables. It describes the primitive and non-primitive data types in Java including byte, short, int, long, float, double, char, boolean, and classes/interfaces/arrays. It also discusses Java identifiers, keywords, and the different types of variables (local, instance, static).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
26 views14 pages

Chapter 2 - Java Basics

The document discusses Java data types and variables. It describes the primitive and non-primitive data types in Java including byte, short, int, long, float, double, char, boolean, and classes/interfaces/arrays. It also discusses Java identifiers, keywords, and the different types of variables (local, instance, static).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

2.

Java Basics

2.1 Java – Data Types


Every variable in Java has a data type. Data types specify the different
sizes and values that can be stored in the variable. There are two types
of data types in Java:
Primitive data types: The primitive data types include byte, short,
int, long, float, double, char and boolean.
Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.

Byte

Byte data type is an 8-bit signed two's complement integer

Default value is 0

Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
Example:
byte employeeId = 121;

Short
Short data type is a 16-bit signed two's complement integer
Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an integer

Default value is 0.

Example:
short employeeAge = 21;

int
Int data type is a 32-bit signed two's complement integer.
Integer is generally used as the default data type for integral values
unless there is a concern about memory.
The default value is 0

Example:
int customerId = 122;

long
Long data type is a 64-bit signed two's complement integer
This type is used when a wider range than int is needed
Default value is 0L
Example:
long customerContactNumber = 9623639693L;

float
Float data type is a single-precision 32-bit IEEE 754 floating point

Float is mainly used to save memory in large arrays of floating point


numbers
Default value is 0.0f

Float data type is never used for precise values such as currency

Example:
float productPrice = 5.75f;

double
double data type is a double-precision 64-bit IEEE 754 floating point

This data type is generally used as the default data type for decimal
values, generally the default choice

Double data type should never be used for precise values such as
currency
Default value is 0.0d

Example:
double employeeSalary = 90000.96d;

boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example:
boolean isStatusOnline = true

char
char data type is a single 16-bit Unicode character
Char data type is used to store any character
Default value is '\u0000'
Example:
char employeeGrade = 'A';

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer
to objects.

The main difference between primitive and non-primitive data types


are:

Primitive types are predefined (already defined) in Java. Non-


primitive types are created by the programmer and is not defined by
Java (except for String).
Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
A primitive type has always a value, while non-primitive types can be
null.
A primitive type starts with a lowercase letter, while non-primitive
types starts with an uppercase letter.
The size of a primitive type depends on the data type, while non-
primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, etc.
i.e. Customer customer = new Customer(“JERRY”);

2.2 Java Identifiers


In programming languages, identifiers are used for identification
purpose. In Java, an identifier can be a class name, method name,
variable name or a label. For example :

public class Customer


{
public static void main(String[] args)
{
int customerId = 121;
}
}

In the above java code, we have 5 identifiers namely :

Customer : class name.


main : method name.
String : predefined class name.
args : variable name.
customerId : variable name.

Rules for defining Java Identifiers

There are certain rules for defining a valid java identifier. These
rules must be followed, otherwise we get compile-time error. These
rules are also valid for other languages like C,C++.

The only allowed characters for identifiers are all alphanumeric


characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘
(underscore).For example “java@” is not a valid java identifier as it
contain ‘@’ special character.
Identifiers should not start with digits([0-9]). For example
“123java” is a not a valid java identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to
use an optimum length of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example “int
while = 20;” is an invalid statement as while is a reserved word.
There are 53 reserved words in Java.
Examples of valid identifiers :
employeeId

2.3 Java Variables


Variables are containers for storing data values. A variable is
a name given to a memory location. It is the basic unit of
storage in a program.

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.

There are three types of variables in java: local, instance and


static.

1) 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.

2) 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.

3) 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.
class Customer{
int customerId=121;//instance variable
static int customerAge=22;//static variable
void show(){
int customerName=”JERRY”;//local variable
}
}//end of class

2.4 Java Keywords


Java keywords are also known as reserved words. Keywords
are particular words which acts as a key to a code. These are
predefined words by Java so it cannot be used as a variables,
methods, classes or object name. Doing this will result into a
compile time error.

The keywords const and goto are reserved, even though they
are not currently used. true, false, and null might seem like
keywords, but they are actually literals; you cannot use them
as identifiers in your programs.

List of Java Keywords


Till date, there are only 50 keywords in java. Those are listed
below-

1. abstract: Java abstract keyword is used to declare


abstract class. Abstract class can provide the
implementation of interface. It can have abstract and non-
abstract methods.

2. boolean: Java boolean keyword is used to declare a


variable as a boolean type. It can hold True and False
values only.

3. break: Java break keyword is used to break loop or


switch statement. It breaks the current flow of the
program at specified condition.

4. byte: Java byte keyword is used to declare a variable that


can hold an 8-bit data values.
5. case: Java case keyword is used to with the switch
statements to mark blocks of text.

6. catch: Java catch keyword is used to catch the exceptions


generated by try statements. It must be used after the try
block only.

7. char: Java char keyword is used to declare a variable that


can hold unsigned 16-bit Unicode characters

8. class: Java class keyword is used to declare a class.

9. const: Constants are basically variables whose value can't


change. In C/C++, the keyword const is used to declare
these constant variables. In Java, for constant declaration
use the keyword final.

10. continue: Java continue keyword is used to continue


the loop. It continues the current flow of the program and
skips the remaining code at the specified condition.

11. default: Java default keyword is used to specify the


default block of code in a switch statement.

12. do: Java do keyword is used in control statement to


declare a loop. It can iterate a part of the program several
times.

13. double: Java double keyword is used to declare a


variable that can hold a 64-bit floating-point numbers.

14. else: Java else keyword is used to indicate the


alternative branches in an if statement.

15. enum: Java enum keyword is used to define a fixed


set of constants. Enum constructors are always private or
default.
16. extends: Java extends keyword is used to indicate
that a class is derived from another class or interface.

17. final: Java final keyword is used to indicate that a


variable holds a constant value. It is applied with a
variable. It is used to restrict the user.

18. finally: Java finally keyword indicates a block of code


in a try-catch structure. This block is always executed
whether exception is handled or not.

19. float: Java float keyword is used to declare a variable


that can hold a 32-bit floating-point number.
20. for: Java for keyword is used to start a for loop. It is
used to execute a set of instructions/functions repeatedly
when some conditions become true. If the number of
iteration is fixed, it is recommended to use for loop.
21. goto: Java does not support goto, it is reserved as a
keyword just in case they wanted to add it to a later
version.
22. if: Java if keyword tests the condition. It executes the
if block if condition is true.
23. implements: Java implements keyword is used to
implement an interface.
24. import: Java import keyword makes classes and
interfaces available and accessible to the current source
code.
25. instanceof: Java instanceof keyword is used to test
whether the object is an instance of the specified class or
implements an interface.
26. int: Java int keyword is used to declare a variable that
can hold a 32-bit signed integer.
27. interface: Java interface keyword is used to declare
an interface. It can have only abstract methods.
28. long: Java long keyword is used to declare a variable
that can hold a 64-bit integer.
29. native: Java native keyword is used to specify that a
method is implemented in native code using JNI (Java
Native Interface).
30. new: Java new keyword is used to create new objects.
31. null: Java null keyword is used to indicate that a
reference does not refer to anything. It removes the
garbage value.
32. package: Java package keyword is used to declare a
Java package that includes the classes.
33. private: Java private keyword is an access modifier. It
is used to indicate that a method or variable may be
accessed only in the class in which it is declared.
34. protected: Java protected keyword is an access
modifier. It can be accessible within package and outside
the package but through inheritance only. It can't be
applied on the class.
35. public: Java public keyword is an access modifier. It is
used to indicate that an item is accessible anywhere. It
has the widest scope among all other modifiers.
36. return: Java return keyword is used to return from a
method when its execution is complete.
37. short: Java short keyword is used to declare a variable
that can hold a 16-bit integer.
38. static: Java static keyword is used to indicate that a
variable or method is a class method. The static keyword
in Java is used for memory management mainly.
39. strictfp: Java strictfp is used to restrict the floating-
point calculations to ensure portability.
40. super: Java super keyword is a reference variable that
is used to refer parent class object. It can be used to
invoke immediate parent class method.
41. switch: The Java switch keyword contains a switch
statement that executes code based on test value. The
switch statement tests the equality of a variable against
multiple values.
42. synchronized: Java synchronized keyword is used to
specify the critical sections or methods in multithreaded
code.
43. this: Java this keyword can be used to refer the
current object in a method or constructor.
44. throw: The Java throw keyword is used to explicitly
throw an exception. The throw keyword is mainly used to
throw custom exception. It is followed by an instance.
45. throws: The Java throws keyword is used to declare
an exception. Checked exception can be propagated with
throws.
46. transient: Java transient keyword is used in
serialization. If you define any data member as transient,
it will not be serialized.
47. try: Java try keyword is used to start a block of code
that will be tested for exceptions. The try block must be
followed by either catch or finally block.
48. void: Java void keyword is used to specify that a
method does not have a return value.
49. volatile: Java volatile keyword is used to indicate that
a variable may change asynchronously.
50. while: Java while keyword is used to start a while
loop. This loop iterates a part of the program several
times. If the number of iteration is not fixed, it is
recommended to use while loop.

2.5 Comments in Java


In a program, comments take part in making the program
become more human readable by placing the detail of code
involved and proper use of comments makes maintenance easier
and finding bugs easily. Comments are ignored by the compiler
while compiling a code.

In Java there are three types of comments:

1. Single – line comments.


The single line comment is used to comment only one line.
Syntax: //This is single line comment

2. Multi – line comments.


The multi line comment is used to comment multiple lines of
code.
Syntax:
/*
This
is
multi line
comment
*/

3. 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:
/**
This
is
documentation
comment
*/

Example:

2.6 Java Package


Package in Java is a mechanism to encapsulate a group of
classes, sub packages and interfaces.
java.lang package by default available in Java.

Package Types-

1. User Defined
These are the packages that are defined by the user.
2. In Built
These packages consist of a large number of classes which
are a part of Java API.Some of the commonly used built-in
packages are:
1) java.lang: Contains language support classes(e.g
classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output
operations.
3) java.util: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for
Date / Time operations.

Packages are used for:

1. Preventing naming conflicts. For example there can be two


classes with name Customer in two packages,
com.fullstack.hdfc.Customer and
com.fullstack.icici.Customer
2. Making searching/locating and usage of classes,
interfaces, enumerations and annotations easier
3. Providing controlled access: protected and default have
package level access control. A protected member is
accessible by classes in the same package and its
subclasses. A default member (without any access
specifier) is accessible by classes in the same package
only.
4. Packages can be considered as data encapsulation (or
data-hiding).
All we need to do is put related classes into packages. After
that, we can simply write an import class from existing
packages and use it in our program. A package is containers
of a group of related classes where some of the classes are
accessible are exposed and others are kept for internal
purpose.
We can reuse existing classes from the packages as many
times as we need it in our program.

Syntax:
package com.fullstack.hdfc.loan.aggreeloan.emi.advance
package com.fullstack.hdfc.loan.aggreeloan.emi.preclosure
package com.fullstack.hdfc.loan.homeloan.emi.advance

As per Industry Standers-

1. com is operating systems- core level package. This is generally a


company specification. In this case, the root folder is “com”.
2. fullstack is a company name as Full Stack Java Developer in
which product is developed
3. hdfc is the client name for which we are developing our product
4. loan is our project name
5. agree loan and home loan are loan types and so on
6. Let it be noted that we can give any names, this is just a
specification.
7. Keep in mind that the root folder should always be same for all
classes.

2.7 TypeCasting
Typecasting means convert one primitive datatype into another
type.

In Java, there are two types of casting:


1. Upcasting[Widening Casting] (automatically) - converting a
smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
2. Downcasting[Narrowing] Casting (manually) - converting a
larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

2.8 Autoboxing & Unboxing


Autoboxing- convert primitive datatype into wrapper class
Ex. int to Integer, double to Double

Unboxing- convert wrapper class into primitive datatype


Ex. Integer to int, Double to double

2.9 Java Access Modifiers

The access modifiers in Java specifies the accessibility or scope


of a field, method, constructor, or class. We can change the
access level of fields, constructors, methods, and class by
applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within


the class. It cannot be accessed from outside the class.

2. Default: The access level of a default modifier is only within


the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the
default.

3. Protected: The access level of a protected modifier is within


the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It


can be accessed from within the class, outside the class,
within the package and outside the package.

You might also like