0% found this document useful (0 votes)
27 views137 pages

Introduction to Java Programming Basics

The document provides an introduction to Java, covering its history, characteristics, and programming structure. It explains key components of the Java programming environment, including the Java Compiler, Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). Additionally, it discusses data types, casting, wrapper classes, autoboxing, unboxing, and arrays in Java.

Uploaded by

Chrispin Joy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views137 pages

Introduction to Java Programming Basics

The document provides an introduction to Java, covering its history, characteristics, and programming structure. It explains key components of the Java programming environment, including the Java Compiler, Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). Additionally, it discusses data types, casting, wrapper classes, autoboxing, unboxing, and arrays in Java.

Uploaded by

Chrispin Joy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECTED ORIENTED PROGRAMMING

Course Code: PBCST304


INTRODUCTION TO JAVA

What is java?

Why java?

History of Java.

Characteristics of Java.

2
Characteristics of Java


Simple

Secure

Object Oriented

Robust

Platform Independent

High Performance

Distributed
3
Structure of a Java Program

Documentation Section

Package Declaration ( package Student;)

Import Statements

Interface Section

Class Definition

Main Method Class
4
Example:
//class definition
public class HelloWorld {
// main method declaration
public static void main(String[] args) {

[Link]("Hello, World!");
}
}

Output : Hello, World! 5



public class Example

Comments

Braces

public static void main

String[] args

[Link]();

6
To Save the java program

To save the program in a file with the name of


Class.
[Link]
The extension should be saved as .java

7
Java Programming Environment

Key Components:

Text Editor or IDE: Used to write source code (.java files).

Java Compiler (javac): Translates source code to bytecode.

Java Virtual Machine (JVM): Executes the compiled bytecode.

Java Development Kit (JDK): A complete software development kit
including tools like compiler, debugger, documentation generator, etc.

Java API Libraries: Collection of classes,packages and interfaces that offer
ready-to-use functionality.

8
Java Compiler


Java is a high level language

Program is translated into machine level code that is bytecode

Javac is the most popular Java compiler

Java has a virtual machine called JVM which then converts bytecode to
target code of the machine on which it is run.
Example: javac [Link]

9
10
11
Java Virtual Machine(JVM)

● JVM (Java Virtual Machine) runs Java applications as a run-time


engine.
● JVM is a part of JRE (Java Runtime Environment)
● Programmer can develop Java code on one system and expect it to run
on any other Java-enabled system without any adjustments.
● When we compile a .java file, .class files (containing byte-code) with the
same class names present in the .java file are generated by the Java
compiler.
● .class file goes through various steps when we run it.
12
Java Program Execution


The class file already created that can execute the
same file from the same directory.
Example: java HelloWord

No need to specify the .class

There is no error in runtime ,the output will be
stored.
13
Java Runtime Environment (JRE)

▶ JRE is an open-access software distribution that has a Java class


library, specific tools, and a separate JVM.
▶ JRE is one of the interrelated components in the Java Development
Kit (JDK).
▶ It is the most common environment available on devices for running
Java programs.
▶ If you want to run the bytecode on any platform, you need JRE.

14
Java Development Kit (JDK)
It is a software development environment used for developing java
application. It includes,
▶ Java Runtime Environment (JRE),
▶ An interpreter/loader (Java),
▶ A Compiler (javac),
▶ An archiver (jar),
▶ A documentation generator (Javadoc),
▶ Development tools.

15
Working of JDK
The JDK enables the development and execution of Java programs.
Consider the following process:

Java Source File (e.g., [Link]): You write the Java program
in a source file.

Compilation: The source file is compiled by the Java Compiler (part
of JDK) into bytecode, which is stored in a .class file (e.g.,
[Link]).

Execution: The bytecode is executed by the JVM (Java Virtual
Machine), which interprets the bytecode and runs the Java
program.
16
17
What is a Class in Java?


In Java, a class is a blueprint or template for creating objects.

It defines the data (fields/attributes) and actions (methods) that
the objects will have.

What is an object?

In Java, an object is an instance of a class. It is a real entity
created based on the blueprint (class) and holds data (fields) and
can perform actions (methods).
Student s1 = new Student(); 18
What is new keyword in Java?


In Java, the keyword new is used to create an object from a
class.

