0% found this document useful (0 votes)
6 views

Unit - 1

The document outlines the syllabus for an introductory unit on Object-Oriented Programming (OOP) and Java, covering key concepts such as procedural vs. object-oriented development, Java basics, and OOP principles like inheritance and polymorphism. It details the advantages of OOP, Java features, and differences between Java and C++, as well as Java architecture components like JVM, JRE, and JDK. Additionally, it includes practical examples of Java programming, specifically user input handling using the Scanner class.

Uploaded by

Devansh Mohar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit - 1

The document outlines the syllabus for an introductory unit on Object-Oriented Programming (OOP) and Java, covering key concepts such as procedural vs. object-oriented development, Java basics, and OOP principles like inheritance and polymorphism. It details the advantages of OOP, Java features, and differences between Java and C++, as well as Java architecture components like JVM, JRE, and JDK. Additionally, it includes practical examples of Java programming, specifically user input handling using the Scanner class.

Uploaded by

Devansh Mohar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Unit - 1

Syllabus
• Procedural vs. object-oriented development,
• basic concepts of object-oriented programming,
• applications and benefits of OOP
• Java Basics: Java as Object-oriented Programming Language
• History of Java,
• Features of Java,
• Difference between Java and C++,
• Java Architecture (JDK, JVM, JRE), Java Tokens:
• Basics of Java programming: Data types, Literals, Variables, Scope and
lifetime of variables,
• Operators. Control Structures including selection, Looping, Arrays.
Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the program


divided into small parts called functions. is divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no In object-oriented programming, the concept


concept of data hiding and inheritance. of data hiding and inheritance is used.
in procedural programming, the function In object-oriented programming, data is
is more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Code reusability absent in procedural Code reusability present in object-


programming, oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
basic concepts of object-oriented programming

• The aim of object-oriented programming is to implement real-world


entities.
• Example: object, classes, abstraction, inheritance, polymorphism, etc
• Simula is considered the first object-oriented programming language.
• Smalltalk is considered the first truly object-oriented programming
language.
• The popular object-oriented languages are Java, C#, PHP, Python, C++,
etc.
OOPs (Object-Oriented
Programming)
• Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects.
• Following terms are used in Object-Oriented design:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object :
• Object means a real-world entity such as a pen, chair, table, computer,
watch, etc.
• Any entity that has state and behavior is known as an object.
• example, a chair, pen, table, keyboard, bike, etc.
It can be physical or logical.
Class :
• Collection of objects is called class. It is a logical entity.
• A class can also be defined as a blueprint from which you can create an
individual object.
• A class is a user-defined data type. It consists of data members and member
functions.
• Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like
all of them will have 4 wheels, Speed Limit, Mileage range, etc.
• Inheritance :
• When one object acquires all the properties and behaviors of a parent object or
class, it is known as inheritance.
• Inheritance allows the user to reuse the code whenever possible and reduce
its redundancy.
• Polymorphism:
• The word polymorphism means having many forms.
• Polymorphism is the ability of a message to be displayed in more than one
form.
• Example : A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person
posses different behavior in different situations. This is called polymorphism.
• Abstraction
• Hiding internal implementation and showing functionality only to the user is
known as abstraction.
• Example : phone call, we do not know the internal processing.
• Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
• Example, a capsule, it is wrapped with different medicines.
• In Encapsulation, the variables or data of a class are hidden from any other
class and can be accessed only through any member function of their class in
which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
• Eg : The finance section handles all the financial transactions and keeps records
of all the data related to finance. Similarly, the sales section handles all the
sales-related activities and keeps records of all the sales. Now there may arise a
situation when for some reason an official from the finance section needs all
the data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular
data. This is what encapsulation is.
• Advantages of OOP

• Modularity: OOP divides complex systems into smaller components.


• Reusability: Inheritance allows code reuse, improving code quality and saving
time.
• Encapsulation: Protects data integrity and privacy by restricting direct access
and allowing controlled access through methods.
• Flexibility and Scalability: OOP enables easy addition and modification of
features without impacting the entire codebase.
• Code Maintenance: Changes and bug fixes can be made to specific objects or
classes without affecting other parts of the system, reducing errors and
improving debugging.
• Code Reusability: OOP encourages the development of reusable code
elements, saving time and improving system reliability.
• Better Problem Solving: OOP models real-world systems, allowing developers
to create intuitive solutions that closely real-world circumstances.
Java User Input (Scanner)

