0% found this document useful (0 votes)
14 views96 pages

Java OOP Concepts and Programming Guide

The document outlines a course on Object Oriented Programming using Java at Shree Devi Institute of Technology, detailing course objectives, outcomes, and program outcomes. It provides an overview of Java's history, key features, and principles of OOP, including encapsulation, inheritance, and polymorphism. Additionally, it includes a sample Java program and explains the significance of Java's bytecode and its impact on programming and security.

Uploaded by

ps7207295
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)
14 views96 pages

Java OOP Concepts and Programming Guide

The document outlines a course on Object Oriented Programming using Java at Shree Devi Institute of Technology, detailing course objectives, outcomes, and program outcomes. It provides an overview of Java's history, key features, and principles of OOP, including encapsulation, inheritance, and polymorphism. Additionally, it includes a sample Java program and explains the significance of Java's bytecode and its impact on programming and security.

Uploaded by

ps7207295
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

Object Oriented Programming

using Java

Shree Devi Institute of Technology, Kenjar


Subject Code- MMC202
Course Learning Objectives

 Analyze the basic concepts of Java


 Improve the analytical skills of object oriented programming, formal
introduction to Java programming language
 Overall development of problem solving and critical analysis
Course Outcomes

SL. No Description Blooms Level


CO1 Understand the basic concepts of Java L2
CO2 Solve the given problem by applying OOP using java L2
CO3 Understanding the fundamentals of Inheritance, L3
interfaces and packages, Exception Handling and
Multi thread
CO4 Identify and list the different applications of event L3
handling
Program Outcomes
Sl. No Description POs
1 Foundation Knowledge: Apply knowledge of mathematics, programming logic and coding PO1
fundamentals for solution architecture and problem solving.
2 Problem Analysis: Identify, review, formulate and analyse problems for primarily focusing on PO2
customer requirements using critical thinking frameworks.
3 Development of Solutions: Design, develop and investigate problems with as an innovative PO3
approach for solutions incorporating ESG(Environment, social and Governance)/SDG goals.
4 Modern Tool Usage: Select, adapt and apply modern computational tools such as PO4
development of algorithms with an understanding of the limitations including human biases.
5 Individual and Teamwork: Function and communicate effectively as an individual or a team PO5
leader in diverse and multidisciplinary groups. Use methodologies such as agile.
6 Project Management and Finance: Use the principles of project management such as PO6
scheduling, work breakdown structure and be conversant with the principles of Finance for
profitable project management.
7 Ethics: Commit to professional ethics in managing software projects with financial aspects. PO7
Learn to use new technologies for cyber security and insulate customers from malware
8 Life-long learning: Change management skills and the ability to learn, keep up with PO8
contemporary technologies and ways of working.
Mapping of COs and POs

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8


CO1 X
CO2 X
CO3 X
CO4 X
Module 1

 The History and Evolution of Java: The Byte code, Features of Java An overview of
Java: Object Oriented Programming, Structure of a Java program, Data Types and
Variables, Type conversion and casting,
 Arrays Classes: Fundamentals, Declaring Objects, Assigning Object Reference
Variables, Methods, Constructors, this Keyword, Garbage Collection, Stack
application
 Methods and Classes: Overloading Methods, Using Objects as Parameters, Argument
Passing, Returning Objects, Access Control, static, final, Command-Line Arguments
The History and Evolution of Java

Why Java Was Created?


• Java was designed in response to the growing need for a platform-
independent and reliable programming language.
• Initially intended for embedded systems (like TVs, remote controls), Java's
true breakthrough came with the rise of the Internet.

 Java’s Lineage
• C influenced Java’s syntax.
• C++ contributed its object-oriented programming (OOP) concepts.
• Java responded to limitations in these languages by improving portability,
security, and simplicity.
The History and Evolution of Java

The Evolution of Programming Languages

 1. C Language (1970s)
