write a ‘java’ program to display characters from ‘a’ to ‘z’

 Here is a simple program that prints characters from a to Z

  1. public class DisplayAlphabets {
  2.     public static void main(String[] args) {
  3.         for (char c = 'a'; c <= 'z'; c++) {
  4.             System.out.print(c + " ");
  5.         }
  6.     }
  7. }

This program uses a for loop to iterate through the characters from 'a' to 'z'. The loop variable "c" is initialized to 'a' and incremented by 1 on each iteration until it reaches 'z'. Inside the loop, the current character is printed using the System.out.print() method. The " " at the end of the print statement will print the character followed by a space.

Alternatively, we can use the Character.toChars(int) method to convert the int value to a char and use the for loop to iterate from 97 to 122.

java program to print characters from a to z


This will also display the same output as the first example: "a b c d e f g h i j k l m n o p q r s t u v w x y z".
Note that, in both examples, the alphabets will be printed in lowercase. If we want to print uppercase alphabets, you can use 'A' to 'Z' in the for loop or use 65 to 90 in the Character.toChars(int) method.

We can also use the java.util.stream.IntStream to display characters from 'a' to 'z'.
 Here is an example of how you can use IntStream to display characters from 'a' to 'z':

public class DisplayAlphabets {
    public static void main(String[] args) {
        IntStream.rangeClosed('a', 'z').mapToObj(c -> (char) c).forEach(System.out::print);
    }
}

This program uses the IntStream.rangeClosed() method to create a stream of ints from the ASCII value of 'a' to the ASCII value of 'z'. Then it uses the mapToObj() method to convert the ints to chars, and finally the forEach() method to print each character.

we can also use the java.util.stream.IntStream to display characters from 'A' to 'Z' using the same approach. Here is an example of how you can use IntStream to display characters from 'A' to 'Z':


public class DisplayAlphabets {
    public static void main(String[] args) {
        IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).forEach(System.out::print);
    }
}

This will print the uppercase alphabets : "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".

It's worth noting that, in all examples the alphabets will be displayed in a single line, if you want to display them in separate lines, you can modify the System.out.print() method to System.out.println().

How to print array in java

 To print an array in Java, you can use a for loop to iterate through the array and print each element. Here is an example of how to print an array of integers:

Here is a simple program that explains how to print an array of integers in java

  1. int[] myArray = {1, 2, 3, 4, 5};
  2. for (int i = 0; i < myArray.length; i++) {
  3.     System.out.print(myArray[i] + " ");
  4. }

This will print the following output: "1 2 3 4 5".

Alternatively:  Arrays.toString(myArray) and directly print the array.

System.out.println(Arrays.toString(myArray));

This will also print the array in same format "1 2 3 4 5"

We can also use the enhanced for loop (also known as the "for-each" loop) to print an array in Java. This type of loop automatically iterates through each element in the array, making it more concise and easier to read than a traditional for loop:

  1. for (int element : myArray) {
  2.     System.out.print(element + " ");
  3. }

This will also print the same output as the previous example "1 2 3 4 5".

When printing arrays of other types, such as Strings or objects, we can use the same approach. For example, if you have an array of Strings, you can use the enhanced for loop to print each element:

java print array

This will print the following output: "Hello World".

It's worth noting that, the Arrays.toString() method will work for all types of arrays, including arrays of objects, it will call the toString() method of each element in the array.

In case of the custom class objects, you may need to override the toString() method of the class.

Another way to print an array in Java is to use the Arrays.deepToString() method if the array is a multi-dimensional array. This method is similar to Arrays.toString(), but it can handle multi-dimensional arrays and it will recursively call itself for each sub-array. Here's an example of how to use Arrays.deepToString() to print a 2D array:

  1. int[][] my2DArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  2. System.out.println(Arrays.deepToString(my2DArray))

This will print the following output: "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]".

we can also use the java.util.Arrays.stream() method to print an array in Java 8 and later versions. This method returns a stream of the array's elements, which can then be passed to various stream operations such as forEach(). Here's an example of how to use Arrays.stream() to print an array:

int[] myArray = {1, 2, 3, 4, 5};

Arrays.stream(myArray).forEach(System.out::print);

This will also print the same output as the previous examples "1 2 3 4 5".

It's worth noting that when you use the Arrays.stream() method to print an array, it does not add any spaces or newlines between the elements, unlike the for loop and enhanced for loop. If we want to add spaces or newlines, you can use the map() method to transform each element into a string, and then use the forEach() method to print each string.