• The Scanner class is used to get user input, and it is found in the
java.util package.
• To use the Scanner class, create an object of the class and use any of
the available methods found in the Scanner class documentation.
• Input Types
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
• import java.util.Scanner;
• public class circle
• {
• public static void main(String args[])
• {
• int x, y, sum;
• Scanner sc=new Scanner(System.in);
• System.out.print("Enter the first number: ");
• x= sc.nextInt();
• System.out.print("Enter the second number: ");
• y=sc.nextInt();
• sum=x+y;
• System.out.println("The sum of two numbers x and y is: " + sum);
• }
• }
Java OOP(Object Oriented Programming) Concepts

• Object-Oriented Programming or Java OOPs concept refers to


programming languages that use objects in programming.
• Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc. in programming.
• The main aim of OOPs is to bind the data and the functions together
that operate on them so that no other part of the code can access this
data except that function.
• History of Java : Java was originally developed by Sun
Microsystems by James Gosling in 1995, who is known as the father of
Java. James Gosling and his team members started the project in the
early '90s.
• Java was originally designed for digital devices such as set-top boxes,
televisions, etc.
• Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc.
• Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic”.
Features of Java Programming
Language
• Java is one of the most popular and commonly used programming languages.
• It is widely recognized for its performance, platform independence, and security.
• Java is a server-side language for back-end development, Android development,
desktop computing, games, and numerical computing.
• some of the most important features of Java programming:
• 1. Inspired by C and C++
• Java is inspired by C and C++. The syntax of Java is similar to these languages, but the languages
are quite different.
• Java inherits many features from C and C++.
• Compared to C++, Java code runs a bit slower, but it is more portable and offers better security
features.
• 2. Object-Oriented
• Java is a fully object-oriented language, unlike C++, which is semi-object-oriented.
• It supports every OOP concept, such as Abstraction, Encapsulation, Inheritance, and
Polymorphism.
• Another notable feature is that the main() function is defined under a class in Java.
• 3. Platform Independent
• Java’s platform independence means that Java programs compiled on one machine or operating
system can be executed on any other machine or operating system without modifications.
• It is also called an Architecture Neutral Language.
• Java supports WORA (Write Once, Run Anywhere), meaning programmers can develop
applications in one operating system and run on any other without any modification.
• 4. Compiled and Interpreted
• Java offers both compilation and interpretation of programs.
• When a Java program is created, the Java compiler (javac) compiles the Java source code into byte
code.
• The Java Virtual Machine (JVM) is an interpreter that converts byte code to machine code, which is
portable and can be executed on any operating system.
• 5. Multi-Threaded
• Java supports multithreading programming.
• A thread is an independent process to execute a set of statements.
• The term multi-threaded refers to creating multiple threads to handle multiple tasks
simultaneously.
• Threads are independent, so one thread does not affect the other
• JVM uses multiple threads to execute different blocks of code of the same program in parallel.
• 6. Dynamic
• Java is more dynamic compared to C and C++.
• It allows programmers to link new class libraries, objects, and methods
dynamically.
• 7. Robust
• The English meaning of Robust is strong.
• Java is a robust language that can handle run-time errors by checking the code
during the compilation and runtime.
• There is a lack of pointers that avoids security problems.
• It also supports the concepts of garbage collection and exception handling.
• 8. Secure
• Java is a secure language that ensures that programs cannot access the memory
locations without authorization.
• 9. High Performance
• Java offers high performance using the JIT (Just In Time) compiler.
• The compiler only compiles that method which is being called.
Difference b/w C++ and Java
Basic C++ Java
Platform Dependency C++ code is platform-dependent, that is code Java is platform-independent. Java
written in C++ may need to be recompiled to run code is compiled into bytecode,
on different platforms. which can run on any platform.
Primarily Used For It is often used for system-level programming, It is commonly used for web
game development, embedded systems, and applications, mobile app
performance-critical applications. development (Android), enterprise
software, etc
Goal of Design C++ was designed with a focus on performance Java was designed with a focus on
and efficiency, allowing low-level memory portability, simplicity, and ease of
manipulation. use, promoting platform
independence and security
goto C++ supports the use of the "goto" statement for Java omits support for the "goto"
branching. statement

Inheritance from C++ supports multiple inheritance, meaning a Java allows multiple inheritance
Multiple Sources class can inherit from multiple base classes. through interfaces,
Difference b/w C++ and Java
Basic C++ Java
Operator Overloading
C++ supports both method overloading Java supports only method
and operator overloading overloading
Pointers C++ includes pointers, which allow direct memory Java does not have pointers
manipulation and access.
Level of Programming C++ allows both high-level and low-level Java is primarily a high-level
programming, making it suitable for system-level language with a focus on simplicity
and performance-critical tasks. and portability.
Structure and Union C++ supports structures and unions, which are Java does not have built-in support
used for grouping related data members. for structures or unions; instead, it
uses classes for data encapsulation.
Garbage C++ needs manual garbage memory Java has an automatic
collection clearance garbage collector