• Developed by Dennis Ritchie.
• Created to replace assembly for system-level programming.
• Balanced:
• Ease of use vs. power-You have control, but it's harder to write correct code.
• Safety vs. efficiency-Fast but risky without careful coding.
• Rigidity vs. extensibility-Extensions rely on external tools/macros, not the
language core.
• Enabled structured programming and replaced “spaghetti code.”(no clear flow or
structure)
The History and Evolution of Java
 2. C++ (1980s)
• Created by Bjarne Stroustrup as “C with Classes.”
• Extended C with OOP features to manage
• Designed for large, scalable programs.

 The Birth of Java (1991–1995)


• Created by James Gosling and team at Sun Microsystems.
• Originally called Oak.
• Needed for cross-platform code execution on various devices.
• Became vital with the emergence of the World Wide Web, which required portable,
secure, and network-savvy programs.
The History and Evolution of Java
 Java’s Key Innovations

• Platform-independence via the Java Virtual Machine (JVM).


• Strong focus on security, robustness, and simplicity.
• Designed to be a "write once, run anywhere" language.
• Java became popular because of the Internet
• Solved key issues: Web programming, Portability, and Security
How Java Impacted the Internet
 Why Applets Were Important?

• Applets were active programs, not just data


• Allowed more interactive and engaging web pages
• Early example of dynamic online content
• Became less important over time
• Phased out starting with JDK 9, removed in JDK 11
How Java Impacted the Internet
 Java and Security
• Programs from the Internet can be risky (e.g., viruses, spyware)
• Java restricted programs to a safe area (sandbox)
• This prevented harmful actions like reading private files
• One of Java’s most innovative features

 Java and Portability


• The Internet connects many types of computers
• Java programs needed to run on all systems
• Java programs are “write once, run anywhere”
• Achieved using the same mechanism that provides security
The Bytecode
• Java compiler doesn’t create executable code
• Instead, it creates bytecode
• Bytecode is run by the Java Virtual Machine (JVM)
• JVM is part of the Java

 Why Bytecode Matters


• Makes Java programs portable across platforms
• One JVM per platform = same Java code runs anywhere
• Solves the need to write different code for different systems
• Bytecode works on all CPUs with a JVM
• Runtime Environment (JRE)
The Bytecode
 Bytecode and Security
• JVM controls how bytecode runs
• Java programs run in a “sandbox” (a restricted environment)
• Prevents programs from harming your system
• Java language adds built-in safety checks

 Performance and Interpretation


• Bytecode is interpreted, which is usually slower
• But Java bytecode is highly optimized
• JVM runs bytecode faster than typical interpreted languages
The Bytecode
 Just-In-Time (JIT) Compilation
• HotSpot technology introduced JIT compilation, it’s a part of JVM
• JIT compiles bytecode into native code as needed, selected portions of bytecode are
compiled into executable code in real time, on a piece-by-piece, demand basis
• Only few sequence of codes are compiled, The remaining code is simply interpreted
• Boosts performance while keeping portability and safety

 Ahead-of-Time (AOT) Compiler


• Starting with JDK 9, Java supports AOT compilation
• Converts bytecode to native code prior to execution by the JVM
• AOT is optional and used in specialized cases
• Traditional bytecode + JIT is still the main method
Java – Key Features Overview
 Simple
• Easy to learn for programmers with experience
• Familiar C/C++-like syntax
• Removes complex features like pointers and operator overloading

 Object-Oriented
• Designed from scratch with clean object-oriented principles
• Supports reusable, modular, and organized code
• Combines flexibility with simplicity (primitive types like integers are kept non-
objects for speed)
Java – Key Features Overview
 Robust
• Java encourages early error detection
• Strict compile-time and runtime checking
• Automatic garbage collection – no need to manually free memory
• Handles runtime errors using exception handling

 Multithreaded
• Supports multithreading for building interactive applications
• Enables programs to do multiple tasks simultaneously
• Built-in support for thread synchronization
Java – Key Features Overview
 Architecture-Neutral
• Code runs on any system with a JVM
• Immune to changes in OS or hardware
• Goal: “Write once, run anywhere”

 Interpreted & High Performance


• Java compiles to bytecode (platform-independent)
• JVM interprets or compiles bytecode with JIT compiler
• Delivers near-native performance without sacrificing portability
Java – Key Features Overview
 Distributed