It allocates memory and calls the constructor of the class.
ClassName objectName = new ClassName();

new → allocates memory for the object

ClassName() → calls the constructor to initialize the object

19
Data Types
● Data type specify size and type of value that can be stored. There are two
types of data types in Java:

1. Primitive data types



Primitive types are basic data types in Java used to hold simple
values — numbers, characters, and true/false — and they do not
have methods like objects do.

2. Non-primitive data types



Non-primitive data types (also called reference types) are data types
that refer to objects. Unlike primitive types, they can store multiple
values, have methods, and are created from classes.
20
Primitive Data types are classified as:

Integer type

Floating point type

Character type

Boolean type

21
Data Types : Integer Type

Java supports 4 types of integers

22
Data Types : Floating point Type
Java supports 2 kinds of floating point storage
Type Size Minimum value Maximum value

float 4 byte 1.4e-45 3.4e+38

double 8 byte 4.9e-324 1.8e+308

23
// FLOATING TYPE Eg: Compute the area of a circle.

class Area
{
public static void main(String args[])
{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
[Link]("Area of circle is " + a);
}
}
O/P: Area of circle is 366.436224 24
Data Types : Character Type

Type Size Minimum value Maximum value


Char 2 byte 0 65535


Java uses Unicode to represent characters.

There are no negative chars.

25
CHARACTER TYPE Example
// Demonstrating char data type
public class cha{
public static void main(String[] args) {
char g = 'A';
char s = '$';
[Link]("Grade: " + g);
[Link]("Symbol: " + s);
}
}
Output:
Grade: A
Symbol: $ 26
Data Types : Boolean Type


Boolean type is used for logical values.


It can have only one of two possible values, true or false.


This is the type returned by all relational operators

27
class TestBoolean {
public static void main(String[] args) {
boolean passed = true;

if (passed) {
[Link]("You passed the test!");
} else {
[Link]("You failed the test.");
}
}
}
O/P: You passed the test!
28
Wrapper Class


A Wrapper class in Java is one whose object wraps or contains
primitive data types.

In Java, wrapper classes are used where primitive types (int, char,
boolean, etc.) need to be used as objects.

29
30
Example:
Int x = 5;
Integer y = new Integer (x);

int x = 5;

→ Declares a primitive int and assigns value 5.

Integer y = new Integer(x);

→ This wraps the primitive x into an Integer object using a


constructor. 31
Why We Need Wrapper Classes in Java ?

In Java, wrapper classes are used to convert primitive data
types (like int, char, etc.) into objects.

This is necessary in many situations where only objects are
allowed, not primitive types.

You cannot assign null to a primitive, but you can assign null to
wrapper objects.
int a = null; ❌✅
//
Integer b = null; //
Error
Valid

32

Wrapper classes come with utility methods to manipulate
and convert values.

int num = 100;


String s = [Link](num); // Convert int to String

33
34
CASTING

Casting in Java means converting one data type to another.

This conversion can apply to both primitive data types and
object types within a class hierarchy.

Casting is a powerful feature that enables both manual and
automatic data type conversions.

There are two types of casting:
a) Widening Casting (Implicit)
b) Narrowing Casting (Explicit)
35
Widening Casting (Implicit Casting)
• Converts a smaller type to a larger type size.

Done automatically by the compiler.

It is safe because there is no data lose.
Int a = 10;
double b = a; // Implicit Casting
[Link](b);
O/P: 10
36
Example:
public class Ca {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt);
[Link](myDouble);
}
}
Output:
9
9.0 37
38
Narrowing Casting (Explicit)
• Converts a larger type to a smaller type.
• Must be done manually.
Double a = 12.7;
int b = (int) a; // Explicit casting from double to int

39
Example:
public class Nca {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myDouble);
[Link](myInt);
}
} O/P : 9.78
9 40
Object Type Casting:
Object casting involves converting one object reference to
another within the inheritance hierarchy.
a) Upcasting
b) Downcasting
a. Upcasting

Casting a subclass object to a superclass type. Safe and done
automatically.
Dog d = new Dog();
Animal a = d; // upcasting Dog to Animal
41
b. Downcasting

Casting a superclass reference back to a subclass.


Risky must be done manually using a cast operator.

Animal a = new Dog ();

Dog d = (Dog) a; // Dowcasting