Instance variable in java

Instance Variables in Java: The Complete Guide

Instance variables are an important topic in Java programming. They are responsible for defining the characteristics of an object and preserving its state for its whole life cycle. In this blog, we will discuss instance variables in great detail, their different characteristics, usage, and best practices.

What Are Instance Variables?

An instance variable is a variable defined in a class (as opposed to a static variable). Since each object of a class has its own copy of instance variables, changes made to such variables in one object do not have any impact on another object of the same class.

Instance Variables:

  • Defined within a class but out of any method, block, or constructor.
  • Every instance has its own copy of instance variables.
  • Gets a default value until you assign it.
  • Can take any access modifier (private, protected, public, or default).
  • They are not shared between entities, unlike static variables.

Syntax of Instance Variables

class Car { String brand; int speed; // Instance variables }

Here, brand and speed are instance variables. Each instance of the Car class will have its own brand and speed values.

Default values of instance variables:

If an instance variable is not initialized, Java assigns default values as shown below:

Data Type Default Value
int 0
double 0.0
boolean false
char '\u0000' (null character)
String (or Other objects) null

Example:

  1. class Example {
  2.     int number; // default value is 0
  3.     String text; // default value is null
  4.     
  5.     void display() {
  6.         System.out.println("Number: " + number);
  7.         System.out.println("Text: " + text);
  8.     }
  9.     
  10.     public static void main(String[] args) {
  11.         Example obj = new Example();
  12.         obj.display();
  13.     }
  14. }

    Instance Variables and Access Modifiers

    Instance variables can have different access modifiers, which control their visibility and accessibility.

    Private Instance Variables

    • Accessibility: same class only.
    • Use getters and setters to provide access.
    1. class Person {
    2.     private String name;
    3.     
    4.     public String getName() {
    5.         return name;
    6.     }
    7.     
    8.     public void setName(String name) {
    9.         this.name = name;
    10.     }
    11. }

      Public Instance Variables

      • Accessible from anywhere in the program.
      • Not recommended, as it violates encapsulation.
      class Animal { public String species; }

      Protected Instance Variables

      • Available within the same package and to subclasses.
      class Vehicle { protected int speed; }

      Default (Package-Private) Instance Variables

      • Only accessible within the same package.
      class Employee { String designation; // Default access modifier }

      Using Instance Variables

      Instance variables are used to store object-specific data.

      Example java program :

      1. class Student {
      2.     String name;
      3.     int age;
      4.     
      5.     // Constructor to initialize instance variables
      6.     public Student(String name, int age) {
      7.         this.name = name;
      8.         this.age = age;
      9.     }
      10.     
      11.     void display() {
      12.         System.out.println("Name: " + name + ", Age: " + age);
      13.     }
      14.     
      15.     public static void main(String[] args) {
      16.         Student s1 = new Student("Alice", 20);
      17.         Student s2 = new Student("Bob", 22);
      18.         
      19.         s1.display();
      20.         s2.display();
      21.     }
      22. }

          Output:

          Name: Alice, Age: 20 Name: Bob, Age: 22

          Each Student object holds its own copy of name and age.


          Instance Variable vs Static Variable

          Feature Instance Variables Static Variables
          Ownership Object specific Class specific
          Memory Allocation At object creation At class loading
          Access Requires an object Accessed via class name

          Example

          1. class Company {
          2. static String companyName = "Tech Corp"; // Static variable
          3. String employeeName; // Instance variable
          4. }

            Best Practices for Instance Variables

            1. Encapsulation: Use the private access modifier and access it through getters and setters.
            2. Meaningful Names: Assign well-defined names to variables.
            3. Initialize in Constructor: Ensure instance variables are initialized in constructors.
            4. Limit Visibility: Use private or protected unless absolutely necessary.
            5. Lower Memory Usage: Use only the necessary instance variables in memory-sensitive applications.

            Instance variables are critical components of Java's object-oriented programming paradigm. They enable objects to store their own independent state and data. Understanding how they work and following best practices allows you to write clean, efficient, and maintainable Java code.

            Want to learn more about Java concepts? Let us know in the comments!

            Ascii values in c

             In C, you can use the int data type to represent ASCII values. Each character in the ASCII table is assigned a unique number between 0 and 127. To get the ASCII value of a character, you can simply cast it to an int. Here's an example:

            char c = 'A';