• Built-in support for networking
• Handles TCP/IP protocols and URLs like files
• Supports Remote Method Invocation (RMI) for calling methods over
networks

 Dynamic
• Java programs carry runtime type info(accesses to objects at run time.)
• Enables dynamic loading and linking of classes
• Allows updates to code while the program is running
Object-Oriented Programming
 Introduction to Object-Oriented Programming (OOP) in Java
• Java is built on the principles of OOP.
• All Java programs use OOP concepts to some extent.
• Understanding OOP is essential before writing Java code.

 Why OOPs in Java?


• Reflects how humans naturally understand systems.
• Enables:
• Clean program design
• Easy updates and maintenance
• Flexibility during software lifecycle: conception → growth → aging
• Objects with clear interfaces can be safely replaced or updated.
Object-Oriented Programming
 Two Programming Paradigms/Instances
• All programs consist of: Code and Data

• Two main approaches to program design:


• Process-Oriented (Procedural)
• Focus on what is happening (code-driven)
• Example: C language
• Object-Oriented Programming (OOP)
• Focus on who is being affected (data-driven)
• Organizes programs around objects and their interfaces
Object-Oriented Programming
 Key OOP Principle – Abstraction
• Abstraction helps manage complexity.
• Example: People view a car as one object, not thousands of parts.
• Use an object without knowing all internal details (e.g., engine or brakes).
 Abstraction with Hierarchy
• Complex systems are easier to understand through hierarchical classification:
• Car → Subsystems → Specialized components E.g., Sound System → Radio, CD Player, MP3
 Applying Abstraction to Programming
• Traditional procedural programs can be restructured: Data becomes objects and
• Processes become messages between objects
• Objects have unique behavior and respond to commands (messages)
The Three OOP Principles
All object-oriented programming languages provide mechanisms that help
you implement the object-oriented model.
Encapsulation
Inheritance
polymorphism
1. Encapsulation
 What is Encapsulation?
• Encapsulation = wrapping code and data together.
• Protects them from outside interference and misuse.
• Access is controlled via a well-defined interface.

 Benefits of Encapsulation
• Keeps internal details hidden.
• Users access functionality without needing to understand the internals.
• Helps prevent unexpected side effects.
• Encourages reusable and modular code.
1. Encapsulation
Juice Machine (Encapsulation Example)
 Internal Complexity (Hidden from User):
• Mixing fruits and Controlling sugar level
• Filtering pulp and Managing temperature
 User Interface: You just press a button: "Make Juice"
 Key Point:
• You don’t need to know how the machine works inside.
• The button is the interface — simple and safe to use.
• Internal parts are encapsulated — protected from misuse.
1. Encapsulation
 Encapsulation in Java
• Java uses classes to implement encapsulation.
• A class defines:
• Data → member variables (instance variables)
• Code → methods (functions that operate on the data)
• Objects are instances of classes.
 Access Control
• public: accessible from outside the class.
• private: only accessible within the class.
• Use public methods to safely expose functionality.
• Keep internal details private to avoid misuse
2. Inheritance
• Inheritance = one object acquires properties (data and behavior) of another.
• Supports hierarchical classification (e.g., Animal → Mammal → Dog).
• Helps reduce code duplication.

 Benefits of Inheritance
• Promotes code reuse.
• Allows specialization without rewriting base functionality.
• Makes it easier to build complex systems from simpler parts.
2. Inheritance
 Vehicle Inheritance Example
 Parent Class: Vehicle
• Properties: speed/color/ fuel Type
• Methods: start()/ stop()
 Child Class: Car (inherits from Vehicle)
• Inherits: speed, color, fuelType, start(), stop()
• Adds: numberOfDoors/ playMusic()
 Another Child Class: Motorcycle
• Inherits: speed, color, fuelType, start(), stop()
• Adds: helmetStorage
2. Inheritance
 Java and Inheritance
• Use extends to inherit a class.
• Subclass (child) gets all accessible attributes and methods from superclass (parent).
A subclass can:
• Add new methods or variables.
• Override existing methods for custom behavior.
 Relationship with Encapsulation