42
Autoboxing and Unboxing

★ Java introduced autoboxing and unboxing in Java


5 to simplify conversions between primitive types
and wrapper classes.

★ This features convert the primitive data type into


objects and objects into primitive automatically.
43
a) Autoboxing

The automatic conversion of primitive types to the
object of their corresponding wrapper classes is
known as autoboxing.

For example – conversion of int to Integer, long to
Long, double to Double, etc.

Before 5th version valueOf() method was used.

44
Example :
Before 5th version After 5th version
int a = 20; int a= 20;
Integer i = [Link](a); Integer b = a; // converting
implicitily
// Conversion do manually

“[Link](a) will do
internally.”

45
Example : Primitive char to Character Object

public class AutoBoxChar {


public static void main(String[] args) {
char ch = 'G'; // primitive char
Character obj = ch; // autoboxing to Character object

[Link]("Primitive char: " + ch);


[Link]("Autoboxed Character object: " + obj);
}
} O/P : Primitive char: G
46
Autoboxed Character object: G
Example:

// Java program to demonstrate Autoboxing


import [Link];
class Auto {
public static void main(String[] args) {
char ch = 'G';
// Autoboxing- primitive to Character object conversion
Character a = ch;
[Link]("Character:" +a);
ArrayList<Integer> arrayList = new ArrayList<Integer>();

47
// Autoboxing because ArrayList stores only objects
[Link](25);
[Link](55);
// printing the values from object
[Link]("ArrayList Contains: " +arrayList);
}
}
O/P: Character:G
ArrayList Contains: [25, 55]
48
Unboxing

It is just the reverse process of autoboxing.



Automatically converting an object of a wrapper
class to its corresponding primitive type is known
as unboxing.

For example, conversion of Integer to int, Long to
long, Double to double, etc.

49
Example:
// Java program to demonstrate Unboxing
import [Link]
class Geeks {
public static void main(String[] args) {
Character ch = 'M';
// unboxing - Character object to primitive

50
// conversion
char a = ch;
[Link](a);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
[Link](24);
// unboxing because get method returns an Integer object
int num = [Link](0);
// printing the values from primitive data types
[Link](num);
} O/P: M
51
24
Arrays

An array is a group of like-typed variables that are referred to by a common
name.

Arrays of any type can be created and may have one or more dimensions.

A specific element in an array is accessed by its index (position), its starts from 0
(0,1,2...).

Arrays offer a convenient means of grouping related information.
Declaring Array:
Syntax:
Method 1:
type var-name[]; Eg: int a[];
Method 2:
type[] var-name; Eg: int[] a; 52

Arrays in java need to be linked to a physical memory location.

So we must allocate space using new keyword and assign it to
array variable.

new is a special operator that allocates memory.

Initialisation of an Array:
Syntax:
var-name = new type [size];
Eg: int a[];
a = new int[12]; or int a[] = new int[12];
53
Store the values in Array
Eg :
int a[];
a = new int[4];
a[0] = 1;
a[1] = 2;
a[2] = 4;
a[3] = 3;

Arrays can be given the values when they are declared.
Eg: int a[] = {1,2,4,3};

54
Access an Element of an Array
Syntax:
// Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];

55
Change an Array Element
Syntax:
// Changing the first element to 20
numbers[0] = 20;
Array Length
Syntax:
// Getting the length of the array
int length = [Link];
56
Types of Arrays in Java

a. Single-Dimensional Arrays
b. Multi-Dimensional Arrays
a) Single-Dimensional Arrays:
A Single-Dimensional Array is a linear array where
elements are stored and accessed in a one-dimensional (1D) index-
based structure.
57
Example:
public class array {
public static void main(String[] args) {
int[] arr = {5, 10, 15};
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + arr[i]);
}
}
} Output: Element at index 0: 5
Element at index 1:10
Element at index 2:15
58
b) Multi-Dimensional Arrays:


A Multi-Dimensional Array is an array of arrays.

The most commonly used is the two-dimensional (2D) array,
which can be visualized as a matrix or table of rows and
columns.
Syntax:
type var_name[][];
Eg: int a[][];
59
Initialisation of 2 Dimensional Array:

Syntax:
type var_name[] [] = new type[][];
Eg: int b[][] = new int[4][5]; here 4 rows and 5 columns