C++ needs manual class and object Java is completely


management using new and delete automatic regarding class
keywords and object management
• Java Architecture :
• In Java, there is a process of compilation and interpretation.
• The code written in Java, is converted into byte codes which is done by the
Java Compiler.
• This byte codes, are converted into machine code by the JVM.
• Then this Machine code is executed directly by the machine.
Components of Java Architecture

• There are three main components of Java language: JVM(Java Virtual


Machine), JRE(Java Runtime Environment ), and JDK(Java
Development Kit).
• JVM :
• The JVM is a Java platform component which can be used for executing the
Java programs.
• JVM interprets the bytecode into machine code which is executed in the
machine in which the Java program runs.
• JVM performs the following functions:
• Loads the code
• Verifies the code
• Executes the code
• Provides runtime environment
JVM Architecture
• Class Loader: Class loader is a subsystem of JVM. It is used to load class files.
Whenever we run the java program, class loader loads it first.
• Class method area: It is one of the Data Area in JVM, in which Class data will
be stored. Static Variables, Static Blocks, Static Methods, Instance Methods
are stored in this area.
• Heap: A heap is created when the JVM starts up. It may increase or decrease
in size while the application runs.
• Stack: JVM stack is known as a thread stack. It is a data area in the JVM
memory which is created for a single execution thread. The JVM stack of a
thread is used by the thread to store various elements i.e.; local variables,
partial results, and data for calling method and returns.
• Java Native Interface
• Java Native Interface (JNI) : is a framework which provides an interface to
communicate with another application written in another language like C, C+
+,
• JIT compiler:
• The Just-In-Time (JIT) compiler is a part of the runtime environment.
• It translates bytecode into machine code, which is executed directly by the
computer's processor.
• The JIT compiler is enabled by default.
• When a method is compiled, the JVM calls the compiled code of that method
directly.
Jit : JIT compiler consists of various components such as :
1. Intermediate Code : intermediate code, commonly known as
bytecode, is the form into which the Java compiler translates source
code. This bytecode is a set of instructions that the Java Virtual
Machine (JVM) can execute.
2. Code Optimizer : to improve the efficiency and performance of Java
programs. This involves reducing execution time, minimize memory
usage, and enhance overall code quality.
3. Target code generator : target code can be machine readable code.
4. Garbage collector : The garbage collector in Java is a process that
automatically deletes unused code and frees up memory. This
makes it easier for developers to write Java applications.
• JDK :
• is a software development environment used for developing Java applications
and applets. It includes a collection of tools, libraries, and executables
necessary for compiling, debugging, and running Java programs. Some
development tools are :
• Java
• Javac
• Jar
• Javadoc
• jdb
• Components of the JDK
• The JDK consists of several key components:
• Java Compiler (javac):
• Converts Java source code (.java files) into bytecode (.class files) that
can be executed by the Java Virtual Machine (JVM).

• Java Runtime Environment (JRE):


• Includes the JVM, class libraries, and other components necessary to
run Java applications.
• The JRE is a subset of the JDK.

• Java Virtual Machine (JVM):


• Executes Java bytecode and provides platform independence.
• Java Debugger (jdb):
• A command-line tool for debugging Java programs.

• Java Archiver (jar):


• Packages Java classes and resources into a single .jar file for distribution.

• Java Documentation Generator (javadoc):


• Generates API documentation in HTML format from Java source code
comments.

• Java Interpreter (java):


• Executes Java applications by running the bytecode on the JVM.
• JRE : stands for java run time environment.
• It provides a runtime environment that helps to run java programs.
• The Java Runtime Environment (JRE) is an implementation of JVM.
• It is a type of software package that provides class libraries of Java, JVM, and various
other components for running the applications written in Java programming.
• JRE has a major responsibility for creating an environment for the execution of code.
• JRE, on the other hand, does not consist of any tool- like a debugger, compiler, etc.
• It contains various supporting files for JVM, and the class libraries that help JVM in
running the program.
• JRE uses crucial package classes like util, math, awt, lang, and various runtime libraries.
• A developer can easily run a source code in JRE. But it does not allow them to write
and compile the concerned Java program.
• JRE also contains various integration libraries like the JDBC (Java Database
Connectivity), JNDI (Java Naming and Directory Interface), RMI (Remote Method
Invocation), and many more.
•Examples: class, public, static, void, int, if, else, for, while, etc.