• Subclass inherits encapsulated data (private/protected members).
• Can use public methods of the superclass to access or modify encapsulated data.
• Helps keep code organized and secure, even as it grows.
3. Polymorphism
 What is Polymorphism?
• Polymorphism = "many forms" (from Greek)
• Allows one interface to be used for different actions
• Behavior changes depending on the situation or data type

 Key Idea
“One Interface, Multiple Methods”
• Use one interface for related tasks
• Java compiler picks the correct method
• Programmer uses the general method name only
3. Polymorphism
Advantages

Simplifies code

Reuses methods

Java chooses correct method automatically

Makes programming easier and cleaner


3. Polymorphism
Real-Life Analogy (Dog Example)

• Dog's sense of smell = polymorphic


• Smells a cat → barks, chases
• Smells food → salivates, runs to bowl
• Same action (smelling), different outcomes
3. Polymorphism
Payment System
 Imagine an online store that accepts different types of payments:
• Credit Card
• PayPal
• UPI
 You, the customer, just click "Pay Now" — you don’t need to know how each payment
works internally.
3. Polymorphism
 One Interface, Many Forms
• The "Pay Now" button is the general interface.
• The actual action (credit card, PayPal, UPI) depends on which payment method is
selected.
• The same button (interface) triggers different behaviors (methods), based on the type
of payment.

One common action → many specific results.


You interact with one method (e.g., pay()), and the system handles which version to run
based on context.
Polymorphism, Encapsulation, an Inheritance
Work Together

 Power of Object-Oriented Programming (OOP)


 Combines:
• Encapsulation
• Inheritance
• Polymorphism

Leads to:
• More robust and scalable programs
• Better code reuse and maintenance
Polymorphism, Encapsulation, an Inheritance
Work Together
 Encapsulation: Hides the internal details of objects
Lets you change how something works without affecting users
Example: Car pedals (simple interface, hides engine complexity)

 Inheritance: Subclasses inherit properties and methods from a superclass


• Bus, Sedan, Minivan → all are types of Vehicles
• Drivers know how to use all because they share a common design

 Polymorphism: Same interface, different implementations


• Different cars have various engines and brake systems
• Still, you use the same controls: pedal, steering wheel, etc.
Polymorphism, Encapsulation, an Inheritance
Work Together
 The Car
• Encapsulation → You press a pedal, not worry about engine type
• Inheritance → All vehicles follow a basic design
• Polymorphism → One set of controls for many vehicle types

 The Smartphone
 Encapsulation → You tap an app, not worry about how it works inside.
 Inheritance → All smartphones (Android, iPhone) share basic features: touchscreen,
camera, apps.
 Polymorphism → You use the same gesture (swipe, tap) to interact with different apps
— each responds in its own way.
First Sample Program

class Example //File name = Class name


{
public static void main(String[] args)
{
[Link]("Java is powerful!");
}
}
Write and save a simple Java program with .java filename extension([Link])
Compile it using javac → Compiles code into bytecode
Run it using java → Launches the Java Virtual Machine (JVM) to run bytecode
First Sample Program

Comments in Java: Three types of comments


Multiline comment: /* comment */
Single-line comment: // comment
Documentation comment: /** doc comment */ (covered later)
Comments are ignored by the compiler and help explain code

Declaring a Class:
class keyword defines a new class
Example is the name of the class
All code must be inside a class
Use { and } to group class contents
First Sample Program

The main() Method:


public → can be called from outside
static → no object needed to run
void → returns no value
main → entry point of the program
String[] args → receives command-line input

Inside main() – Output Statement: Prints text to the console


System → built-in class
out → standard output stream
println() → method that prints and adds a new line
Second Sample Program

Class Example2{
public static void main(String args[]){
int num;
num=100;
[Link]("This is num:" +num);
num=num*2;
[Link]("The value of num * 2 is:" +num);
[Link](num);
}
output:
}
This is num: 100
The value of num * 2 is: 200
Second Sample Program

Variable declaration:
type var-name;
type specifies the type of variable being declared
var-name is the name of the variable
int num; // this declares a variable called num

