PeakNotes - Your Ultimate Resource for Coding Tips and Tutorials

BCA-S403: JAVA Programming

 


          BCA-S403: JAVA Programming

UNIT-I

Introduction to Java: Bytecode, features of Java, data types, variables and arrays, operators, control

statements.

Objects & Classes: Object Oriented Programming, defining classes, static fields and methods, object

construction

UNIT-II

Inheritance: Basics, using super, method overriding, using abstract classes, using final with inheritance.

Packages and Interfaces: Defining a package, importing package, defining an interface, implementing

and applying interfaces.

 

·        Bytecode

Bytecode in Java

Bytecode is one of the most common java programming terms which is used more often while learning java programming. As a beginner sometime it's quite confusing to understand what exactly the bytecode is. In this tutorial let's understand what bytecode is in simple terms and also the differences with some other type of programming terms to make it more clear.

What is bytecode in Java

In java when you compile a program, the java compiler(javac) converts/rewrite your program in another form/language which we call as bytecode. The .class file that is generated after compilation is nothing else, it's basically the bytecode instructions of your program. The word bytecode and .class are used interchangeably, so if someone says bytecode, it simply means the .class file of program.

 


At runtime Java virtual machine takes bytecode(.class) as an input and convert this into machine(windows, linux, macos etc) specific code for further execution. So bytecode in java is just an intermediate representation/code of your java program in the form of .class file. We call it intermediate representation/code because it lies between source and machine code.

 Source code → Bytecode → Machine code

 

 

·        Features/Characteristics of Java

Java has many important features that makes java one of the most useful programming language today. As the time passes, java has emerged as one of the most preferable programming language for different types of need. This tutorial will cover some of it's features which makes it one of the most useful language.


 

 

Java is secure

Java program cannot harm other system thus making it secure. 

Java provides a secure means of creating Internet applications.

Java provides secure way to access web applications.

 

Java is portable

Java programs can execute in any environment for which there is a Java run-time system.(JVM)

Java programs can be run on any platform (Linux,Window,Mac) .

Java programs can be transferred over world wide web (e.g applets)

 

Java is object-oriented

Java programming is object-oriented programming language.

 Like C++ java provides most of the object oriented features.

Java is pure OOP. Language. (while C++ is semi object oriented)

 

Java is robust

Java encourages error-free programming by being strictly typed and performing run-time checks.

 

Java is multithreaded

Java provides integrated support for multithreaded programming.

 

Java is architecture-neutral

Java is not tied to a specific machine or operating system architecture.

Machine Independent i.e Java is independent of hardware .

 

Java is interpreted

Java supports cross-platform code through the Java bytecode.

use of Bytecode can be interpreted on any platform by JVM.

 

Java’s performance

Bytecodes are highly optimized.

JVM can executed them much faster

 

Java is distributed

Java was designed with the distributed environment.

Java can be transmit,run over internet.

 

·        variables

What is a Variable in Java?

Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold. Variable is a memory location name of the data. The Java variables have mainly three types : Local, Instance and Static.

In order to use a variable in a program you to need to perform 2 steps

  1. Variable Declaration
  2. Variable Initialization

Variable Declaration:

To declare a variable, you must specify the data type & give the variable a unique name.


Examples of other Valid Declarations are

int a,b,c;

 

float pi;

 

double d;

 

char a;

Variable Initialization:

To initialize a variable, you must assign it a valid value.

Example :

int a=2,b=4,c=6;

 

float pi=3.14f;

 

double do=20.22d;

 

char a=’v’;

Types of variables

In Java, there are three types of variables:

  1. Local Variables
  2. Instance Variables
  3. Static Variables

1) Local Variables

Local Variables are a variable that are declared inside the body of a method.

2) Instance Variables

Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables.

3) Static Variables

Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables.

Example: Types of Variables in Java

class Guru99 {

    static int a = 1; //static variable 

    int data = 99; //instance variable 

    void method() {

        int b = 90; //local variable 

    }

}

 

 

·        What is Data Types in Java?