            int asciiValue = (int)c;

            printf("The ASCII value of '%c' is %d\n", c, asciiValue);

            This will output:

            The ASCII value of 'A' is 65

            Alternatively you can also use the 'C' library function (int)c to get the ASCII value of a character.

            char c = 'A';

            int asciiValue = (int)c;

            printf("The ASCII value of '%c' is %d\n", c, asciiValue);

            will give you the same output.

            You can also find the ASCII value of a character with a function like getchar(), that returns an int value of the char type that it reads from the keyboard, or with a function like scanf() that reads a character input.

            Additionally, if you want to find the ASCII value of a string, you can use a for loop to iterate through each character of the string and then get the ASCII value of each character by casting it to an int.



            Java enum constructor

            In Java, an enumeration is a special kind of class that represents a fixed number of predefined values. The values are defined as enum constants, which are static and final fields of the enumeration.

            When you define an enum, you can also define a constructor for it, which is called when each enum constant is created. The constructor is passed the values of the constant's fields and can use those values to initialize the constant.

            Here's an example of an enumeration called Size with a constructor that takes a single String argument:


            In this example, the Size enumeration has four constants: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. Each constant has an associated abbreviation, which is passed to the constructor when the constant is created. The constructor sets the value of the abbreviation field to the passed-in value.

            You can call the constructor explicitly or it will be called automatically when enum constants are created, so the following code:

            Size s = Size.SMALL;

            is equivalent to

            Size s = new Size("S");

            When you define constructors for your enum, it is a best practice to make them private. So that no other classes can create an instance of your Enum. This way you can only use the predefined values of the Enum and not create any new value on runtime.

            jstl if else string comparison

             In JavaServer Pages (JSP), the JSTL (Java Standard Tag Library) provides a set of tags that you can use to perform common tasks, such as iterating over a collection of data, performing conditional logic, and formatting text. The JSTL if tag is used to perform conditional logic in a JSP page. The if tag evaluates a boolean expression, and if the expression evaluates to true, the content inside the if tag is rendered to the response. If the expression evaluates to false, the content inside the if tag is not rendered.

            JSTL (JavaServer Pages Standard Tag Library) is a collection of tags that provide common functionality when working with JSPs (JavaServer Pages). One of the tags provided by JSTL is the <c:if> tag, which can be used to conditionally include content in a JSP based on a Boolean expression.

            Here's an example of how you might use the JSTL if tag to conditionally render content in a JSP page:

            <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

            <c:if test="${someCondition}">

              <p>This content will be displayed if someCondition is true</p>

            </c:if>

            The JSTL if tag also provides an else branch which will be executed if the test conditions return false

            jstl if else


            Additionally, you can also use c:choose, c:when, c:otherwise tags for conditions where you have more than one test case.


            <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

            <c:choose>
              <c:when test="${someCondition}">
                <p>This content will be displayed if someCondition is true</p>
              </c:when>
              <c:when test="${anotherCondition}">
                <p>This content will be displayed if anotherCondition is true</p>
              </c:when>
              <c:otherwise>
                <p>This content will be displayed if neither someCondition nor anotherCondition is true</p>
              </c:otherwise>
            </c:choose>
            Please note that to use the above-mentioned tags, you need to include JSTL core library in your project.

            C program to print table of 2 using for loop


            #include <stdio.h>

            int main() {

                int i;

            The first line includes the standard input/output header file, which is needed for the printf function used later in the program.

            The main function is the entry point for the program. It is the first function that is executed when the program runs.

            The next line declares a variable i of type int. This variable will be used as the loop counter in the for loop.

                for (i = 1; i <= 10; i++) {

                    printf("2 * %d = %d\n", i, 2 * i);

                }

            This is the for loop. It starts with the for keyword, followed by parentheses that contain three statements separated by semicolons:

            The initialization statement i = 1 sets the value of i to 1 before the loop starts.

            The loop condition i <= 10 specifies that the loop will continue as long as the value of i is less than or equal to 10.

            The iteration statement i++ increments the value of i by 1 after each iteration of the loop.

            Inside the loop, the printf function is used to print a string to the console. The string contains two %d format specifiers, which are placeholders for two integer values that will be printed. The first %d is replaced by the value of i, and the second %d is replaced by the result of 2 * i. The \n at the end of the string is a newline character that causes the output to be printed on a new line.

            Finally, the return 0; statement at the end of the main function indicates that the program has completed successfully.

            Select Menu