num = 100; // this assigns num the value 100


The print( ) method is just like println( ), except that it does not output a newline
character after each call
Two Control Statements

Control statements determine flow of execution.


Java has various control structures.

Two common ones:


1. if statement (conditional execution): tests conditions and executes statements
conditionally.
2. for loop (repetitive execution): It repeats tasks with loop control.
Two Control Statements

The if Statement : It determines the flow of execution based on whether some condition
is true or false
Syntax: if(condition) statement;
condition is a Boolean expression(True or False)

Example:
if(num < 100) [Link]("num is less than 100");
if num contains a value that is less than 100, the conditional expression is true, and
println( ) will execute.
If num contains a value greater than or equal to 100, then the println( ) method is
bypassed
Two Control Statements

Class Sample{
public static void main(String args[]){
int x=10,y=20;
if(X<Y) [Link]("X ix less than Y"); Output:
X=X*2; x is less than y
x now equal to y
if(X==Y) [Link]("X now equal to Y");
x now greater than y
X=X*2;
if(X>Y) [Link]("X now greater than Y");
if(X==Y) [Link]("This won't be displayed");
}
}
Two Control Statements

The for loop : It provide a way to repeatedly execute some task


Syntax: for(initialization; condition; iteration)statement;

the initialization portion of the loop sets a loop control variable to an initial value
The condition is a Boolean expression that tests the loop control variable. If the outcome
of that test is true, statement executes and the for loop continues to iterate. If it is false,
the loop terminates.
The iteration expression determines how the loop control variable is changed each time
the loop iterates
Two Control Statements

Example:
Class Test{
public static void main(String args[]){
int x;
for(x=0;x<10;x=x+1)
[Link]("This is x:"+x);
}
}
Atomic elements of Java

Java programs are a collection of

1. Whitespace
2. Identifiers
3. Literals
4. Comments
5. Operators//Study in next chapter
6. Separators
7. Keywords.
Atomic elements of Java

 Whitespace in Java

• Java is a free-form language – no strict indentation rules.


• Code can be written on one line or many.
• Requirement: At least one whitespace (space, tab, newline, or form feed) between
tokens not separated by operators/separators.
• Whitespace improves readability, not syntax.
Atomic elements of Java

 Identifiers in Java: Used to name classes, variables, methods, etc.


1. Letters (A–Z, a–z)
2. Digits (0–9)
3. Underscore (_) and dollar sign ($)// Dollar sign is not recommended for general use
Must not start with a digit
Java is case-sensitive: hence, VALUE ≠ Value

 Valid identifiers: myVariable, _temp, Data2, $price,a4, count


 In Valid identifiers: 2count, high-temp, not/ok
Atomic elements of Java

 Literals: A constant value in Java is created by using a literal representation of it.

 int number = 42; // Integer literal


 double pi = 3.14; // Floating-point literal
 char grade = 'A'; // Character literal
 String greeting = "Hello"; // String literal
Atomic elements of Java

Comments : Three types of comments defined by java

1. Multiline comment: /* comment */


2. Single-line comment: // comment
3. Documentation comment: /** doc comment */ (covered later)
Atomic elements of Java

Separators : In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon.
Atomic elements of Java

Keywords : The keywords const and goto are reserved but not used. keywords cannot be
used as identifiers, meaning that they cannot be used as names for a variable, class, or
method.
Data Types, Variables, and Arrays
Data Types, Variables, and Arrays

 The Primitive Types: Java has 8 primitive data types, which are the most basic data
types available within the language. They are predefined by the language and named
by a reserved keyword
Literals

•Literal: A fixed value used directly in code. Java supports:

•Integer literals

•Floating-point literals

•Boolean literals

•Character literals

•String literals
Literals

 1. Integer Literals:
 Decimal (base 10): e.g., 1, 42
 Octal (base 8): prefix with 0 (e.g., 077)
 Note: 09 is invalid (9 not in octal range)
 Hexadecimal (base 16): prefix with 0x or 0X (e.g., 0x1A)
 Binary: prefix with 0b or 0B (e.g., 0b1010)
 Type Defaults: Defaults to int
 Use L or l to specify long (e.g., 123L)
 Underscores allowed for readability: int x = 1_000_000;
