Java Rules for creating a class, Data types and Static variable

java dev.to

Rules for creating a class

=> Using class keyword to create a class.

public class Home
{

}
Enter fullscreen mode Exit fullscreen mode

=> Give a class name meaningful (template).

=> Class name must start with Uppercase.

=> No special characters allowed except (_) underscore and ($) dollor symbol.

=> No space allowed inbetween class names.

Data types in java

Java data types define the type of data a variable can store in a program. They are categorized into two types

  1. Primitive data types
  2. Non primitive data types.

=> PRIMITIVE DATA TYPES : Store simple values directly in memory.It's categorized into two types Numeric and Non numeric type.

NUMERIC TYPE :

  • byte: 1 byte (8 bits). Range from -128 to 127. Used to save memory in large arrays.

  • short: 2 bytes (16 bits). Range from -32,768 to 32,767. Used for moderate numbers where memory is tight.

  • int: 4 bytes (32 bits). Range from -2.14 billion to 2.14 billion. This is the default type for whole numbers.

  • long: 8 bytes (64 bits). Extremely wide numerical range.

  • float: 4 bytes (32 bits). Sufficient for 6 to 7 decimal digits of precision.

  • double: 8 bytes (64 bits). Provides up to 15 decimal digits of precision. This is the default type for decimal numbers in Java.

NON NUMERIC TYPE

  • char: 2 bytes (16 bits). Stores a single character enclosed in single quotes (e.g., char grade = 'A';).

  • boolean: Stores only two possible values: true or false. Typically used for conditional flags and decision logic.

=> NON PRIMITIVE DATA TYPES: Store memory references to objects.

  • String: Represents an immutable sequence of characters enclosed in double quotes (e.g., String name = "Alice";).

  • Arrays: Collections of multiple elements of the data type grouped under a single name (e.g., int[] scores = {90, 85, 88};).

  • Classes: Custom user-defined blueprints that combine attributes (variables) and behaviors (methods) into unique entities.

Static variable :

=> In Java, when a variable is declared with the static keyword.

=> Then, a single variable is created and shared among all the objects at the class level.

=> Static variables are, essentially, global variables.

Key Characteristics :

  • Class-Level: We can create static variables at the class level only.

  • Accessed through Class Name: Static variables can be called directly with the help of a class only.

  • Single Copy: Every object of the class accesses and shares the exact same memory location.

  • Global Availability: Changes made to a static variable by one object are instantly visible to all other objects

public class Mobile
{
static int price = 23000;
static String name = "Vivo T5X 5g";

public static void main(String [] args){

System.out.println(Mobile.name);
System.out.println(Mobile.price);

}
}

Enter fullscreen mode Exit fullscreen mode

OUTPUT :

Source: dev.to

arrow_back Back to Tutorials