Basic Concepts of Java
Table of Contents
Java Basic Syntax
Java is an object-oriented programming language, which means that it consists of objects that interact with each other through method calls to perform various tasks. Here’s an overview of some essential concepts in Java:
Basic Terminologies in Java:
1. Class:A class is a blueprint for objects. It defines a logical template that shares common properties and methods.
2. Object: An object is an instance of a class. It represents an entity with a behavior and state.
3. Method: A method defines the behavior of an object.
4. Instance Variables: Each object has its own unique set of instance variables. These variables represent the state of an object, defined by the values assigned to them.
Example: Compiling and Running a Java Program in a Console
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output:
Hello, World!
5. Comments in Java: There are three types of comments in Java:
- Single-line Comment:
// This is a single-line comment
- Multi-line Comment:
/*
This is a multi-line comment
*/
- Documentation Comment:
/** This is a documentation comment */
6. Source File Name: The source file name should exactly match the public class name with the extension .java
. If there is no public class, the file name can differ.
Example:
GFG.java // valid
gfg.java // invalid if public class is GFG
7. Case Sensitivity:
Java is case-sensitive, meaning identifiers like AB
, Ab
, aB
, and ab
are considered different.
Example:
System.out.println("Hello"); // valid
system.out.println("Hello"); // invalid
8. Class Names: The first letter of a class name should be uppercase.If multiple words are used, each word should start with an uppercase letter.
Example:
class MyClass // valid
class 1Program // invalid
class My1Program // valid
class $Program // valid but discouraged
9. Main Method: The main()
method is the entry point of every Java program:
public static void main(String[] args) {
// program logic
}
10. Method Names: Method names should start with a lowercase letter.If multiple words are used, the first letter of each word (after the first one) should be uppercase.
Example:
public void calculateSum() // valid
11. Identifiers in Java: Identifiers are names given to classes, methods, variables, etc. They must follow certain rules:Can begin with a letter, underscore (_), or currency symbol. Subsequent characters can be letters, digits, or underscores. Java keywords cannot be used as identifiers. Legal identifiers: myVar, hello_world, $amount.
Illegal identifiers: 1Var, -amount.
12. White Spaces in Java: Blank lines, spaces, and comments are ignored by the Java compiler.
13. Access Modifiers: Java provides access control to classes and methods through access modifiers:
Access Modifier | Within Class | Within Package | Outside Package by Subclass | Outside Package |
---|---|---|---|---|
Private | Yes | No | No | No |
Default | Yes | Yes | No | No |
Protected | Yes | Yes | Yes | No |
Public | Yes | Yes | Yes | Yes |
14. Java Keywords:
Keywords in Java have predefined meanings and cannot be used as identifiers. Examples include class
, interface
, void
, int
, public
, static
, etc.
Java Hello World Program
Java is one of the most popular and widely-used programming languages, known for its speed, reliability, and security. Java applications can be found everywhere—from desktop software to web applications, scientific supercomputers to gaming consoles, and mobile phones to the Internet. In this guide, we’ll explore how to write a simple Java program.
Steps to Implement a Java Program
To implement a Java application, follow these key steps:
- Creating the Program
- Compiling the Program
- Running the Program
If you’re looking to dive deeper into Java and gain a strong understanding of the entire development process, consider enrolling in a structured Java programming course. These courses provide hands-on experience and cover everything from basic to advanced topics, allowing you to develop efficient and scalable applications.
Example of a Simple Java Program
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output:
Hello, World!
Primitive data type vs. Object data type in Java with Examples
Java is known as a statically and strongly typed language because all data types (such as integers, characters, etc.) are predefined. Additionally, every constant or variable must be explicitly declared with a data type.
Data Types in Java
Java’s data types vary in size and in the values they can store. These types are categorized into two main groups:
- Primitive Data Types: Includes
boolean
,char
,int
,short
,byte
,long
,float
, anddouble
. For example,Boolean
is a wrapper class for the primitiveboolean
type. - Non-Primitive Data Types (Reference types): Examples include
String
,Array
, and more.
Effectively understanding and using these data types is crucial for writing efficient and error-free Java code. If you’re aiming to become proficient in Java, it’s worth exploring detailed learning materials or taking courses to deepen your knowledge of data types and other core Java concepts.
Primitive Data Types
Primitive data types represent basic values and lack any special properties. Java supports eight primitive data types, as shown in the table below:
Type | Description | Default | Size | Example Literals | Range |
---|---|---|---|---|---|
1. boolean | Represents true or false | false | 8 bits | true , false | N/A |
byte | 8-bit signed integer | 0 | 8 bits | (none) | -128 to 127 |
char | 16-bit Unicode character | \u0000 | 16 bits | 'a' , '\u0041' , 'β' | 0 to 65,535 |
short | 16-bit signed integer | 0 | 16 bits | (none) | -32,768 to 32,767 |
int | 32-bit signed integer | 0 | 32 bits | -2 , 1 , 2 | -2,147,483,648 to 2,147,483,647 |
long | 64-bit signed integer | 0 | 64 bits | -2L , 0L , 1L | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 32-bit floating-point | 0.0 | 32 bits | 1.23e10f , -1.23e-100f | Up to 7 decimal digits |
double | 64-bit floating-point | 0.0 | 64 bits | 1.2345e300d , 1e1d | Up to 16 decimal digits |
Below is a detailed breakdown of each data type:
1. boolean Data Type: Represents logical values (true
or false
). Actual size depends on the virtual machine implementation.
Syntax:
boolean isAvailable;
2. byte Data Type: An 8-bit signed integer, often used to save memory when working with large arrays.
Syntax:
byte age;
3. short Data Type: A 16-bit signed integer. This is similar to byte
, but used when larger ranges are required.
Syntax:
short population;
4. int Data Type: A 32-bit signed integer and one of the most commonly used data types for numerical values.
Syntax:
int salary;
5. long Data Type: A 64-bit signed integer, suitable for larger numerical values.
Syntax:
long distance;
6. float Data Type: A 32-bit single-precision floating-point, typically used when saving memory is a priority for large floating-point arrays.
Syntax:
long distance;
7. double Data Type: A 64-bit double-precision floating-point, typically the default choice for decimal values.
Syntax
double price;
8. char Data Type: A 16-bit Unicode character. Java uses the Unicode system rather than ASCII, which allows it to represent a wide range of characters.
Syntax:
char initial;
Non-Primitive (Reference) Data Types
Non-Primitive data types store references to memory locations where data is stored. These include strings, arrays, and objects.
1. String: A string is a sequence of characters. In Java, strings are objects, not primitive data types. They can be declared either with or without the new
keyword.
Example:
String message = "Hello, World!";
2. Class: A class in Java is a blueprint used to create objects. A class can contain fields (attributes) and methods to describe the behavior of the objects it represents.
3. Object: An object is an instance of a class, representing real-world entities with states (fields) and behaviors (methods).
4. Interface: An interface defines a set of methods that a class must implement. Interfaces provide a way to achieve abstraction in Java.
5. Array: Arrays are used to store multiple values of the same type in a single variable. Java arrays are objects, and their size is fixed upon creation.
Example:
int[] numbers = {1, 2, 3, 4, 5};
Java Identifiers
In Java, identifiers are used to name various entities like classes, methods, variables, or labels. These names help in uniquely identifying different elements within a Java program.
Example of Java Identifiers
public class Test {
public static void main(String[] args) {
int a = 20;
}
}
In the above code, we have 5 identifiers:
- Test: This is the class name.
- main: This is the method name.
- String: This is a predefined class name.
- args: This is a variable name.
- a: This is also a variable name.
Rules for Defining Java Identifiers
There are specific rules for defining valid Java identifiers. Violating these rules will lead to a compile-time error. These rules are also similar in other programming languages like C and C++.
1. Allowed Characters: Identifiers can contain letters (both uppercase and lowercase), digits ([0-9]), the dollar sign ($), and the underscore (_). Special characters such as @, %, or & are not allowed.
Example: “my@name” is not a valid identifier because @ is not allowed.
2. Starting Character: Identifiers cannot begin with a digit.
Example: “123variable” is invalid.
Case Sensitivity: Java is case-sensitive, so identifiers like MyVariable and myvariable are treated as distinct.
3. Length: There is no restriction on the length of an identifier, but it’s recommended to keep it between 4 and 15 characters for readability.
Reserved Words: Keywords or reserved words in Java cannot be used as identifiers.
Example: int while = 20; is invalid because while is a reserved keyword in Java.
Examples of Valid Identifiers:
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
name123
Examples of Invalid Identifiers:
My Variable
// Contains a space.123name
// Begins with a digit.a+c
// Contains a special character (+
).variable-2
// Contains a hyphen (-
).sum_&_difference
// Contains an ampersand (&
).
Reserved Words in Java
Programming languages reserve certain words to represent built-in functionalities. These are known as reserved words, and in Java, they fall into two categories: keywords (50) and literals (3). Keywords represent functions, while literals represent values. Identifiers are utilized by compilers during various phases of program analysis like lexical, syntax, and semantic analysis.
Here are some reserved words in Java:
Keyword | Keyword | Keyword | Keyword |
---|---|---|---|
abstract | default | package | super |
continue | goto | private | case |
for | public | class | enum |
protected | try | byte | extends |
transient | boolean | double | interface |
assert | do | implements | short |
static | if | strictfp | switch |
throws | break | else | catch |
return | void | long | finally |
char | final | int | synchronized |
volatile | float | native | this |
const | throw | instanceOf | while |
These reserved words cannot be used as identifiers.
int myVariable = 10;
String $myString = "Hello";
double _myDouble = 20.5;
Operators in Java
Java Operators: A Comprehensive Guide
Java provides various operators that are categorized based on their functionality, making it easier to perform tasks like arithmetic operations, logical comparisons, and bitwise manipulations. In this guide, we will explore the different types of Java operators and their uses.
What are Java Operators?
Operators in Java are symbols that trigger specific operations on operands. They simplify complex tasks such as arithmetic operations, logical evaluations, and bitwise manipulations, enhancing the efficiency of the code.
Types of Java Operators
There are several types of operators in Java, each serving a unique purpose:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instanceof Operator
1. Arithmetic Operators: Arithmetic operators perform basic mathematical operations such as addition, subtraction, multiplication, and division.
*
: Multiplication/
: Division%
: Modulus (remainder)+
: Addition–
: Subtraction
Example:
public class ArithmeticOperators {
public static void main(String[] args) {
int x = 15;
int y = 4;
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
}
}
Output:
x + y = 19
x - y = 11
x * y = 60
x / y = 3
x % y = 3
2. Unary Operators: Unary operators operate on a single operand. They are used to increment, decrement, or negate a value.
-
: Unary minus (negates a value)+
: Unary plus (retains the positive value)++
: Increment operator (increases the value by 1)--
: Decrement operator (decreases the value by 1)!
: Logical NOT operator (inverts a boolean value)
Example:
public class UnaryOperators {
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println("Post-Increment: " + (a++));
System.out.println("Pre-Increment: " + (++a));
System.out.println("Post-Decrement: " + (b--));
System.out.println("Pre-Decrement: " + (--b));
}
}
Output:
Post-Increment: 5
Pre-Increment: 7
Post-Decrement: 5
Pre-Decrement: 3
3. Assignment Operators: Assignment operators assign values to variables. You can combine them with other operations to simplify code, such as +=
or -=
.
=
: Assign+=
,-=
,*=
,/=
,%=
: Compound assignment operators
Example:
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
a += 5;
System.out.println("a after += 5: " + a);
a *= 2;
System.out.println("a after *= 2: " + a);
}
}
Output:
a after += 5: 15
a after *= 2: 30
4. Relational Operators: Relational operators compare two values and return a boolean result (true or false).
==
: Equal to!=
: Not equal to<
: Less than>
: Greater than<=
: Less than or equal to>=
: Greater than or equal to
Example:
public class RelationalOperators {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a == b: " + (a == b));
}
}
5. Logical Operators: Logical operators are used to combine multiple boolean expressions.
&&
: Logical AND||
: Logical OR!
: Logical NOT
Example:
public class LogicalOperators {
public static void main(String[] args) {
boolean x = true, y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
}
}
Output:
x && y: false
x || y: true
6. Ternary Operator: The ternary operator is a shorthand for an if-else
statement.
Syntax: condition ? value_if_true : value_if_false
Example:
public class TernaryOperator {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max value: " + max);
}
}
Output:
Max value: 20
7. Bitwise Operators: Bitwise operators operate on binary representations of integers.
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise NOT
Example:
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println("a & b: " + (a & b)); // AND operation
System.out.println("a | b: " + (a | b)); // OR operation
}
}
Output:
a & b: 1
a | b: 7
8. Shift Operators: Shift operators shift bits left or right.
<<
: Left shift>>
: Right shift>>>
: Unsigned right shift
Example:
public class ShiftOperators {
public static void main(String[] args) {
int a = 8;
System.out.println("Left Shift: " + (a << 1));
System.out.println("Right Shift: " + (a >> 1));
}
}
Output:
Left Shift: 16
Right Shift: 4
9. instanceof
Operator:The instanceof
operator checks whether an object is an instance of a class or an interface.
Example:
class Animal {}
class Dog extends Animal {}
public class InstanceOfExample {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Animal); // true
}
}
Output:
true
true
Java Variables
In Java, variables serve as containers to hold data values during the execution of a program. Each variable is assigned a specific data type that determines the kind and amount of data it can store. Essentially, a variable is a reference to a memory location that stores the data.
Variables are crucial for storing and manipulating data in a program, and their values can be altered during program execution. Operations on the variable impact the referenced memory location. It’s important to note that all variables in Java must be declared before use.
Declaring Variables in Java
Variables in Java can be declared by specifying the data type followed by the variable name. The following two key elements must be considered during declaration:
- datatype: The type of data that the variable can hold.
- variable_name: The name given to the memory location.
Example:
// Example of variable declaration:
float interestRate; // Declaring a float variable
int time = 10, speed = 20; // Declaring and initializing integer variables
char grade = 'A'; // Declaring and initializing a character variable
Types of Variables in Java
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables: A local variable is declared within a method, constructor, or block, and its scope is limited to that block or method. Local variables must be initialized before use.
// Example of local variables
public class LocalVariableExample {
public static void main(String[] args) {
int x = 10; // Local variable
String message = "Hello, world!"; // Another local variable
System.out.println("x = " + x);
System.out.println("Message: " + message);
if (x > 5) {
String result = "x is greater than 5"; // Local variable within 'if' block
System.out.println(result);
}
for (int i = 0; i < 3; i++) {
String loopMessage = "Iteration " + i; // Local variable within 'for' loop
System.out.println(loopMessage);
}
}
}
Output:
x = 10
Message: Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables: Instance variables are non-static and are declared outside of any method, constructor, or block. These variables are created when an object is instantiated and are destroyed when the object is destroyed. They can have access specifiers and do not need to be initialized explicitly.
// Example of instance variables
public class InstanceVariableExample {
public String name;
public int age;
public InstanceVariableExample(String name) {
this.name = name; // Initializing instance variable
}
public static void main(String[] args) {
InstanceVariableExample person = new InstanceVariableExample("Alice");
System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age); // Default value for int is 0
}
}
Output:
Name: Alice
Age: 0
3. Static Variables: Static variables are shared across all instances of a class and are declared with the static
keyword. Only one copy of a static variable exists, regardless of how many objects are created.
// Example of static variables
public class StaticVariableExample {
public static String company = "TechCorp"; // Static variable
public static void main(String[] args) {
System.out.println("Company: " + StaticVariableExample.company); // Accessing without object
}
}
Output:
Company: TechCorp
Scope of a Variables
In Java, the scope of a variable refers to the region in the code where the variable is accessible. Java has lexical (static) scoping, meaning the scope of a variable is determined at compile time and is not dependent on the function call stack. The scope rules in Java can be broadly classified into three categories based on where the variables are declared.
1. Member Variables (Class-Level Scope)
2. Local Variables (Method-Level Scope)
3. Block Variables (Loop or Block-Level Scope)
1. Member Variables (Class-Level Scope)
Member variables are declared inside a class but outside any method, constructor, or block. They can be accessed anywhere within the class and can have different access levels (e.g., public
, private
, protected
, or default). Access to member variables outside the class depends on the access modifier used.
Example:
public class Test {
// Member variables
int a; // Default access modifier
private String b; // Private member variable
char c; // Default access modifier
void method1() {
// Member variables can be accessed here
System.out.println(a);
System.out.println(b);
}
int method2() {
return a;
}
}
- Public: Accessible within the class, in subclasses, and outside the class.
- Protected: Accessible within the class and in subclasses but not outside the package.
- Default (no modifier): Accessible within the same package but not outside it.
- Private: Only accessible within the class.
2. Local Variables (Method-Level Scope)
Local variables are declared inside a method or constructor and are only accessible within that method. They must be initialized before use, and their lifetime is limited to the method’s execution. Once the method finishes, local variables are destroyed.
Example:
public class Test {
void method1() {
// Local variable
int x = 10;
System.out.println(x); // Accessible inside the method
}
public static void main(String[] args) {
Test t = new Test();
t.method1();
}
}
3. Block Variables (Loop or Block-Level Scope)
Variables declared inside a block (within curly braces {}
) are only accessible within that block. Once the block is exited, these variables are out of scope and cannot be accessed. This applies to variables declared inside loops or conditionals.
Example of Block-Level Scope:
public class Test {
public static void main(String[] args) {
{
int x = 10; // x is only accessible inside this block
System.out.println(x);
}
// Uncommenting the following line will cause an error
// System.out.println(x); // x is out of scope here
}
}
Loop Variables (Block Scope)
Variables declared inside a loop have scope limited to the loop. They cannot be accessed outside the loop.
Example:
class Test {
public static void main(String[] args) {
for (int x = 0; x < 4; x++) {
System.out.println(x); // x is accessible inside the loop
}
// Uncommenting the following line will result in an error
// System.out.println(x); // x is out of scope here
}
}
If you need to access a loop variable outside the loop, declare it before the loop:
class Test {
public static void main(String[] args) {
int x;
for (x = 0; x < 4; x++) {
System.out.println(x);
}
System.out.println(x); // x is accessible outside the loop
}
}
Output:
0
1
2
3
4
Loop Variable Scope with Overlapping Names
In Java, you cannot declare two variables with the same name within the same scope. However, in languages like C++, it’s possible to have the same variable name in nested scopes, which is not allowed in Java.
Incorrect Example in Java (compilation error):
class Test {
public static void main(String[] args) {
int a = 5;
for (int a = 0; a < 5; a++) { // Error: Variable 'a' is already defined
System.out.println(a);
}
}
}
Output:
Error: variable 'a' is already defined
Valid Example with Loop Variable Declaration After Loop
To avoid such errors, you can declare a variable outside the loop and use it after the loop finishes.
Example:
class Test {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i); // Loop variable i
}
int i = 20; // Declare i after the loop
System.out.println(i); // Access new i outside the loop
}
}
Output:
1
2
3
4
5
6
7
8
9
10
20