Literals

 2. Floating point Literals:


 Represent numbers with fractions
 Standard notation: 3.14, 0.5
 Scientific notation: 6.022E23, 1.5e-3
 Defaults to double (64-bit)
 Use F or f for float (32-bit)
 Optional D or d for double
 Hexadecimal format: 0x1.2P3 (rare)
 Underscores allowed: double d = 1_000.000_1;
Literals

 3. Boolean Literals:

 Only two valid values:


 true
 false

 Cannot be treated as numbers


 Used only with boolean type and logical operations
Literals

 4. String Literals:

 Enclosed in double quotes: "Hello World"


 Can include escape sequences:
 "two\nlines"
 "\"quoted\""
 No multi-line strings across lines
 Escape characters work same as in character literals
Literals

 5. Character Literals:

 Represented with single quotes: 'a', 'Z', '@'


 Escape sequences:
 Newline: '\n'
 Quote: '\''
 Octal: '\141' (a)
 Hexadecimal: '\u0061' (a)
 Stored as 16-bit Unicode values
Variables

 The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer.

 Declaring a variable:
type identifier [ = value ][, identifier [= value ] …];

type is one of Java’s atomic types, or the name of a class or interface.


The identifier is the name of the variable
Ex: int a, b, c;
Int d=19, r=23;
Variables

 Dynamic Initialization: Java allows variables to be initialized dynamically

class DynInit{
public static void main(String args[]){
double a=3.0, b=3.0;
double c=[Link](a*b);
s.o.p("Value is: "+c);
}
}
Scope of Variables

 What is Scope?
The part of a program where a variable can be accessed.
Defined by blocks { }, Each { } creates a new scope.

Types of Scope in Java


 Method Scope: Variables declared inside a method (local variables).
 Block Scope: Variables declared inside any block (e.g., if, for).
 Class Scope: (Covered in Chapter 6; not discussed now.)
 Java doesn't use global scope like some other languages.
Scope of Variables

 Nested Scopes
• Inner blocks can access outer block variables.
• Outer blocks cannot access variables declared in inner blocks.
 Lifetime of Variables
• Variables are created when their scope is entered and are destroyed when the scope is
exited.
• They do not retain values between method calls or block exits.
 Variable Name Conflicts