• Java Tokens : tokens is the smallest elements of a program that is


identified by a compiler.
• Every java statements and expression are created by tokens.
• They are the building blocks of Java code and are used to construct
statements, expressions, and other structures.
• Some tokens are : keyword : Reserved words with predefined meanings in
Java.(48 nos)
• Examples: class, public, static, void, int, if, else, for, while, etc.
• Identifiers : Names given to variables, methods, classes, interfaces, etc.
• Rules:
• Must start with a letter, underscore (_), or dollar sign ($).
• Cannot start with a digit.
• Cannot be a keyword.
• Case-sensitive.
• Examples: myVariable, calculateSum, MyClass, MAX_VALUE.
• Operator : Symbols used to perform operations on variables and
values.
• Types:
• Arithmetic: +, -, *, /, %.
• Relational: ==, !=, >, <, >=, <=.
• Logical: &&, ||, !.
• Assignment: =, +=, -=, *=, /=.
• Bitwise: &, |, ^, ~, <<, >>, >>>.
• Ternary: ? :.
• Separator : Symbols used to separate and organize code.
• Examples:
• Parentheses: () for method parameters and expressions.
• Braces: {} for blocks of code.
• Brackets: [] for arrays.
• Semicolon: ; to terminate statements.
• Comma: , to separate items in a list.
• Dot: . to access members of a class or object.
• Literals : Constant values assigned to variables or used directly in code.
• Types:
• Integer literals: 10, 0xFF (hexadecimal), 0b1010 (binary).
• Floating-point literals: 3.14, 2.0e-5.
• Character literals: 'A', '\n' (newline), '\t' (tab).
• String literals: "Hello, World!".
• Boolean literals: true, false.
• Null literal: null.
• Comments : Non-executable text used in document.
• Types:
• Single-line: // This is a comment.
• Multi-line: /* This is a multi-line comment */.
• Documentation: /** This is a Javadoc comment */.
• Literals : literals are constant values that are directly written in the source code.
• They represent fixed values that can be assigned to variables or used in expressions.
• Java supports several types of literals, depending on the data type.
• Integer Literals
• Represent whole numbers.
• Can be written in decimal, hexadecimal, binary, or octal formats.
• Examples:
• int decimal = 123; // Decimal literal
• int hexadecimal = 0x1A; // Hexadecimal literal (starts with 0x)
• int binary = 0b1101; // Binary literal (starts with 0b)
• int octal = 0123; // Octal literal (starts with 0)
• By default, integer literals are of type int. For long, append L or l:
• long bigNumber = 1234567890L;