Data Types in Java are defined as specifiers that allocate different sizes and types of values that can be stored in the variable or an identifier. Java has a rich set of data types. Data types in Java can be divided into two parts :

  1. Primitive Data Types :- which include integer, character, boolean, and float
  2. Non-primitive Data Types :- which include classes, arrays and interfaces.



Primitive Data Types

Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with other primitive values.

There are 8 primitive types: byte, short, int, long, char, float, double, and boolean

Integer data types

byte (1 byte)

short (2 bytes)

int (4 bytes)

long (8 bytes)


Floating Data Type

float (4 bytes)

 

double (8 bytes)

Textual Data Type

char (2 bytes)

Logical

boolean (1 byte) (true/false)

Data Type

Default Value

Default size

byte

0

1 byte

short

0

2 bytes

int

0

4 bytes

long

0L

8 bytes

float

0.0f

4 bytes

double

0.0d

8 bytes

boolean

false

1 bit

char

‘\u0000’

2 bytes

Points to Remember:

  • All numeric data types are signed(+/-).
  • The size of data types remain the same on all platforms (standardized)
  • char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports internationalization. UNICODE is a character set which covers all known scripts and language in the world

 

 

 

·        Array

Array in java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. 

·        In Java, all arrays are dynamically allocated. (discussed below)

·        Arrays are stored in contiguous memory [consecutive memory locations].

·        Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.

·        A Java array variable can also be declared like other variables with [] after the data type.

·        The variables in the array are ordered, and each has an index beginning with 0.

·        Java array can also be used as a static field, a local variable, or a method parameter.

·        The size of an array must be specified by int or short value and not long.

·        The direct superclass of an array type is Object.

·        Every array type implements the interfaces Cloneable and java.io.Serializable

·        This storage of arrays helps us randomly access the elements of an array [Support Random Access].

·        The size of the array cannot be altered(once initialized).  However, an array reference can be made to point to another array.

 

 

Declaring Array Variables

 

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable –

 In Java, here is how we can declare an array.

dataType arrayName[];

 

• dataType - it can be primitive data types like int, char, double, byte, etc.

• arrayName - it is an identifier

For example-

double data[];

 

·        Control statement

Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

  1. Decision Making statements
    • if statements
    • switch statement
  2. Loop statements
    • do while loop
    • while loop
    • for loop
    • for-each loop
  3. Jump statements
    • break statement
    • continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below.

  1. Simple if statement
  2. if-else statement
  3. if-else-if ladder
  4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

1.      if(condition) {    

2.      statement 1//executes when condition is true   

3.      }    

 

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

freestar

1.      if(condition) {    

2.      statement 1//executes when condition is true   

3.      }  

4.      else{  

5.      statement 2//executes when condition is false   

6.      }  

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

1.      if(condition 1) {    

2.      statement 1//executes when condition 1 is true   

3.      }  

4.      else if(condition 2) {  

5.      statement 2//executes when condition 2 is true   

6.      }  

7.      else {  

8.      statement 2//executes when all the conditions are false   

9.      }  

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

Syntax of Nested if-statement is given below.

1.      if(condition 1) {    

2.      statement 1//executes when condition 1 is true   

3.      if(condition 2) {  

4.      statement 2//executes when condition 2 is true   

5.      }  

6.      else{  

7.      statement 2//executes when condition 2 is false   

8.      }  

9.      }  

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.

Points to be noted about switch statement:

  • The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
  • Cases cannot be duplicate
  • Default statement is executed when any of the case doesn't match the value of expression. It is optional.
  • Break statement terminates the switch block when the condition is satisfied.
    It is optional, if not used, next case is executed.
  • While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

1.      switch (expression){  

2.          case value1:  

3.           statement1;  

4.           break;  

5.          .  

6.          .  

7.          .  

8.          case valueN:  

9.           statementN;  

10.       break;  

11.      default:  

12.       default statement;  

13.  }  

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.

  1. for loop
  2. while loop
  3. do-while loop

Let's understand the loop statements one by one.

freestar

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.

1.      for(initialization, condition, increment/decrement) {    

2.      //block of statements    

3.      }    

The flow chart for the for-loop is given below.


Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.