• Cannot declare two variables with the same name in nested scopes.
 int x = 10;
 { int x = 20; // Illegal: x already defined in outer scope}
Type Conversion and Casting

 Java allows assigning values between different types.


 If types are compatible, Java may do the conversion automatically.
 If not, you must use casting to convert.

Automatic Type Conversion (Widening)


 Happens when:
• Types are compatible.
• Destination type is larger than the source type.

Ex: int x = 100;


long y = x; // automatic widening
Type Conversion and Casting

Narrowing conversion(Casting):
 Assigning a larger type to a smaller type
 Types are incompatible
Syntax: (target-type) value
Ex: int a = 257; byte b = (byte) a;

Floating-Point to Integer: here fractional part is truncated.


If the whole number is too large, it’s reduced modulo target type range.
double d = 323.142;
int i = (int) d; // i = 323
byte b = (byte) d; // b = 67 (323 % 256)
Type Promotion

 Java automatically promotes smaller types in expressions.


 Ensures compatibility between operands.
 Helps prevent data loss and ensures correct calculation precision.

Java’s Type Promotion Rules


 byte, short, and char → promoted to int
 If one operand is long, expression → long
 If one operand is float, expression → float
 If any operand is double, expression → double
Arrays

 A collection of like-typed variables.


 Referred to by a common name.
 Can be one-dimensional or multidimensional.
 Elements accessed via index (starting from 0).

 Declaring One-Dimensional Arrays:


Ex: int month_days[]; // Declaration only (no memory yet)

 Allocating memory Using new


month_days = new int[12];
int month_days[] = new int[12];
Arrays

 Initializing Arrays at Declaration:


int[] days = {31, 28, 31, 30, 31, 30};

 Accessing Array Elements:


month_days[1] = 28;
[Link](month_days[3]); // Outputs 30

 Multidimensional Arrays:
int twoD[][] = new int[4][5]; // 4 rows, 5 columns
Arrays

 Irregular Arrays
int twoD[][] = new int[2][];
twoD[0] = new int[1];
twoD[1] = new int[2];

 Initializing Multidimensional Arrays:


double[][] m = {
{0.0, 0.0, 0.0},
{0.0, 1.0, 2.0},
{0.0, 2.0, 4.0}};
Arrays

 3D Arrays Example:
int[][][] threeD = new int[3][4][5];
Accessed via threeD[i][j][k]

 Alternative Declaration Syntax:


int[] a1 = new int[3];
int a2[] = new int[3]; // Same
Arrays

 1D Arrays Example:
int[] arr = {10, 20, 30, 40, 50};

 2D Arrays Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Arrays

 3D Arrays Example:
[depth][row][column]

int[][][] arr3D = {
{ {1, 2},
{3, 4} },
{ {5, 6},
{7, 8} }};
Operators

 Arithmetic Operators:
Operators

 Modulus Operators: The modulus operator, %, returns the remainder of a division


operation. It can be applied to floating-point types as well as integer types.
Operators

 The Boolean Logical Operators:


Operators

 The Relational Operators:


Operators

 The Assignment Operators:


The assignment operator works in Java much as it does in any other computer language. It
has this
general form: var = expression;
int x, y, z; x = y = z = 100; // set x, y, and z to 100

 The ? Operator: a special ternary (three-way) operator that can replace certain types
of if-then-else statements
general form: expression1 ? expression2 : expression3
Ex: i<10 ? True : False;
Control Statements

 Selection Statements Java supports two selection statements: if and switch


 If statement:
Syntax:
if (condition) statement1;
else statement2;

Ex: int a, b;
//...
if(a < b)
a = 0;
else b = 0;
Control Statements

 Nested ifs
Example:
Control Statements

 The if-else-if Ladder


 Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else statement;
Control Statements

 The if-else-if Ladder Example:


if (marks >= 90) {
[Link]("Grade: A+");
} else if (marks >= 80) {
[Link]("Grade: A");
} else if (marks >= 70) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");}
else {
[Link]("Grade: F (Fail)"); }
Control Statements

 switch:
switch (expression)
{
case value1: // statement sequence break;
case value2: // statement sequence break;
...
case valueN : // statement sequence break;
default: // default statement sequence
}
Control Statements

 Switch example:

switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
………
default:
[Link]("Invalid day number");
}
Control Statements

 Iteration Statement: while


 Syntax:
Output:
while(condition) Count is: 1
{ // body of loop } Count is: 2
Count is: 3
Count is: 4
Count is: 5
Ex:
int count = 1;
while (count <= 5) {
[Link]("Count is: " + count);
count++; }
Control Statements

 Iteration Statement: do-while


 Syntax:
Output:
do { // body of loop } Count is: 1
while (condition); Count is: 2
Count is: 3
Ex: Count is: 4
Count is: 5
int count = 1;
do {
[Link]("Count is: " + count);
count++;
} while (count <= 5);
Control Statements

 For Loop
 Syntax:
For(initialization; condition; iteration)
Output:
{//Body}
Number: 1
Ex: Number: 2
Number: 3
public class ForLoopExample { Number: 4
public static void main(String[] args) { Number: 5

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


[Link]("Number: " + i);
} } }
Control Statements

 For Loop, Using the Comma


 Example:

Output:
a=1
b=4
a=2
b=3
Control Statements

 Enhanced for
 Example:
Control Statements

 Nested Loops
 Example:
Jump Statements

 Using break
 Example:
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
Jump Statements

 Using break as goto: Syntax: break label_name;


 Example:

Output:
Before the break.
This is after second block.
Jump Statements

 Using continue
 Example:

Output:
01
23
45
67
89
Jump Statements

 Using return: The return statement is used to explicitly return from a method
 Example:

Output:
Before the return.

You might also like