• 2. Floating-Point Literals
• Represent decimal numbers.
• Can be written in standard or scientific notation.
• Examples:
• double decimal = 3.14; // Standard decimal notation
• double scientific = 2.5e-3; // Scientific notation (2.5 × 10^-3)
• By default, floating-point literals are of type double. For float, append F or f:
• float pi = 3.14F;
• 3. Character Literals
• Represent a single Unicode character.
• Enclosed in single quotes (').
• Examples:
• char letter = 'A';
• char escape = '\n'; // Escape sequence for newline
• char unicode = '\u0041'; // Unicode for 'A'

• Common escape sequences:


• \n - Newline
• \t - Tab
• \\ - Backslash
• \' - Single quote
• \" - Double quote

• 4. String Literals
• Represent a sequence of characters.
• Enclosed in double quotes (").
• Examples:
• String greeting = "Hello, World!";
• String escape = "This is a \"quote\"."; // Escaping double quotes
• Strings are immutable in Java.
• 5. Boolean Literals
• Represent logical values.
• Only two possible values: true or false.
• Examples:
• boolean isJavaFun = true;
• boolean isRaining = false;

• 6. Null Literal
• Represents a null reference (no object).
• Used for object references.
• Example:
• String str = null; // No object is assigned to 'str'

• 7. Class Literals
• Represents a Class object for a specific type.
• Formatted as <type>.class.
• Example:
• Class<?> clazz = String.class; // Represents the String class
• public class LiteralsExample {
• public static void main(String[] args) {
• // Integer literals
• int decimal = 42;
• long bigNumber = 1234567890L;
• // Floating-point literals
• double pi = 3.14159;
• float gravity = 9.8F;
• // Character literals
• char grade = 'A';
• char newline = '\n';
• // String literals
• String message = "Hello, Java!";
• // Boolean literals
• boolean isJavaEasy = true;
• // Null literal
• String empty = null;
• // Output
• System.out.println(decimal);
• System.out.println(bigNumber);
• System.out.println(pi);
• System.out.println(gravity);
• System.out.println(grade);
• System.out.println(message);
• System.out.println(isJavaEasy);
• System.out.println(empty);
• }
•}
• Datatypes : data types define the type of data that a variable can hold.
• Java is a strong-typed language, which means that the data type of a variable must be declared before it
can be used. Java data types are broadly categorized into two groups:
• Primitive Data Types
• Non-Primitive Data Types (Reference Types)
• 1. Primitive Data Types
• Primitive data types are the most basic data types in Java. They are predefined by the language and are
not objects. There are 8 primitive data types in Java, divided into four categories:
• a. Integer Types : Store whole numbers (positive, negative, or zero).
• Types:
• byte: 8-bit signed integer. Range: -128 to 127.
• short: 16-bit signed integer. Range: -32,768 to 32,767.
• int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
• long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.

• Examples:
• byte b = 100;
• short s = 1000;
• int i = 100000;
• long l = 1000000000L; // Use 'L' or 'l' for long literals
• b. Floating-Point Types : Store decimal numbers.
• Types:
• float: 32-bit single-precision floating-point. Range: ~±3.4e38.
• double: 64-bit double-precision floating-point. Range: ~±1.7e308.
• Examples:
• float f = 3.14F; // Use 'F' or 'f' for float literals
• double d = 3.14159;

• c. Character Type : Stores a single Unicode character.


• Type:
• char: 16-bit Unicode character. Range: \u0000 to \uffff.
• Examples:
• char c = 'A';
• char unicode = '\u0041'; // Unicode for 'A'
• d. Boolean Type : Stores logical values.
• Type:
• boolean: Represents true or false.
• Examples:
• boolean isJavaFun = true;
• boolean isRaining = false;
• 2. Non-Primitive Data Types (Reference Types): Non-primitive data
types are also called reference types because they refer to objects.
They are not predefined and are created by the programmer. They
include:
• a. Classes : User-defined data types :
• Example:
• class Person {
• String name;
• int age;
•}
• Person p = new Person(); // 'p' is a reference to a Person object
• b. Interfaces : Define a contract for classes to implement.
• Example:
• interface Drawable
•{
• void draw();
•}
• c. Arrays : Store multiple values of the same type.
• Example:
• int[] numbers = {1, 2, 3, 4, 5};
• String[] names = {"Alice", "Bob", "Charlie"};
• d. Strings : A sequence of characters.
• Example:
• String greeting = "Hello, World!";
• public class DataTypesExample
• {
• public static void main(String[] args)
• {
• // Primitive data types
• byte b = 100;
• short s = 1000;
• int i = 100000;
• long l = 1000000000L;
• float f = 3.14F;
• double d = 3.14159;
• char c = 'A';
• boolean isJavaFun = true;
• // Non-primitive data types
• String greeting = "Hello, World!";
• int[] numbers = {1, 2, 3, 4, 5};
• // Output
• System.out.println("byte: " + b);
• System.out.println("short: " + s);
• System.out.println("int: " + i);
• System.out.println("long: " + l);
• System.out.println("float: " + f);
• System.out.println("double: " + d);
• System.out.println("char: " + c);
• System.out.println("boolean: " + isJavaFun);
• System.out.println("String: " + greeting);
• System.out.println("Array: " + Arrays.toString(numbers));
• }
•}
Scope of a variable
• Scope of a variable refers to in which areas or sections of a program the variable
will be accessed and
• lifetime of a variable means how long the variable stays alive in memory. three
types of variables:
• 1) instance variables : These variables must be declared inside class (outside any
function). They can be directly accessed anywhere in class.
• 2)class variables or static variable : Static Variables are the variables which once
declared can be used anywhere even outside the class without initializing the
class.
• 3) local variables : Local variables are those that are declared inside of a
method, constructor, or code block. Only the precise block in which they are
defined is accessible. Temporary data is stored in local variables, which are
frequently initialised in the block where they are declared.
Instance variable example
• public class Test {
// All variables defined directly inside a class
// are member variables
int a;
private String b;

void method1() {….}


int method2() {….}

char c;
}
• // Define a class named "Student"
• class student
• {
• // Instance variables
• private String name; // Stores the name of the student
• private int age; // Stores the age of the student
• private double gpa; // Stores the GPA of the student
• // Constructor to initialize instance variables
• public student(String name, int age, double gpa)
• {
• this.name = name;
• this.age = age;
• this.gpa = gpa;
• }
• // Method to display student details
• public void displayDetails()
• {
• System.out.println("Name: " + name);
• System.out.println("Age: " + age);
• System.out.println("GPA: " + gpa);
• }
• public class student
• {
• /* declaration of instance variables. */
• public String name; //public instance
• String division; //default instance
• private int age; //private instance
• /* Constructor that initialize an instance variable. */
• public student(String sname)
• {
• name = sname;
• }
• /* Method to intialize an instance variable. */
• public void setDiv(String sdiv)
• {
• division = sdiv;
• }
• /* Method to intialize an instance variable. */
• public void setAge(int sage)
• {
• age = sage;
• }
• /* Method to display the values of instance variables. */
• public void printstud()
• {
• System.out.println("Student Name: " + name );
• System.out.println("Student Division: " + division);
• System.out.println("Student Age: " + age);
• }

• /* Driver Code */
• public static void main(String args[])
• {
• student s = new student("Monica");
• s.setAge(14);
• s.setDiv("B");
• s.printstud();
• }
• }
• // Main class to test the Student class

• public static void main(String[] args)


• {
• // Create objects of the Student class
• student student1 = new student("Alice", 20, 3.8);
• student student2 = new student("Bob", 22, 3.5);

• // Display details of the students


• System.out.println("Student 1 Details:");
• student1.displayDetails();

• System.out.println("\nStudent 2 Details:");
• student2.displayDetails();
• }
• }
Static variable example

