Introduction to Java Programming Basics
Introduction to Java Programming Basics
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!");
}
}
6
To Save the java program
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)
●
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)
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:
21
Data Types : Integer Type
22
Data Types : Floating point Type
Java supports 2 kinds of floating point storage
Type Size Minimum value Maximum value
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
●
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;
32
●
Wrapper classes come with utility methods to manipulate
and convert values.
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.
42
Autoboxing and Unboxing
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
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
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)
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";
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:
85
Example:
87
f) Conditional (Ternary) Operator
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
precedence.
●
Associativity defines the direction (left-to-right or right-to-left) in which
90
91
Example:
public class OperatorPrecedence {
public static void main(String[] args) {
int a = 10, b = 5, c = 2;
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.");
}
●
Iteration statements repeat a block of code as long as a condition is true.
●
Types of Iteration Statements
99
Example 1: for 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);
●
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
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
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 :
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
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