2

Programming Structures in Java

In this chapter...

Here are the topics we'll cover

  • Defining Classes and Access Specifiers

  • Comments, Data Types and variables

  • Classes in Java

    Classes is fundamental to object-oriented programming. Here's a basic example of how to define a class in Java

    • We've defined a class named MyClass.
    • It has two fields. myField of int, and anotherField of type String.
    • It has a Constructor MyClass(int myField, String anotherField) that initializes these fields.
    • It has getter and setter methods for accessing and modifying these fields.
    MyClass.java
    public class MyClass {
      // Fields (attributes)
      private int myField;
      private String anotherField;
     
      // Constructor
      public MyClass(int myField, String anotherField) {
        this.myField = myField;
        this.anotherField = anotherField;
      }
     
      // Methods
      public int getMyField() {
        return myField;
      }
     
      public void setMyField(int myField) {
        this.myField = myField;
      }
     
      public String getAnotherField() {
        return anotherField;
      }
     
      public void setAnotherField(String anotherField) {
        this.anotherField = anotherField;
      }
    } 
    • Create an intance of this class and manipulate its fields.
    Main.java
    public class Main {
      public static void main(String[] args) {
        MyClass obj = new MyClass(10, "Hello");
        System.out.println(obj.getMyField());
        System.out.println(obj.getAnotherField());
     
        obj.setMyField(20);
        obj.setAnotherField("World");
     
        System.out.println(obj.getMyField());
        System.out.println(obj.getAnotherField());
      }
    }
    Output
    10
    Hello
    20
    World

    Given examples are just a basic. Classes can have more complex structure, including inheritance, interfaces, and other features of object-oriented programming.

    Modifiers in Java

    Modifier is conceivable to alter classes and systems by utilizing modifiers. There are two classifications of modifiers —

    • Access Modifiers: public, default, protected and private
    • Non-access Modifiers: static, final and abstract.

    Access Modifiers

    Java gives various access modifiers to set access levels for classes, fields, variables, routines and constructors. It is also known as Access Specifiers. The four right to gain access are —

    • Private: visible to the class.
    • Default: visible to the bundle. No modifiers are required
    • Protected: visible to all subclasses and package.
    • Public: visible to the world.
    PrivateNo ModifierProtectedPublic
    Same classYesYesYesYes
    Same package subclassNoYesYesYes
    Same package non-subclassNoYesYesYes
    Different package subclassNoNoYesYes
    Different package non-subclassNoNoNoYes

    Here's the example of access modifier.

    MyClass.java
    package mypackage;
     
    public class MyClass {
      public int publicField;
      protected int protectedField;
      int defaultField;    // package-private
      private int privateField;
     
      public MyClass() {
        // Constructor
      }
     
      public void publicMethod() {
        // Method with public access
      }
     
      protected void protectedMethod() {
        // Method with package-private access
      }
     
      private void privateMethod() {
        // Method with private access
      }
    }
    • publicField is accessible from any class.
    • protectedField is accessible within its package and by subclasses.
    • defaultField is accessible within its package.
    • privateField is accessible only within its own class.
    • publicMethod(), protectedField(), and defaultField() have similar access levels as thir corresponding fields.
    • privateMethod() is accessible only within its own class.

    Non Access Modifiers

    Java gives various non-access modifiers to attain numerous other usefulness.

    • Static: The static modifier for making class variables and methods.
    • Final: The final modifier for concluding the executions of classes, variables and methods.
    • Abstract: This modifier is used for creating abstract methods and classes.
    • Volatile and Synchronized: These modifiers and typically used for threads.

    Static Members

    The class level members which have static keyword in their definition are called static members.Static members are those that belong to the class itself, rather than being associated with an instance of the class. Let's explore the different types of static members —

    • Static Methods: These are the methods declared with the static keyword. Like static variables, static methods belong to the class rather than to instances of the class. They can be called direcly using the class name without creating an object of the class.
    public class MyClass {
      static void myStaticMethod() {  // static method
        System.out.println("This is a static method.");
      }
    }
    • Static Variables (Class Variables): These are variables declared with the static keyword. They are shared among all instances of the class. Static variables are initialized only once, at the start of the execution, and retain their values throughout the program's lifetime.
    public class MyClass {
      static int count = 0;
    }
    • Static Blocks: These are blocks of code enclosed in curly braces {} and preceded by the static keyword. They are executed only once when the class is loaded into memory. Static blocks are typically used to initialize static variables.
    public class MyClass {
      static {
        System.out.println("Static blocks is executed.");
      }
    }
    • Static Nested Classes: These are nested classes thet are declared as static. They can access only static members of the outer class.
    public class OuterClass {
      static class StaticNestedClass {
        void display() {
          System.out.println("Static nested class");
        }
      }
    }

    Final Members

    The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable i.e. impossible to inherit or override. Final keyword is the part of modifier which are already studed. The final keyword can be applied to variables, methods, and classes, each with its own significance.

    • Final Variables (Constants): When applied to a variable, the final keyword indicates that the variable's value cannot be changed after it has been initialized. Final variables are essentially constants and must be initialized exactly once, either at the time of declaration or within a constructor. Once initialized, their values cannot be modified.
    public class MyClass {
      final int MY_CONSTANT = 10;   // final variable
    }
    • Final Methods: When applied to a method, the final keyword indicates that the method cannot be overridden by subclasses. This means that subclasses cannot provide a different implementation of the final method. Final methods are typically used to enforce certain behaviors in a class hierarchy.
    public class ParentClass {
      public final void finalMethod() { // final method
        // method implemntation
      }
    }
     
    public class ChildClass extends ParentClass {
      /* this will result in a compilation error because 
      finalMethod() cannot be overridden. */
    }
    • Final Classes: When applied to a class, the final keyword indicates that th class cannot be subclassed. This means that no other class can inherit from a final class. Final classes are often used when a class is desiged to be immutable or when its behavior should not be altered or extended.
    final public class FinalClass { // final class
      // class members and methods
    }

    Comments in Java

    Just an in the case of C++ and C, Java supports two types of comments namely, single line comments and multi-line comments. The syntax for these types of comments are as follows —

    • Single line comment
    //<comment>
    • Multiple line comment
    /*<commnet 
    line 2
    .
    .
    line n>*/

    All characters that exist in the comments region are simply ignored by the Java compiler.

    Any line that is only composed of whitespace characters or comments is considered a blank line. These lines are just ignored by the compiler and are not included in the executable.

    Data Types

    Data types specify the type of data that can be stored in a variable. Java supports several built-in data types, which can be categorised into two main categories —

    • Primitive data types and
    • Referance data types

    Primitive data types: These are basic data types provided by Java.

    • Numeric types: byte, short, int, float, double
    • Text types: char
    • Logical type: boolean
    Example.java
    int myNum = 7;                // Integer
    float myFloatNum = 8.74f;     // Floating Point Number
    char myChar = 'P';            // Character
    boolean myBool = true;        // Boolean
    String myText = "Hello";      // String

    There are mainly eight types of primitive data types in Java programming —

    Data TypeCharacteristicsRange
    byte8 bit signed integer-128 to 127
    short16 bit signed integer-32768 to 32767
    int32 bit signed integer2E-31 to 2E+30
    long64 bit signed integer2E-63 to 2E+62
    float32 bit floating point number± 1.4E-45 to ± 3.4028235E+38
    double64 bit floating point number± 4.9E-324 to ± 1.7976931348623157E+308
    boolean1 bit true or falseNA
    char16 bit, UnicodeUnicode character, \u0000 to \uFFFF can mix with hexadecimal number.

    Referance data types: These are non-primitive data types that include objects, arrays, and user-defined types.

    Variables in Java

    Manipulation of data is performed with the help of variables. Data is stored in the memory and a named referance to this memory location is called a variable. Any identifier is declared as a variable by preceding it with a keyword var. Sample declaration of a variable is.

    var result;
    var result1 = 0;
    var result2 = 23 * 4 + 6;

    Certain rules have to be followed while naming variables. These are the following rules —

    • A variable name can be a combination of numbers and characters.
    • A variable name cannot start with a number.
    • The only special characters allowed in variable names is underscore _ and dollar sign $.
    • There should not be any whitespace in the variable name. e.g. result value is not allowed.
    • JavaScript keywords are reserved and cannot be used.

    Another convention used in JavaScript is to name variables such that th e first letter of the variable name is lowercase.

    Next Up

    3: Operators in Java

    Let's know about different types of Operators in Java.

    Start Chapter 3

    Help us