Java Language Fundamentals (chapter 2)
Java Comments
The compiler and the interpreter do not execute the comments in the program.
use of comments,
- Make the code more readable and explainable.
- Easy to modify and find errors.
- Prevent execution of some code blocks when testing alternative codes.
There are two types of comments,
- single-line comments
// one line comment
- multi-line comments
/*
multi line comments
*/
Java Variables
Variables are used for data storing purposes. There are different ways to create variables.
// Declaration of a variable
int count;
String name;
// Initialization of a variable
count = 12;
name = "Jhone";
// we can do both in one line
int age = 15;
String last_name = "Wick";
Types of Variables
There are 3 types of variables,
- local variables
- static variables
- instance variables
Local variables
Local variables are declared inside a body of a method or a block.
This variable is stored inside a stack memory. The scope of the local variable is the scope of the block or the method.
public class ExampleClass {
public void exampleMethod() {
int localVar = 10; // This is a local variable
System.out.println(localVar);
}
// can't use outside of the method
}
Instance variables
Instance variables are declared outside of the body of the method without the STATIC keyword (within the class).
Instance variables are object-specific which means a separate copy of the variable will be created for each object. This variable is stored inside a heap memory. The scope of the instance variable is the scope of the object.
public class ExampleClass {
int instanceVar; // This is an instance variable
public void setInstanceVar(int value) {
instanceVar = value;
// can use within the class (inside methods or blocks)
}
public int getInstanceVar() {
return instanceVar;
}
}
// can't use outside the class directly, for outside use have to make a object
Static variables
Static variables are declared outside of the body of the method with the STATIC keyword (within the class).
Static variables are shared across all objects of the same class (single copy) and can be accessed using the class name rather than an object reference. This is not object-specific and is declared at the class level. Also, static variables can’t be local variables. The scope is the scope of the class file.
public class ExampleClass {
static int staticVar; // This is a static variable
public void setStaticVar(int value) {
staticVar = value;
}
public int getStaticVar() {
return staticVar;
}
}
Java Identifiers
In java, identifiers are names given to classes, variables, methods, packages, and other program elements. Identifiers are used to identify and refer to these program elements in the code.
There are some rules and conventions for naming identifiers,
- Identifiers must start with a letter (A-Z or a-z) or an underscore (_) or a dollar sign ($).
- After the first character, identifiers can contain letters, digits (0–9), underscores, and dollar signs. (no limit for the number of characters)
- Identifiers cannot use reserved words or keywords (such as
class
,public
,void
, etc.) or operators (such as+
,-
,*
,/
, etc.) as their names. - Identifiers are case-sensitive. (
myVariable
andMyVariable
are different identifiers ) - Identifiers can’t contain white spaces. (
My Variable
is invalid ) - It is a convention in Java to use camel case for naming variables and methods (e.g.,
myVariable
,myMethod()
) and Pascal's case for naming classes (e.g.,MyClass
).
// Vaild Identifiers examples,
int myVariable;
String firstName;
double averageScore;
void myMethod();
MyClass myClassObject;
// Invaild Identifiers examples,
int 123Variable; // Can't start with a digit
String public; // Can't use a reserved word / keyword
void my-method(); // Can't use hyphen in identifier
String first Name; // can't have white spaces
Java Keywords
Keywords are also known as reserved words. Here is a list of keywords in java,
abstract, assert, boolean, break, byte, case, catch, char, class,
continue, default, do, double, else, enum, extends, final, finally,
float, for, if, implements, import, instanceof, int, interface, long,
native, new, null, package, private, protected, public, return, short,
static, strictfp, super, synchronized, this, throw, throws, transient,
try, void, volatile
Data Types
The data types are used for specifying the different sizes and types of variables that can be stored. Java is a strongly typed programming language, which means that every variable in the program must be declared knowing the data type and range of values.
There are two data types in java,
- primitive data types
- non-primitive data types
primitive data types
Primitive data types are predefined and it has no additional methods. There are 8 primitive data types (boolean, char, byte, short, int, long, float, double ).
non-primitive data types
Non-primitive data types are not predefined and they are created by the programmers. class, arrays, interfaces and Strings are some examples of non-primitive data types. These can be null and also can call methods and perform certain operations.
Java literals
Java literals are the fixed values that assign to the variables.
1. Integer literals
An integer literal is a value that represents a whole number and is expressed in the code as an integer. Integer literals can be written in several formats, including decimal, binary (0b), octal (0), and hexadecimal (0x) formats.
// Decimal integer literals
int myInt = 42;
int myNegativeInt = -42;
// Binary integer literals
int myBinary = 0b101010; // 0b
int myNegativeBinary = -0b101010;
// Ocatal integer literals
int myOctal = 052; // 0
int myNegativeOctal = -052;
// Hexadecimal integer literals
int myHex = 0xA3; // 0x
int myNegativeHex = -0xA3;
They are assigned to data types byte
, short
, int
and long
. In the long
data type, we use L
or l
as a suffix after the variable.
byte byteNum = 42;
short shortNum = 1000;
int intNum = 1000000;
long longNum = 988888873L; // or 988888873l
Integer literals in Java can also include underscores (_) to improve readability.
int longInt = 1_000_000_000;
int negativeLongInt = -1_000_000_000;
2. Floating-point literals
These literals are used for float
and double
data types. By default, every floating-point literal is a double type. By using suffix f
or F
can create a float
data type.
float floatNum = 12.0413F; // or 12.0413f
double doubleNum = 12.04136516;
3. Boolean literals
This literal is used to initialize a boolean data type.
boolean boolValue = true; // or false
4. Char literals
Unicode char enclosed inside single quotes.
char myChar = 'a';
Escape sequences in java
Special sequences of characters are used to represent certain characters that would otherwise be difficult or impossible to include in a string literal. In Java, the backslash (\
) character is used to indicate an escape sequence.
\\ // Backslash
\n // New line
\r // Carriage return (move cursor to beginning of line)
\t // Tab
\b // Backspace
\f // Form feed (advance printer to next page)
\" // Double quote
\' // Single quote
// Example,
String myString = "He said, \"Hello world!\"";
System.out.println(myString); // Output: He said, "Hello world!"
Type Casting
Type casting is the process of converting the value of one data type to another data type. There are two main ways to typecast in java,
- Widening type casting (implicit type casting)
- Narrowing type casting (explicit type casting)
1. Widening type casting (implicit type casting)
widening casting is converting a small capacity data type to a larger capacity data type. This casting is done automatically when assigning a variable of smaller capacity to another variable of larger capacity.
byte -> short -> char -> int -> long -> float -> double
int x = 5;
double y = x; // implicit type casting from int to double
System.out.println(y); // Output: 5.0
2. Narrowing type casting (explicit type casting)
The higher data types are converted into lower data types. Hence there is a loss of data. Therefore, this type of conversion does not happen automatically.
double -> float -> long -> int -> char -> short -> byte
double x = 5.5;
int y = (int) x; // explicit type casting from double to int
System.out.println(y); // Output: 5
Overflow and Underflow
Overflow occurs when we assign such a value to a variable which is more than the maximum permissible value.
Underflow occurs when we assign such a value to a variable which is less than the minimum permissible value.
There will be no errors but it will change the value of the variable.
byte x = 127;
x++; // overflow occurs, x is now -128
System.out.println(x); // Output: -128
byte y = -128;
y--; // underflow occurs, y is now 127
System.out.println(y); // Output: 127
In the next chapter, we will discuss operations in java language.