60
// Demonstrate a two-dimensional array.
class Multi {
public static void main(String args[]) {
int twoD[][]= new int[4][5]; // Declare a 2D array of size 4x5
int i, j, k = 0;
for(i=0; i<4; i++) // Fill the array with incremental values
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) { // Print the 2D array
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
} 61
O/P:
01234
56789
10 11 12 13 14
15 16 17 18 19

62
Strings


A String in Java is a sequence of characters used to store textual
data.

Java treats Strings as objects, rather than primitive data types.

The String class is defined in the [Link] package.

It is immutable, meaning once created, it cannot be changed.

63
String Declaration and Initialization
String Declaration and Initialization
1. Using String Literals (String Constant Pool)

In Java, string literals are sequences of characters


enclosed in double quotes.
Example : String s1 = "Hello";

• Stored in String Constant Pool (SCP).

• If a string with the same value already exists in SCP, it is reused.


64
2. Using new Keyword (Heap Memory)
Example : String s2 = new String("Hello");
• Creates a new object in heap memory even if the same value
exists in the SCP.
• Not memory efficient.
String Immutability
Once a String object is created, its content cannot be changed.
Example:
String s = "Java"
[Link](" Programming"); // Does not change s
[Link](s); // Output: Java 65
Example:
String s = "Java"
s = [Link](" Programming");
[Link](s);
O/P: Java Programming

Initially, s holds the string "JAVA".

The line s = [Link](" Programming"); creates a new string "JAVA Programming"
and assigns it back to s.

Since strings are immutable, the original "JAVA" is untouched—concat() just
returns a new String object.
66
Important String Methods

67
String Comparison
1. == Operator
• Compares reference (memory address).
Example:
String a = "Java";
String b = "Java";
[Link](a == b); // true (SCP)
68
2. equals() Method
• Compares actual content.
Example:
String a = new String("Java");
String b = "Java";
[Link]([Link](b)); // true

69
String Concatenation
1. Using + Operator
String result = "Hello" + " " + "World";

Combines three string literals: "Hello" + " " + "World"

O/P : “Hello World”

2. Using concat() Method


String result = "Hello".concat(" World");

"Hello".concat(" World") returns a new String object with the value


"Hello World". 70
Operators – Arithmetic, Bitwise, Relational, Boolean Logical,
Assignment, Conditional(Ternary)

a) Arithmetic Operators:

Used to perform mathematical calculations.

71
72
Example:
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 20, b = 7;
int add = a + b;
int sub = a - b;
int mul = a * b;
int div = a / b;
int mod = a % b;
[Link]("Addition: " + add);
[Link]("Subtraction: " + sub);
[Link]("Multiplication: " + mul);
[Link]("Division: " + div);
[Link]("Modulus: " + mod);
}
} 73
Output:

Addition: 27
Subtraction: 13
Multiplication: 140
Division: 2
Modulus: 6

74
b) Bitwise Operators

Used to perform bit-level operations.


Often used in low-level programming, flags, and embedded systems.

75
Example:
public class BitwiseOperators {
public static void main(String[] args) {
int a = 10; // 1010
int b = 4; // 0100
int andResult = a & b;
int orResult = a | b;
int xorResult = a ^ b;
int complement = ~a;
int leftShift = a << 2;
76
int rightShift = a >> 1;
[Link]("AND: " + andResult);
[Link]("OR: " + orResult);
[Link]("XOR: " + xorResult);
[Link]("Complement: " + complement);
[Link]("Left Shift: " + leftShift);
[Link]("Right Shift: " + rightShift);
}
} 77
Output:
AND: 0
OR: 14
XOR: 14
Complement: -11
Left Shift: 40
Right Shift: 5
78
c) Relational Operators:

Used to compare two values.

Results in boolean true or false.

79
Example:
public class RelationalOperators {
public static void main(String[] args) {
int x = 25, y = 30;
[Link]("x == y: " + (x == y));
[Link]("x != y: " + (x != y));
[Link]("x > y: " + (x > y));
[Link]("x < y: " + (x < y));
[Link]("x >= y: " + (x >= y));
[Link]("x <= y: " + (x <= y));
}
} 80
Output:

