Pages

Saturday, May 25, 2024

Operators in Java

Java operators with examples:

1. Arithmetic Operators:

+ (Addition): Adds two operands.

int a = 5;

int b = 3;

int sum = a + b; // sum will be 8


- (Subtraction): Subtracts the second operand from the first.

int difference = a - b; // difference will be 2


* (Multiplication): Multiplies two operands.

int product = a * b; // product will be 15


/ (Division): Divides the first operand by the second. Be aware of integer division which truncates decimals.

int quotient = a / b; // quotient will be 1 (integer division)

double dQuotient = (double) a / b; // dQuotient will be 1.6666... (cast to double for decimal result)


% (Modulo): Returns the remainder after division.

int remainder = a % b; // remainder will be 2 (5 divided by 3 leaves a remainder of 2)


2. Assignment Operators:

= (Assignment): Assigns a value to a variable.

int x = 10;

Compound assignment operators (e.g., +=, -=, *=, /=): Combine assignment with the specified operation.

x += 5; // equivalent to x = x + 5; (x becomes 15)

x *= 2; // equivalent to x = x * 2; (x becomes 30)


3. Relational Operators:

== (Equal to): Checks if two operands are equal.

boolean isEqual = a == b; // isEqual will be false

!= (Not equal to): Checks if two operands are not equal.

boolean isNotEqual = a != b; // isNotEqual will be true

< (Less than): Checks if the first operand is less than the second.

boolean isLessThan = a < b;  // isLessThan will be false

> (Greater than): Checks if the first operand is greater than the second.

boolean isGreaterThan = a > b; // isGreaterThan will be true

<= (Less than or equal to): Checks if the first operand is less than or equal to the second.

boolean isLessOrEqualTo = x <= 30; // isLessOrEqualTo will be true (x is 30)

>= (Greater than or equal to): Checks if the first operand is greater than or equal to the second.

boolean isGreaterThanOrEqualTo = x >= 20; // isGreaterThanOrEqualTo will be true (x is 30)


4. Logical Operators:

&& (Logical AND): Returns true if both operands are true, false otherwise.

boolean isEven = (x % 2 == 0) && (x > 0); // isEven will be false (x is even but not greater than 0)

|| (Logical OR): Returns true if at least one operand is true, false otherwise.

boolean isPositive = (x > 0) || (x == 0); // isPositive will be true (x is positive)

! (Logical NOT): Inverts the logical state of the operand.

boolean isNegative = !isPositive; // isNegative will be false (x is positive)l

These are just a few examples. Java offers a variety of operators for different purposes.

What is Java identifier ?

In Java, an identifier is a fancy name for a custom label you give to things like variables, methods, classes, and even labels within your code. These labels are critical for differentiating between different parts of your program and and and and making your code readable.

Here's what makes a valid Java identifier:

Characters: Identifiers can only contain letters (uppercase and lowercase), digits (0-9), the dollar sign ($), and the underscore (_).

Starting character: The first character of an identifier must be a letter or one of the special characters ($ or _). Digits cannot be the first character.

Case sensitivity: Java identifiers are case-sensitive. This means that myVariable and MyVariable are considered different identifiers.

No keywords: You cannot use reserved keywords (like int, for, if, etc.) as identifiers.

Here are some examples of valid Java identifiers:

name

customerAge

total_cost

$temporaryValue (using dollar sign)

And some examples of invalid identifiers:

1stPlace (cannot start with a number)

if (reserved keyword)

my-variable (hyphens are not allowed)

By following these rules, you can create clear and meaningful identifiers that improve the readability and maintainability of your Java code.

Tuesday, May 7, 2024

Data Types in Java

 In Java, there are several data types, which can be categorized into two main categories: primitive data types and reference data types.


1. Primitive Data Types: These are basic data types predefined by the language and are not objects. They store simple values.

a. Numeric Types:

  • Integer Types: byte, short, int, long
  • Floating-point Types: float, double