• // Using Static variables


• import java.io.*;

• class Test{
• // static variable in Test class
• static int var = 10;
• }

• class Geeks
• {
• public static void main (String[] args) {
• // accessing the static variable
• System.out.println("Static Variable : "+Test.var);
• }
• }
• public class student {

• // static variable
• static int age;
• // static method
• static void display() {
• System.out.println("Static Method");
• }
• public static void main(String[] args) {

• // access the static variable


• age = 30;
• System.out.println("Age is " + age);

• // access the static method


• display();
• }
• }
Local variable

• public SumExample
•{
• public void calculateSum() {
• int a = 5; // local variable
• int b = 10; // local variable
• int sum = a + b;
• System.out.println("The sum is: " + sum);
• } // a, b, and sum go out of scope here
•}
Control Structure
• Java compiler executes the code from top to bottom.
• The statements in the code are executed according to the order in
which they appear.
• 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.
• Decision Making statements
• if statements
• switch statement
• Loop statements
• do while loop
• while loop
• for loop
• for-each loop
• Jump statements
• break statement
• continue statement
Decision-Making statements:
• decision-making statements decide which statement to execute and when.
• There are two types of decision-making statements in Java,
• If statement : "if" statement is used to evaluate a condition.
• the If statement gives a Boolean value, either true or false.
• In Java, there are four types of if-statements :
• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement

• switch statement :
• 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.
• The case variables can be int, short, byte, char, or enumeration.
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression.
• Break statement terminates the switch block when the condition is satisfied.