x == y: false
x != y: true
x > y: false
x < y: true
x >= y: false
x <= y: true
81
d) Boolean Logical Operators:

Used to combine multiple conditions.

82
Example:
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
[Link]("a && b: " + (a && b));
[Link]("a || b: " + (a || b));
[Link]("!a: " + (!a));
[Link]("!b: " + (!b));
}
} 83
Output:
a && b: false
a || b: true
!a: false
!b: true

84
e) Assignment Conditional Operators:

Used to assign values to variables.

85
Example:

public class AssignmentOperators {


public static void main(String[] args) {
int x = 10;
x += 5;
[Link]("After += 5: " + x);
x -= 3;
[Link]("After -= 3: " + x);
x *= 2;
[Link]("After *= 2: " + x);
x /= 4;
[Link]("After /= 4: " + x);
x %= 3;
[Link]("After %= 3: " + x);
}
86
}
Output:
After += 5: 15
After -= 3: 12
After *= 2: 24
After /= 4: 6
After %= 3: 0

87
f) Conditional (Ternary) Operator

Used to replace simple if-else conditions in one line.

Operator Syntax Real-Time Example


?: condition ? true : false Choose message based on exam score
Example:
public class ConditionalOperator {
public static void main(String[] args) {
int marks = 65;
String result = (marks >= 50) ? "Pass" : "Fail";

88
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Result: " + result);
[Link]("Maximum: " + max);
}
}
Output:
Result: Pass
Maximum: 20

89
Operator precedence

It determines the order in which operators are evaluated in an expression

when there are multiple operators.



Operators with higher precedence are evaluated before those with lower

precedence.

Associativity defines the direction (left-to-right or right-to-left) in which

operators of the same precedence are evaluated.

90
91
Example:
public class OperatorPrecedence {
public static void main(String[] args) {
int a = 10, b = 5, c = 2;

int result1 = a + b * c; // Multiplication before addition


int result2 = (a + b) * c; // Parentheses first
int result3 = a + b - c; // Left to right (same precedence)
int result4 = a + b * c - 1; // Mix of operators

[Link]("Result 1 (a + b * c): " + result1);


[Link]("Result 2 ((a + b) * c): " + result2);
[Link]("Result 3 (a + b - c): " + result3);
[Link]("Result 4 (a + b * c - 1): " + result4);
}
}
92
Output:

Result 1 (a + b * c): 20 // 10 + (5 * 2) = 10 + 10 = 20
Result 2 ((a + b) * c): 30 // (10 + 5) * 2 = 15 * 2 = 30
Result 3 (a + b - c): 13 // (10 + 5 - 2) = 13
Result 4 (a + b * c - 1): 19 // 10 + (5 * 2) - 1 = 19

93
Control Statements


Java control statements determine the flow of program execution
based on conditions, loops, or abrupt changes.

They are broadly categorized into:


Selection Statements: Allow branching based on conditions.

Iteration Statements: Execute a block of code repeatedly.

Jump Statements: Transfer control to another part of the program.

94
1. Selection Statements

Selection statements execute specific blocks of code depending on
conditions.

Types of selection statements:

95
Examples 1: if Statement
int age = 18;
if (age >= 18)
{
[Link]("Eligible to vote.");
}

Examples 2: if-else Statement


int marks = 45;
if (marks >= 50)
{
[Link]("Pass");
}
else
{
[Link]("Fail");
} 96
Examples 3: if-else-if Ladder
int marks = 85;
if (marks >= 90)
{
[Link]("Grade A");
}
else if (marks >= 75)
{
[Link]("Grade B");
}
else
{
[Link]("Grade C");
}
97
Examples 4: switch Statement
int day = 3;
switch (day)
{
case 1: [Link]("Monday");
break;
case 2: [Link]("Tuesday");
break;
case 3: [Link]("Wednesday");
break;
default: [Link]("Invalid day");
}

The expression inside switch must be of type byte, short, int, or char.

The case values must be of a type compatible with the expression. Each case
value must be a unique literal.

Duplicate case values are not allowed.
98
2. Iteration Statements


Iteration statements repeat a block of code as long as a condition is true.

Types of Iteration Statements

99
Example 1: for Loop

for (int i = 1; i <= 5; i++)


{
[Link]("Iteration: " + i);
}
Example 2: while Loop

