Java Basics


Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name.
int gear = 1; Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it.

Data Types in Java
Primitive Data Type

There are eight primitive data types in Java:

Data Type Size Description Syntax
byte 1 byte Stores whole numbers from -128 to 127 byte byteVar;
byte b = 126;
short 2 bytes Stores whole numbers from -32,768 to 32,767 short shortVar;
short s = 56;
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 int intVar;
int i = 89;
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long longVar;
long a = 100000L, long b = -200000L
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits float floatVar;
float f = 4.7333434f;
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits double doubleVar;
double d = 4.355453532;
boolean 1 bit Stores true or false values boolean booleanVar;
boolean b = true;
char 2 bytes Stores a single character/letter or ASCII values char charVar;
char ch = 'G';
Non-Primitive Data Type

The Reference 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, class, objects, interface, arrays, etc.

String:

Strings are defined as an array of characters. The difference between a character array and a string in Java is, the string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of separate char type entities.
// Declare String without using new operator
String s = "hello";
// Declare String using new operator
String s1 = new String("hello");

Class:

A class is a user-defined blueprint or prototype from which objects are created. It represents the 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, which as you know, interact by invoking methods.

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, nobody).

Arrays:

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++. The following are some important points about Java arrays.


Naming Conventions

Classes and Interfaces

Class names should be nouns, in mixed cases with the first letter of each internal word capitalized.
Interface names should also be capitalized just like class names.
Classes:
public class Employee
{
//code snippet
}
Interfaces :
interface Printable
{
//code snippet
}

Methods

Methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized.
class Employee
{
//method
void draw()
{
//code snippet
}
}

Variables

Variable names should be short yet meaningful.
Variables can also start with either underscore('_') or dollar sign '$' characters. Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
One-character variable names should be avoided except for temporary variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
class Employee
{
//variable
int id;
//code snippet
}

Constant Variables

Should be all uppercase with words separated by underscores (“_”). There are various constants used in predefined classes like Float, Long, String etc.
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;

Packages

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.
Subsequent components of the package name vary according to an organization’s own internal naming conventions.
java.util.Scanner ;
java.io.*;
class Employee
{
//code snippet
}
As the name suggests in the first case we are trying to access the Scanner class from the java.util package and in other all classes(* standing for all) input-output classes making it so easy for another programmer to identify.

Operators

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift <<>> >>>
relational <> <=>= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<=>>= >>>=

The equality operator (==) compares only the value after applying the type coercion, if applicable. The strict equality operator (===) compares both, the value and the type, of two operands.

Methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
Create a method inside Main:

public class Main {
static void myMethod() {
// code to be executed
}
}
Inside main, call the myMethod() method:

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

Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");

Conditions

Java supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions. Java has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
if (20 > 18) {
System.out.println("20 is greater than 18");
}
  • Use else to specify a block of code to be executed, if the same condition is false
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
  • Use else if to specify a new condition to test, if the first condition is false
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
  • Short Hand If...Else Or ternary operator
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening." ;
System.out.println(result);
  • Use switch to specify many alternative blocks of code to be executed
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Loop

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

For Loop

For loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
The syntax of a for loop is as shown below.
// For(initialization; condition ; increment)
for(int counter = 1; counter <= 10; counter++){
System.out.println(counter);
}

Enhanced For Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined variable.
// Syntex

for( [datatype] [variable_name] : [collection_name] ) {
//Statements;
}

// Example of Enhanced For Loop

public class EnhancedFor {
public static void main(String[] args) {
String array[] = {
"C",
"Java",
"Python"
};
for (String a: array) {
System.out.println(a);
}
}
}

While loop

The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop.
//The basic syntax of Java while loop is:
while(boolean condition)
{
//statements;
}

int counter = 1; // Control variable initialized
// Condition for loop continuation
while (counter <= 10)
{
System.out.println(counter);
counter++; // Increment the control variable
}

Do While loop

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body.
int counter = 1; // Control variable initialized
do{
System.out.println(counter);
counter--; // Decrements the control variable
} while(counter <= 10); // Condition statement