b. Character Type: char

c. Boolean Type: boolean

2. Reference Data Types: These are objects that are created using predefined classes or user-defined classes. They hold references to the memory location where the data is stored.

Now, let's represent this information with a diagram:



                                      

In this diagram, you can see the two main categories of data types in Java: primitive data types and reference data types. Each category contains specific data types with their respective subtypes.

Saturday, April 13, 2024

Basic terminologies in Java

 

  1. Class: A blueprint for creating objects, defining attributes (fields) and behaviors (methods) that objects of that type will have.

  2. Example :

  3. public class Car { // Class definition String color; int year; // Constructor public Car(String color, int year) { this.color = color; this.year = year; } // Method public void drive() { System.out.println("The car is driving."); } }


  4. Object: An instance of a class. It's a concrete realization of the class blueprint, with its own set of attributes and behaviors.

  5. Example :

  6. Car myCar = new Car("Red", 2022); // Creating an object of the Car class


  7. Method: A block of code that performs a specific task. Methods are defined within a class and can be called to execute their functionality.

  8. Example :

  9. public void drive() { System.out.println("The car is driving."); }


  10. Constructor: A special type of method that is called when an object is instantiated. It is used to initialize the object's state.

  11. Example :

  12. public Car(String color, int year) { this.color = color; this.year = year; }


  13. Instance Variables (Fields): Variables declared within a class but outside of any method. They represent the state of an object.

  14. Example :

  15. String color; int year;


  16. Instance Method: A method that operates on an instance of a class. It can access and modify the instance variables of the class.

  17. Example :

  18. public void drive() { System.out.println("The car is driving."); }


  19. Inheritance: A mechanism in which a new class inherits properties and behaviors from an existing class (superclass). It promotes code reuse and allows for the creation of hierarchical relationships between classes.

  20. Example :

  21. public class SportsCar extends Car { // Additional fields and methods specific to SportsCar }


  22. Polymorphism: The ability of objects of different classes to be treated as objects of a common superclass. It allows methods to be called on objects without knowing their specific type at compile time.

  23. Example :

  24. Car myCar = new SportsCar(); // Polymorphism


  25. Encapsulation: The bundling of data (instance variables) and methods that operate on the data into a single unit (class). It hides the internal state of an object and only exposes the necessary functionalities.

  26. Example :

  27. private String model; // Encapsulated field public void setModel(String model) { // Encapsulated method this.model = model; }


  28. Abstraction: The process of hiding the implementation details of a class and only showing its essential features. It allows for the creation of user-defined data types with specific behaviors.

  29. Example :

  30. public abstract class Vehicle { public abstract void drive(); // Abstract method }


  31. Interface: A reference type in Java that defines a set of abstract methods. Classes can implement interfaces, thereby agreeing to provide concrete implementations for those methods.

  32. Example :

  33. public interface Drivable { void drive(); }


  34. Package: A namespace that organizes a set of related classes and interfaces. It helps in avoiding naming conflicts and provides better modularization of code.

  35. Example :

  36. package com.example.myproject;


  37. Access Modifiers: Keywords such as public, private, protected, and default that control the accessibility of classes, variables, and methods in Java.

  38. Example :

  39. public class Car { // Public access modifier private String color; // Private access modifier protected int year; // Protected access modifier int price; // Default (package-private) access modifier }


  40. Static Keyword: A keyword used to declare members (variables and methods) that belong to the class rather than to any specific instance. Static members can be accessed using the class name itself.

  41. Example :

  42. public static double PI = 3.14; // Static variable public static void printMessage() { // Static method System.out.println("Hello!"); }


  43. Exception Handling: The process of handling runtime errors or exceptional conditions in a program. Java provides keywords such as try, catch, finally, and throw for exception handling.

  44. Example :

  45. try { // Code that may throw an exception } catch (Exception e) { // Handling the exception } finally { // Code that runs regardless of whether an exception occurred or not }