int i = 1;
while (i <= 5)
{
[Link]("Iteration: " + i);
i++;
}
100
Example 3: do-while Loop
int i = 1;
do
{
[Link]("Iteration: " + i);
i++;
} while (i <= 5);

Example 4: Enhanced for Loop Syntax :for (type variable : arrayOrCollection) {


// Use variable
}

int[] numbers = {10, 20, 30};


for (int num : numbers)
{
[Link]("Number: " + num);
101
}
3. Jump Statements


Jump statements abruptly change the flow of control in a program.
Types of Jump Statements:

102
Example 1: break Statement
for (int i = 1; i <= 5; i++)
{
if (i == 3)
break;
[Link](i);
}
Output:
1
2
Example 2: continue Statement
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
continue;
[Link](i);
103
}
Example 3: return Statement
public class Example
{
public static void main(String[] args)
{
[Link](getGreeting());
}
public static String getGreeting()
{
return "Hello, World!";
}
}
Output: Hello, World!

104
Vector Class


In Java, the Vector class is a part of the Java Collection Framework.

It is found in the package [Link] and implements the List interface.

Vector is synchronized, meaning it is thread-safe for operations in multi-
threaded environments.

It grows dynamically and allows the storage of duplicate elements and null
values.
Declaration and Syntax Syntax:
Vector<Type> vectorName = new Vector<>();

105
Example:
import [Link];
public class Example {
public static void main(String[] args) {
Vector<String> names = new Vector<>();
[Link]("Alice");
[Link]("Bob");
[Link](names);
}
}
Output: [Alice, Bob]
106
Commonly Used Methods in Vector

107
Constructors of Vector

108
Functions

A function (commonly referred to as a method) is a block of code
that performs a specific task and can be reused multiple times.

Functions help in modularizing code, making it easier to read,
maintain, and debug.
Syntax of a Function (Method)
returnType functionName(parameter1, parameter2, ...){
// body of the function
return value; // if returnType is not void 109
Example 2:
int add(int a, int b)
{
int c=a+b;
return c;
}
110
111
Function Declaration, Definition and Call

• Declaration: Defined using the returnType, name, and parameters.

• Definition: Body of the method containing the logic.

• Calling: Executing the function from main() or another method.

112
Command Line Arguments

Command Line Arguments in Java are the parameters passed to the main()
method when a program is executed from the command line.

They provide a way to input data to the program at runtime without using
Scanner or GUI.

Command-line arguments are stored as strings in the String array passed to
main( ).

To access these arguments, you can simply traverse the args parameter in the
loop or use direct index value because args is an array of type String.
Syntax:
public static void main(String[] args)

113
Example:
public class CommandLineExample {
public static void main(String args[]) {
for(int i=0; i<[Link]; i++)
[Link]("args[" + i + "]: " + args[i]);
}
}
Command line input: java CommandLineExample Hello World
Output:
args[0]: Hello
args[1]: World
114
Example: Add two numbers using command line arguments

public class SumArguments {


public static void main(String[] args) {
int a = [Link](args[0]); //This converts the String to an integer.
//Type Conversion (String → int)
int b = [Link](args[1]);
int sum = a + b;
[Link]("Sum: " + sum);
}
}
Command line input :: java SumArguments 20 40
Output:
Sum: 60
115
Variable Length Arguments

Variable Length Arguments (Varargs) allow a method to accept zero or more
arguments of the same data type.

This feature was introduced in Java 5 to support method calls with variable
numbers of parameters without explicitly using arrays.
Syntax:
returnType methodName(type... variableName)

The ellipsis ... indicates varargs.

Inside the method, the varargs parameter is treated as an array.

116
Example: Sum of any number of integers using varargs:
public class VarargsExample {
static int sum(int... numbers) {
int total = 0;
for (int num : numbers)
total += num;
return total;
}
public static void main(String[] args) {
[Link]("Sum 1: " + sum(10, 20));
[Link]("Sum 2: " + sum(5, 15, 25, 35));
[Link]("Sum 3: " + sum()); // No arguments
}
}
Output: Sum 1: 30
Sum 2: 80
117
Sum 3: 0
Rules of varargs

Only one varargs parameter per method
• Varargs must be the last parameter
• Treated as an array inside method
Example
public class Demo {
static void display(String label, int... values) {
[Link](label + ": ");
for (int v : values)
[Link](v + " ");
[Link]();
}

118
public static void main(String[] args) {
display("Marks", 75, 80, 90);
display("IDs", 101, 102);
display("Empty");
}
}
Output:
Marks: 75 80 90
IDs: 101 102
Empty

119
Classes

A class in Java is a user-defined data type.

It is a blueprint or prototype from which objects are created.

The class forms the basis for object-oriented programming in Java. In
object-oriented programming (OOP), a class is the fundamental building
block that encapsulates data and methods.

Any concept we wish to implement in a Java program must be
encapsulated within a class.

120
Syntax of a Class:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
} 121