• if Statement : Executes a block of code if a condition is true.
• // Simple If statement
• public class new2
• {
• public static void main(String[] args) {
• int x = 10;
• int y = 12;
• if(x+y > 20) {
• System.out.println("x + y is greater than 20");
• }}}
• if-else Statement : Executes one block of code if the condition is true, and another block if the condition is false.
• // If else statement
• public class new2
• {
• public static void main(String[] args) {
• int x = 10;
• int y = -12;
• if(x+y < 10)
• {
• System.out.println("x + y is less than 10");
• }
• else
• {
• System.out.println("x + y is greater than 20");
• // else if ladder : Checks multiple conditions in sequence.
• public class new2
• {
• public static void main(String[] args)
• {
• String city = "Delhi";
• if(city == "Meerut")
• {
• System.out.println("city is meerut");
• }
• else if (city == "Noida")
• {
• System.out.println("city is noida");
• }
• else if(city == "Agra")
• {
• System.out.println("city is agra");
• }else
• {
• System.out.println(city);
• }}}
• nested if statements are used when you need to check multiple
conditions in a hierarchical manner.

• 1. checks if a number is positive, negative, or zero, and further checks


if the positive number is even or odd.
• 2. assigns a grade based on the marks obtained by a student.
• 3. checks the username and password for a login system.
• 4. checks if a person is eligible for a roller coaster ride based on their
age and height.
• 5. to determine if a person is eligible for a loan.
class student
{
public static void main(String[] args)
{
int number = 10;
if (number > 0)
{
System.out.println("The number is positive.");

// Nested if
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
}
else if (number < 0)
{
System.out.println("The number is negative.");
} else
{
System.out.println("The number is zero.");
Switch examples

• WAP to calculates the grade based on a student's score.


• WAP to prints the name of the day based on a number (1 = Monday, 2
= Tuesday, etc.).
• WAP to performs basic arithmetic operations (addition, subtraction,
multiplication, division) based on user input.
• WAP to simulates a traffic light system.
• WAP to determines the number of days in a given month.
• Enhanced Switch: This example uses the enhanced switch syntax with arrow (->)
and multiple case labels.
• public class new2 {
• public static void main(String[] args) {
• String fruit = "kiwi";
• switch (fruit)
• {
• case "apple", "banana", "orange" -> System.out.println("Common fruit");
• case "mango", "guava" -> System.out.println("Tropical fruit");
• case "dragon fruit", "kiwi" -> System.out.println("Exotic fruit");
• default -> System.out.println("Unknown fruit");
• }
• }
•}
• public class new2 {
• public static void main(String[] args) {
• int month = 2; // February
• int year = 2024; // Leap year
• switch (month) {
• case 1: case 3: case 5: case 7: case 8: case 10: case 12:
• System.out.println("31 days");
• break;
• case 4: case 6: case 9: case 11:
• System.out.println("30 days");
• break;
• case 2:
• if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
• System.out.println("29 days (Leap Year)");
• } else {
• System.out.println("28 days");
• }
• break;
• default:
• System.out.println("Invalid month!");
• }}}
• Looping Statements :
• These statements allow you to execute a block of code repeatedly. Or 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.
• for Loop : Repeats a block of code a specific number of times.
• for (initialization; condition; update)
• {
• // Code to execute in each iteration
• }
• while Loop : Repeats a block of code as long as a condition is true.
• while (condition) {
• // Code to execute while condition is true
• }
• do-while Loop : Similar to the while loop, but the block of code is executed at least once, even if the
condition is false.

• do {
• // Code to execute at least once
• } while (condition);
• WAP to print sum of first 10 Natural numbers using For Loop
• public class new2
•{
• public static void main(String[] args)
•{
• int sum = 0;
• for(int j = 1; j<=10; j++)
•{
• sum = sum + j;
•}
• System.out.println("The sum of first 10 natural numbers is " + sum);
• }}
• WAP to print the list of first 10 even numbers using While Loop
• public class new2
• {
• public static void main(String[] args)
• {

• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• while(i<=10)
• {
• System.out.println(i);
• i = i + 2;
• }}}
• // WAP to print the list of first 10 even numbers using do While Loop
• public class new2
• {
• public static void main(String[] args)
• {
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• do
• {
• System.out.println(i);
• i = i + 2;
• }while(i<=10);
• }
• }
• Jump Statements : These statements allow you to transfer control to another part of the program.
• There are two types of jump statements in Java, i.e., break and continue.
break Statement : Exits a loop or switch statement.
The break statement cannot be used independently in the Java
program, i.e., it can only be written inside the loop or switch statement.
Example :
• public class new2
• {
• public static void main(String[] args)
• {
• for(int i = 0; i<= 10; i++)
• {
• System.out.println(i);
• if(i==6)
• {
• break;
• }}}}
• Continue : the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop.
• public class new2
• {
• public static void main(String[] args)
• {
• for(int i = 0; i<= 2; i++)
• {
• for (int j = i; j<=5; j++)
• {
• if(j == 4)
• {
• continue;
• }
• System.out.println(j);
• }}}
• Arrays : Arrays is used to store multiple values of the same data type
in a single variable.
• They are fixed in size, meaning once an array is created, its size cannot
be changed.
• Arrays are indexed, starting from 0, and can store primitive data types
(e.g., int, char, double) or objects (e.g., String)
• Features :
• Fixed Size: The size of an array is defined at the time of creation and cannot
be changed.
• Indexed: Elements in an array are accessed using their index (starting from 0).
• Homogeneous: All elements in an array must be of the same data type.
• Memory Efficiency: Arrays are stored in contiguous memory locations, making
them efficient for accessing elements.
• Declaring and Initializing Arrays
• 1. Declaring an Array :
• dataType[] arrayName; // Preferred way
• // or
• dataType arrayName[];
• Example:
• int[] numbers; // Declares an array of integers
• String[] names; // Declares an array of strings

• 2. Initializing an Array : Arrays can be initialized using the new keyword or with predefined values.
• Using new Keyword:
• arrayName = new dataType[size];
• Example:
• numbers = new int[5]; // Creates an array of size 5
• names = new String[3]; // Creates an array of size 3
• With Predefined Values:
• dataType[] arrayName = {value1, value2, value3, ...};
• Example:
• int[] numbers = {10, 20, 30, 40, 50}; // Array of size 5
• String[] names = {"Alice", "Bob", "Charlie"}; // Array of size 3
• Accessing Array Elements : Array elements are accessed using their index. The index starts at 0 and goes up to
arrayLength - 1.
• int[] numbers = {10, 20, 30, 40, 50};
• System.out.println(numbers[0]); // Output: 10
• System.out.println(numbers[2]); // Output: 30
• Using for Loop : We can use the for loop to iterate over an array by taking advantage of index numbers.
• public class new2
• {
• public static void main(String[] args)
• {
• // declaration of array in java
• int[] myArray = new int[5];
• // Initialization of array with for loop
• for (int i = 0; i < myArray.length; i++)
• {
• myArray[i] = i * 10;
• }
• // Accessing myArray with for loop
• for (int i = 0; i < myArray.length; i++)
• {
• System.out.println("Value at index " + i + " : " + myArray[i]);
• } }}
• Using Arrays.fill() : Fill() method is present in the arrays class which is part
of java.util package.
• This method is useful to initialize the same value at all indices of an array.
• Example :
• import java.util.Arrays;
• public class new2 {
• public static void main(String[] args)
• {
• String[] myArray = new String[5];

• // using fill() method to initialize value at all indices.


• Arrays.fill(myArray, "Hello");

• // printing the values from myArray


• for (int i = 0; i < myArray.length; i++)
• {
• System.out.println("Value at index " + i + " : " + myArray[i]);
• Multidimensional Arrays : A multidimensional array is an array of arrays.
• Example : int[][] a = new int[3][4];
• Example :

• class new2 {
• public static void main(String[] args)
• {

• // create a 2d array
• int[][] a = {
• {1, 2, 3},
• {4, 5, 6, 9},
• {7},
• };

• // calculate the length of each row
• System.out.println("Length of row 1: " + a[0].length);
• System.out.println("Length of row 2: " + a[1].length);
• System.out.println("Length of row 3: " + a[2].length);
• }
• }
Examples

• WAP to adds two matrices and stores the result in a third matrix.
• WAP to multiplies two matrices and stores the result in a third matrix.
• WAP to finds the transpose of a matrix (rows become columns and
vice versa).
• WAP to searches for a specific value in a 2D array.
// Search specific element
public class new2 {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 8;
boolean found = false;
// Searching for the target
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
found = true;
System.out.println("Element " + target + " found at position: (" + i + ", " + j + ")");
break;
}}
if (found) break;
}
if (!found) {
System.out.println("Element " + target + " not found in the matrix.");
• Three-Dimensional (3D) Array : A 3D array is an array of 2D arrays. It can be thought
of as a cube with layers, rows, and columns.
• You can use three nested loops to iterate over a 3D array.
• Declaration and Initialization
• // Syntax
• dataType[][][] arrayName = new dataType[layers][rows][columns];
• Example:
• int[][][] cube = new int[2][3][3]; // 2 layers, each with 3 rows and 3 columns

• For example:
• int[ ][ ][ ] x = new int[2][3][4];

• x[0][0][0] refers to the data in the first table, first row, and first column.
• x[1][0][0] refers to the data in the second table, first row, and first column.
• x[1][2][3] refers to the data in the second table, third row, and fourth column.
• student1 scores: 75, 87, 69
• student2 scores: 90, 87, 85
• student3 scores: 56, 67, 76

• student1 scores: 78, 67, 75


• student2 scores: 87, 98, 76
• student3 scores: 67, 56, 65

• student1 scores: 72, 63, 72


• student2 scores: 82, 91, 71
• student3 scores: 64, 56, 66
• Example :
• scores[0][1][0]=90
• scores[0][1][2]= 85
• scores[2][2][0]=64
public class new2
{
public static void main(String[] args)
{
int[ ][ ][ ] x;
x = new int[3][3][3];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
x[i][j][k] = i + 1;
}
for(int i = 0; i < 3; i++)
{
System.out.println("Table-" +(i + 1));
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
System.out.print(x[i][j][k] +" ");
System.out.println();
}
System.out.println();

You might also like