1.      for(data_type var : array_name/collection_name){    

2.      //statements    

3.      }    

Java while loop

The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

freestar

1.      while(condition){    

2.      //looping statements    

3.      }    

The flow chart for the while loop is given in the following image.


Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.

freestar

1.      do     

2.      {    

3.      //statements    

4.      while (condition);    

The flow chart of the do-while loop is given in the following image.


Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement.

 

 

·        Object & classes

Classes and objects in Java

Learn how to make classes, fields, methods, constructors, and objects work

together in your Java applications

Classes, fields, methods, constructors, and objects are the building blocks of object-based

Java applications. This tutorial teaches you how to declare classes, describe attributes via

fields, describe behaviors via methods, initialize objects via constructors, and instantiate

objects from classes and access their members. Along the way, you'll also learn about

setters and getters, method overloading, setting access levels for fields, constructors, and

methods, and more. Note that code examples in this tutorial compile and run under Java 12.

Advanced techniques: Fields and methods in Java

TABLE OF CONTENTS

• Class declaration

• Fields: Describing attributes

• Methods: Describing behaviors

• Constructors: Initializing objects

• Objects: Working with class instances

Class declaration

A class is a template for manufacturing objects. You declare a class by specifying

the class keyword followed by a non-reserved identifier that names it. A pair of matching

open and close brace characters ({ and }) follow and delimit the class's body. This syntax

appears below:

class identifier

{

 // class body

}

By convention, the first letter of a class's name is uppercased and subsequent characters are

lowercased (for example, Employee). If a name consists of multiple words, the first letter of

each word is uppercased (such as SavingsAccount). This naming convention is

called CamelCasing.

The following example declares a class named Book:

class Book

{

 // class body

}

A class's body is populated with fields, methods, and constructors. Combining these

language features into classes is known as encapsulation. This capability lets us program at a

higher level of abstraction (classes and objects) rather than focusing separately on data

structures and functionality.

What is an object-based application?

An object-based application is an application whose design is based on declaring classes,

creating objects from them, and designing interactions between objects.

Utility classes

A class can be designed to have nothing to do with object manufacturing. Instead, it exists

as a placeholder for class fields and/or class methods. Such a class is known as a utility class.

An example of a utility class is the Java standard class library's Math class.

 

Multi-class applications and main()

A Java application is implemented by one or more classes. Small applications can be

accommodated by a single class, but larger applications often require multiple classes. In

that case one of the classes is designated as the main class and contains the main() entrypoint method. For example, Listing 1 presents an application built using three classes: A, B,

and C; C is the main class.

Listing 1. A Java application with multiple classes

class A

{

}

class B

{

}

class C

{

 public static void main(String[] args)

 {

 System.out.println("Application C entry point");

 }

}

 

Fields: Describing attributes

 A class models a real-world entity in terms of state (attributes). For example, a vehicle has a color and a checking account has a balance. A class can also include non-entity state. Regardless, state is stored in variables that are known as fields. A field declaration has the following syntax:

[static] type identifier [ = expression ] ;

 

 

 

Methods: Describing behaviors

In addition to modeling the state of a real-world entity, a class also models its behaviors. For example, a vehicle supports movement and a checking account supports deposits and withdrawals. A class can also include non-entity behaviors. Regardless, Java programmers use methods to describe behaviors. A method declaration has the following syntax: [static] returnType identifier ( [parameterList] ) { // method body }

 

What are Constructors in Java?

In Java, Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

 

Example

 

// Java Program to demonstrate

// Constructor

import java.io.*;

 

class Geeks {

    // Constructor

    Geeks()

    {

        super();

        System.out.println("Constructor Called");

    }

 

    // main function

    public static void main(String[] args)

    {

        Geeks geek = new Geeks();

    }

}

Output

Constructor Called

Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.

 

 

How Java Constructors are Different From Java Methods?

Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.

Constructors do not return any type while method(s) have the return type or void if does not return any value.

Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.

 

class Geek

{  

  .......

 

  // A Constructor

  Geek() {

  }

 

  .......

}

 

// We can create an object of the above class

// using the below statement. This statement

// calls above constructor.

Geek obj = new Geek();

The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:

 

If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t say extends object in your class definition.

 

Need of Constructors in Java

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No.

So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

 

When Constructor is called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:

 

The constructor(s) of a class must have the same name as the class name in which it resides.

A constructor in Java can not be abstract, final, static, or Synchronized.

Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

So by far, we have learned constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

 

 

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:

1. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

 

3. Copy Constructor in Java

Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.

 

Java Methods

The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. A Java method can perform some specific task without returning anything. Java Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python. 

1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.

Syntax of Method

<access_modifier> <return_type> <method_name>( list_of_parameters)

{

    //body

}

Advantage of Method

  • Code Reusability
  • Code Optimization 

Note: Methods are time savers and help us to reuse the code without retyping the code. 

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your application. In Java, there 4 types of access specifiers. 

  • public: It is accessible in all classes in your application.
  • protected: It is accessible within the class in which it is defined and in its subclass/es
  • private: It is accessible only within the class in which it is defined.
  • default: It is declared/defined without using any modifier. It is accessible within the same class and package within which its class is defined.

Note: It is Optional in syntax.

2. The return type: The data type of the value returned by the method or void if does not return a value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to method names as well, but the convention is a little different. It is Mandatory in syntax.

4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().  It is Optional in syntax.

5. Exception list: The exceptions you expect by the method can throw, you can specify these exception(s). It is Optional in syntax.

6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.  It is Optional in syntax.


Types of Methods in Java

There are two types of methods in Java:

1. Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. 

2. User-defined Method

The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.

2 Ways to Create Method in Java

There are two ways to create a method in Java:

1. Instance Method: Access the instance data using the object name.Declared inside a class.

Syntax:

  • Java

// Instance Method

void method_name(){

  body // instance area

}

2. Static Method: Access the static data using class name. Declared inside class with static keyword.

Syntax:

  • Java

//Static Method

static void method_name(){

  body // static area

}

Method Signature

It consists of the method name and a parameter list (number of parameters, type of the parameters, and order of the parameters). The return type and exceptions are not considered as part of it. 

Method Signature of the above function:  

 max(int x, int y) Number of parameters is 2, Type of parameter is int.

How to Name a Method?

A method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective, noun….. After the first word, the first letter of each word should be capitalized. 

Rules to Name a Method

  • While defining a method, remember that the method name must be a verb and start with a lowercase letter.
  • If the method name has more than two words, the first name must be a verb followed by an adjective or noun.
  • In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example, findSum, computeMax, setX, and getX.

Method Calling

The method needs to be called for use its functionality. There can be three situations when a method is called: 
A method returns to the code that invoked it when:  

  • It completes all the statements in the method
  • It reaches a return statement
  • Throws an exception

Memory Allocation for Methods Calls

Methods calls are implemented through a stack. Whenever a method is called a stack frame is created within the stack area and after that, the arguments passed to and the local variables and value to be returned by this called method are stored in this stack frame and when execution of the called method is finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top of the stack which is adjusted accordingly.

There are several advantages to using methods in Java, including:

  • Reusability: Methods allow you to write code once and use it many times, making your code more modular and easier to maintain.
  • Abstraction: Methods allow you to abstract away complex logic and provide a simple interface for others to use. This makes your code more readable and easier to understand.
  • Improved readability: By breaking up your code into smaller, well-named methods, you can make your code more readable and easier to understand.
  • Encapsulation: Methods allow you to encapsulate complex logic and data, making it easier to manage and maintain.
  • Separation of concerns: By using methods, you can separate different parts of your code and assign different responsibilities to different methods, improving the structure and organization of your code.
  • Improved modularity: Methods allow you to break up your code into smaller, more manageable units, improving the modularity of your code.
  • Improved testability: By breaking up your code into smaller, more manageable units, you can make it easier to test and debug your code.
  • Improved performance: By organizing your code into well-structured methods, you can improve performance by reducing the amount of code that needs to be executed and by making it easier to cache and optimize your code.

 

 

Post a Comment

0 Comments