The methods and variables defined within a class are called members of
the class.

The variables, defined within a class are called instance variables
because each instance of the class contains its own copy of these variables.

The methods, defined within a class are called member functions. The
code is contained within methods.

The data for one object is separate and unique from the data for another.

122
Example: Define a class Box which defines three instance variables: width, height,
and depth. Also define a mehod called volume() to calculate the volume of the Box.

class Box{
double Width;
double Height;
double Depth;
void volume() {
[Link]("Volume is ");
[Link](width * height * depth);
}
}

123
Object


An object is an instance of a class.

It is the runtime instance of a class.

To use a class, you need to create an object.

Class object declaration is a two-step process.
Declare a variable of the class type
Syntax:
classname class-var ;

It is simply a variable that can refer to an object.

Acquire an actual, physical copy of the object and assign it to that variable
124

Syntax: class-var = new classname( );
Example :

Box mybox = new Box();


The above statement can also be written as follows
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

125
To access these variables, we will use the dot (.) operator.
Syntax:
[Link]();
[Link] = value;
Example: assign the Width variable of mybox the value 100
[Link] = 100;

126
127
Abstract Classes


An abstract method is a method that does not have a body (implementation).

It only has a declaration and must be overridden in a subclass.

It is declared using the abstract keyword.
Syntax:
abstract type method_name(parameter-list);
Example: abstract void makeSound(); // Abstract method (no body)
void method2() { // Concrete method (has body). Optional
// Code
} 128

Any class that contains one or more abstract methods must be declared as an abstract
class.

Such a class cannot be instantiated(do not create object directly), and it is meant to be
extended by subclasses that provide the implementation for the abstract methods.

Even if a class has only one abstract method, the whole class must be abstract.

Abstract classes must satisfy the following conditions:
1. Can have abstract and non-abstract methods.
2. Can extend another class or be extended by others
3. Subclass must override all abstract methods
4. Abstract classes are not used to instantiate objects directly

129
Example:
abstract class Person {
abstract void makeSound(); // abstract method
void eat()
// concrete method
{
[Link]("Person is walking");
}
}

130
Example
abstract class Plant {
abstract void makeFurniture(); // abstract method
void grow() {
// concrete method
[Link]("Plant needs water");
}
}
class Neem extends Plant {
void makeFurniture() {
[Link]("It is a Plant");
}
}
131
public class Main {
public static void main(String[] args) {
Plant p = new Neem();
[Link]();
[Link]();
}
}
// Output:Plant needs water
It is a Plant

Here, Plant p = new Plant();



It is illegal because Plant is an abstract class. Such an object would be useless,
because an abstract class is not fully defined.

132
133
Interfaces

An interface in Java is like a contract — it defines what a class must do, but not how
to do it.

It contains only abstract methods (until Java 7), and no method bodies.

An interface normally contains only abstract methods and constants.

From Java 8 onwards, default and static methods with body are allowed.

A class implements an interface and provides code for its methods.

An interface cannot have constructors or instance variables.

134
Syntax
interface InterfaceName {
return_type const1=value;
//Constant declaration
return_type const2=value;
//Constant declaration
return_type method1();
// Abstract method (implicitly public and abstract)
return_type method2();
// Abstract method (implicitly public and abstract) }

These constants are public, static, and final. Methods are public and abstract.
135
Implementing an Interface
class Classname implements InterfaceName {
public void method1() {
method1() definition
}
public void method2() {
method2() definition
}
}

136
Example:

interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
[Link]("Car engine started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car(); // Polymorphism
[Link]();
}
}
// Output: Car engine started

137

You might also like