KEMBAR78
Vlsi Oop & Java Unit-1 and 3 | PDF | Java Virtual Machine | Object Oriented Programming
0% found this document useful (0 votes)
8 views53 pages

Vlsi Oop & Java Unit-1 and 3

Uploaded by

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

Vlsi Oop & Java Unit-1 and 3

Uploaded by

nathiyagoutham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

UNIT I INTRODUCTION TO OOP AND JAVA FUNDAMENTALS

Object Oriented Programming - Abstraction – objects and classes - Encapsulation- Inheritance -


Polymorphism- OOP in Java – Characteristics of Java – The Java Environment- Java Source File -
Structure- Compilation.Fundamental Programming Structures in Java – Defining classes in Java –
access specifiers - static members - Data Types, Variables, Operators, Control Flow, Arrays.
1. OBJECT ORIENTED PROGRAMMING

● The word object-oriented is the combination of two words i.e. object and oriented.

⮚ Object is an entity that exists in the real world such as a pen, chair, table, fan, keyboard,

bike, etc.

⮚ The meaning of oriented is interested in a particular kind of thing or entity.

Definition:

⮚ Object-Oriented Programming (OOP) is a programming paradigm based on the concept of

"objects", which contain:

⮚ State (data/variables)

⮚ Behavior (methods/functions)

⮚ It is well suited for programs that are large, complex, and actively updated or maintained.

⮚ A real-world example of OOP is the automobile.

All computer programs consist of two key elements:


● Code (instructions)
● Data (information that code acts upon)
Based on how we organize these, programming can follow two paradigms:
1. Process-Oriented Model:
● Focuses on "what is happening" (the process or actions)
● Organized around functions or procedures.
● Data is usually shared globally.
● Common in procedural languages like C.
● Suitable for simple and small applications.
Example:
In a billing system, steps like input, calculation, and output are the focus, not the customer.
2. Object-Oriented Model
● Focuses on "who is being affected" (the objects/entities).
● Organized around classes and objects.
● Data and behavior are bundled inside objects.
● Promotes modularity, reusability, and is suitable for large and complex applications.
● Used in languages like Java, C++, Python.
Example:
In a billing system, the focus is on the Customer object, which has:
Properties: name, bill amount
Methods: viewBill(), payBill()
Advantages of OOP:
• Ability to represents Real Word Entities
• Code Reusability
• Easy Management
• Maintenance
• Abstraction
• Polymorphism
Disadvantages:
• Complex Design
• Many skills
• Large size & Many Instructions
• Slow Speed
Concepts of Object-Oriented Programming

(i) Class
● Class is a blueprint for creating objects by providing member variables, and member
functions.
● A class is an abstract data type which consists of set of objects that share common structure
and a common behavior.
● It consists of data members and member functions (methods), which can be accessed and used by

creating an instance of that class.

Syntax:
class ClassName {
// variables
dataType variable;

// method
void methodName() {
// code
}
}
Example code to declare a class:
public class Student
{
void display()
{
System.out.println(“welcome”);
}
}
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. So here, Car is the
class, and wheels, speed limits, mileage are their properties (data members), brake, accelerator are
methods.
(ii) Objects

● An Object is an instance of a Class.

● When a class is defined, no memory is allocated but when an object is created memory is

allocated.

● Each object contains data and code to manipulate the data.


● Objects can interact without having to know details of each other’s data or code, it is sufficient to

know the type of message accepted and type of response returned by the objects.
Characteristics of Object :
An object has three characteristics:

● State: represents the data (value) of an object.

● Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

● Identity: An object identity is typically implemented via a unique ID. The value of the ID is not

visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
Example: “Dog” is a real-life Object

● Dog has some characteristics like color, Breed, Bark, Sleep, and Eats.

Creating Object :
Syntax 1:
ClassName objName; // Declare Object Reference
objName = new ClassName(); // allocating Memory
Syntax 2:
ClassName objName = new ClassName();
Student s1= new Student();
Accessing member:Members are accessed using object.
Syntax :
objectname.memebername;

● When we create an object (instance) of class then space is reserved in heap memory.
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message deliver.

Abstraction in Java or Object oriented programming is a way to segregate implementation from


interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class
and Object
● An essential component of object oriented programming is Abstraction
● Humans manage complexity through abstraction.
For example people do not think a car as a set of tens and thousands of individual parts. They think of
it as a well-defined object with its own unique behavior.
● This abstraction allows people to use a car ignoring all details of how the engine, transmission
and braking systems work.
● In computer programs the data from a traditional process oriented program can be transformed
by abstraction into its component objects.
● A sequence of process steps can become a collection of messages between these objects.
● Thus each object describes its own behavior.
Encapsulation
The wrapping up of data and methods into a single unit (called class) is known as encapsulation.

● In encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

● It protects data and methods from outside interference and misuse.

Real-life example

● In a company, there are different sections like the accounts section, finance section, sales section,

etc. 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. Here the data of the sales section and the employees that can manipulate them
are wrapped under a single name “sales section”.
(iv) Inheritance

1. The concept allows us to inherit or acquire the properties of an existing class (parent class) into a

newly created class (child class). It is known as inheritance.

2. It provides code reusability.

Syntax:
class ParentClass {
// parent class members
}

class ChildClass extends ParentClass {


// child class members }
Types of Inheritance
Polymorphism
○ Polymorphism is one of the key principles of Object-Oriented Programming (OOP). The
word “Polymorphism” means “many forms.” In Java, polymorphism allows the same method
or object to behave in multiple ways depending on the context. It enhances flexibility and
code reusability.
○ There are two main types of polymorphism in Java:
● Compile-time Polymorphism (Method Overloading):
○ This occurs when multiple methods in the same class have the same name but different
parameters (number, type, or order). The method that gets called is determined at compile
time.
Example:
class Calculator {
void add(int a, int b) {
System.out.println(a + b);
}
void add(double a, double b) {
System.out.println(a + b);
}
}
● Runtime Polymorphism (Method Overriding):
This occurs when a subclass provides its own implementation of a method that is already defined in
its superclass. The method that gets executed is determined at runtime based on the object's actual type.

Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog's version at runtime
}
}
OOP IN JAVA
• Java was developed by Sun Microsystems in the year 1995.
• James Gosling is known as the father of Java.
• Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
• Platform independent: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform independent.
Different Types of Java Applications:
1) Standalone Application

● Also known as Desktop or window-based applications.

● These are traditional software that we need to install on every machine.

● Examples :Media player, antivirus, etc.

● Technology used : AWT and Swing

2) Web Application

● That runs on the server side and creates a dynamic page

● Technology used : Servlet, JSP, Struts, Spring, Hibernate, JSF

3) Enterprise Application
● distributed in nature, such as banking applications, etc.

● Advantages:high-level security, load balancing, and clustering.

● Technology used : EJB

4) Mobile Application

● Application which is created for mobile devices.

● Technology used : Android and Java ME

Java Platforms / Editions :


1) Java SE (Java Standard Edition)

● Java programming platform Includes APIs such as java.lang, java.io, java.net, java.util, java.sql,

java.math etc.

● Includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,

Networking, AWT, Swing, Reflection, Collection, etc.


2) Java EE (Java Enterprise Edition)

● Enterprise platform

● Used to develop web and enterprise applications.

● Built on the top of the Java SE platform.

● It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

● Micro platform which is mainly used to develop mobile applications.

4) JavaFX

● Used to develop rich internet applications.

● It uses a light-weight user interface API

Characteristics of Java:
● Simple – Java has a clean and easy-to-understand syntax, eliminating complex features like pointers
and operator overloading.
● Object-Oriented – Java follows OOP principles such as encapsulation, inheritance, polymorphism,
and abstraction, which improve code modularity and reusability.
● Platform-Independent – Java code is compiled into bytecode, which can run on any operating
system that has a JVM ("Write Once, Run Anywhere").
● Secure – Java provides a secure execution environment with features like runtime checking, no
pointer access, bytecode verification, and sandboxing.
● Robust – Java emphasizes early error detection, strong memory management, and exception
handling to build reliable applications.
● Multithreaded – Java supports multiple threads of execution, enabling the development of high-
performance applications like games, servers, and real-time systems.
● Portable – Java programs are architecture-neutral and can be easily moved from one system to
another without modification.
● High Performance – Java uses a Just-In-Time (JIT) compiler that converts bytecode into machine
code at runtime for better performance.
● Distributed – Java supports distributed computing with built-in networking APIs and technologies
like RMI and EJB, making it suitable for internet-based applications.
● Dynamic – Java supports dynamic loading of classes and libraries during runtime, allowing
flexibility and adaptability in program execution.

The Java Environment:


The Java Development Environment is a collection of tools and components used to write, compile,
run, and debug Java programs. It includes everything needed for developing and executing Java applications.

JVM - Java Virtual Machine :


• JVM is an abstract machine.
• Virtual machine because it doesn't physically exist.
• It is a specification that provides a runtime environment in which Java bytecode can be executed.
• It can also run those programs which are written in other languages and compiled to Java bytecode.
• VMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other
• The JVM performs the following main tasks:
- Loads code
- Verifies code
- Executes code
- Provides runtime environment
Bytecode:.
• Intermediate code generated by java compiler.
• Highly optimized set of instruction designed to be executed by JVM.
• This byte code is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere(WORA).
• Bytecode is the secret behind portability and security
JRE - Java Runtime Environment :

● JRE is an acronym for Java Runtime Environment.

● The Java Runtime Environment is a set of software tools which are used for developing Java

applications.

● It is used to provide the runtime environment.

● It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM

uses at runtime.
JDK - Java Development Kit :

● JDK is an acronym for Java Development Kit.

● The Java Development Kit (JDK) is a software development environment which is used to develop

Java applications and applets.

● It physically exists.

● It contains JRE + development tools.

● The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an

interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),


etc. to complete the development of a Java Application.
Java Source File:
A Java Source File is a plain text file that contains Java code written by the programmer. This file
has a .java extension and is the first step in creating any Java program.
Example:
// File: HelloWorld.java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

Fundamental Programming Structures in Java

Documentation Section

● It is used to improve the readability of the program.

● It consists of comments in Java which include basic information such as the method’s usage or

functionality to make it easier for the programmer to understand it while reviewing or debugging the
code.

● It can appear anywhere in the code.


● The compiler ignores these comments during the time of execution and is solely meant for improving

the readability of the Java program.


Package Statement

● Java that allows you to declare your classes in a collection called package.

● There can be only one package statement in a Java program and it has to be at the beginning of the

code before any class or interface declaration.

● This statement is optional.

● Eg: package student;

Import Statement

● Many predefined classes are stored in packages in Java, an import statement is used to refer to the

classes stored in other packages.

● An import statement is always written after the package statement but it has to be before any class

declaration.

● We can import a specific class or classes in an import statement.

● Eg: import java.util.Date; // Imports the Date class from util package

Interface Section

● This section is used to specify an interface in Java.

● It is an optional section which is mainly used to implement multiple inheritance in Java.

● An interface is a lot similar to a class in Java but it contains only constants and method declarations.

Class Definition

● A Java program may contain several class definitions, classes are an essential part of any Java

program.

● It defines the information about the user-defined classes in a program. A class is a collection of

variables and methods that operate on the fields. Every program in Java will have at least one class
with the main method.
Main Method Class

● The main method is from where the execution actually starts and follows the order specified for the

following statements.
First Java Program | Hello Java Example
• Here we will see how to write a simple program in Java.
The requirements for Hello Java Example

3. For executing any Java program, the following software or application must be properly installed.

⮚ Install Java (JDK) by downloading it. Any version of Java 8 or above 8 is good. Java can be

installed from this link - https://www.oracle.com/java/technologies/downloads/

⮚ Set path of the jdk/bin directory.

⮚ Create the Java program

⮚ Compile and run the Java program

Creating Hello java Example


• To write a simple program, you need to open notepad by clicking on start menu -> All Programs ->
Accessories -> Notepad and type a simple program as shown below:

• Save the file with classname.java


Example: Simple.java
• In order to compile and run the above program, you need to open the command prompt by clicking
on start menu -> All Programs -> Accessories -> command prompt.

• To compile and run the above program, go to the directory where the file is saved; my current
directory is c:\new.

● Type the following commands here:

⮚ To compile: javac Simple.java

⮚ To execute: java Simple


Output:

Keywords used in Hello Java Program


• Let's try to understand the meaning of class, public, static, void, main, String[], System.out.println()
used in the program.
class
• It is a keyword.
• It is used to declare a class in Java.
public
• It is a keyword.
• It is an access modifier that represents visibility.
• It means it is visible to all.
static
• It is a keyword.
• If we declare any method as static, it is known as the static method.
• The core advantage of the static method is that there is no need to create an object to invoke the
static method.
• The main() method is executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.
void
• It is the return type of the method.
• It means it doesn't return any value.
main
• It represents the starting point of the program.
• It is a pre-defined name.
String[] args or String args[]
• It is used to work with command line argument
System.out.println()
• It is a print statement used to print an output on the console.
• Here, System is a class, out is an object of the PrintStream class, println() is a method of the
PrintStream class.
Internal Details of Program

4. Let's see what happens while we compile and run the Java program.

What happens at compile time?


• At compile time, the Java file is compiled by Java Compiler (It does not interact with OS) and is
converted into bytecode.

What happens at run time?


• At runtime, the following steps are performed:

Classloader:
• It is a subsystem of JVM that is used to load class files.

Bytecode Verifier:
• Checks the code fragments for illegal code that can violate access rights to objects.
Interpreter:
• Reads bytecode stream and then executes the instructions.
Access Specifier:

● Access specifier or modifier is the accessibility or visibility or scope of the method.

● It is optional to use an access specifier while defining a method.

● Java provides four types of access specifier:

1) Private:
• The access level of a private modifier is only within the class.
2) Default:
• The access level of a default modifier is only within the package.
• If you do not specify any access level, it will be the default.
3) Protected:
• The protected access modifier is accessible within package and outside the package but through
inheritance only.
4) Public:
• It can be accessed from within the class, outside the class, within the package and outside the
package.
STATIC MEMBERS

● The static keyword in Java is used for memory management mainly.

● The static keyword can be used with fields, methods, blocks.

Static Fields/variable:

● You can create a static field by using the keyword static.

● For instance variable memory will be allocated when an object is created.

● For static variable memory will be allocated whenever the class is loaded in the main memory during

execution. The JVM loads the .class file into the main memory during the time, memory will be
allocated for static variable.

● For static variables memory will be allocated only once. All the objects of the class will be use that

memory.

● For instance variable, every object will allocate one slot of memory to one instance variable in heap

memory.
● If the value of the variable is constant for all the objects then we will use static variable.

● If the value of the variable is varies for every object then will use instance variable.

● Default value for static variable is 0.

● You can access static variables in 2 two ways:

1. Directly
2. With the help of class name
When will use directly and with the class name?
Direct access: if program contains only one class, the class contains static variable and main method.
With the help of class name: if program contains multiple class, one class contains static variable and other
class contains main method.

JAVA FUNDAMENTALS
• Identifier
• Variables
• Data Types
• Operators
• Keywords
• Control Flow Statements
• Comments
• Arrays
• Naming standards
IDENTIFIER

● Used to identify any entity like variable, array, classs and method etc.

Rules for naming an Identifier:


• Must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ).
• Identifiers cannot start with a number.
• After the first character, identifiers can contain any combination of letters, currency characters,
connecting characters, or numbers.
• there is no limit to the number of characters an identifier can contain.
• You can't use a Java keyword as an identifier.
• Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
• Some legal identifiers:
• int _a;
• int $c;
• int ______2_w;
• int _$;
• int this_is_a_very_detailed_name_for_an_identifier;
• Some illegal (R ecognize why ?):
• int :b;
• int -d;
• int e#;
• int .f;
• int 7g;
VARIABLES

● Variables are used to store data in a Java program.

● The general rules for naming variables are:

⮚ Names can contain letters, digits, underscores, and dollar signs.

⮚ Names must begin with a letter.

⮚ Names should start with a lowercase letter and it cannot contain whitespace.

⮚ Names can also begin with $ and _ .

⮚ Names are case sensitive ("myVar" and "myvar" are different variables)

⮚ Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Syntax:
datatype variable_name=value;
Example
int data = 50; // here data is a variable

Local Variables: Local variables are declared within a method or block of code.
Instance Variables:
● Instance variables are declared within a class.

● When space is allocated for an object in the heap, a slot for each instance variable value is created.

● Instance variables are created when an object is created with the use of the keyword 'new'.

● Instance variables hold values that must be referenced by more than one method, constructor or

block.

● The instance variables are visible for all methods, constructors, and block in the class. Normally, it is

recommended to make these variables private (access level). However, visibility for subclasses can
be given for these variables with the use of access modifiers.

● Instance variables have default values. For numbers, the default value is 0, for Booleans it is false.

● Instance variables can be accessed directly by calling the variable name inside the class.

Class Variables: Class variables are declared with the static keyword and are shared among all instances of
a class.
Example to understand the three types of variables in java
public class A
{
static int variable1 = 100;//static variable
int variable2 = 200;//instance variable
void method()
{
int variable3 = 90;//local variable
}
public static void main(String args[])
{
int data = 50;//local variable
}
}//end of class

DATA TYPES

⮚ Data types are used to store values in the variable.

⮚ Data types in Java are categorized into two:

1. Primitive data types


2. Non-primitive data types
⮚ Each data types have different sizes

Primitive Data Types

● There are eight primitive data types in Java:

Non-Primitive Data Types

⮚ The non-primitive data types include classes, interfaces, and arrays.

OPERATORS

● Operators are used to perform operations on variables and values.

Types of Operators in Java

● Java divides the operators into the following groups:

i. Arithmetic operators
ii. Assignment operators
iii. Comparison operators/Relational Operators
iv. Logical operators
v. Bitwise operators
● Other categorization of operators

i. Unary Operator
ii. Binary operator
iii. Ternary operator(conditional operator)
(i) Arithmetic Operators

● Arithmetic operators are used to perform common mathematical operations.

(ii) Assignment Operators

● Assignment operators are used to assign values to variables.

Example
we use the assignment operator (=) to assign the value 10 to a variable called x:
int x = 10;
(iii) Comparison Operators/Relational Operators

● Comparison operators are used to compare two values (or variables).

● The return value of a comparison is either true or false.

● These values are known as Boolean values


(iv) Logical Operators

● You can also test for true or false values with logical operators.

● Logical operators are used to determine the logic between variables or values:

Bitwise Operator
• Bitwise operators are used on (binary) numbers
• There are five types of the bitwise operator in Java:
Operators Symbol Uses
Bitwise AND & op1 & op2
Bitwise exclusive OR ^ op1 ^ op2
Bitwise inclusive OR | op1 | op2
Bitwise Compliment ~ ~ op
Bitwise left shift << op1 << op2
Bitwise right shift >> op1 >> op2
Unsigned Right Shift >>> op number of places to
Operator >>> shift
Unary Operator
• The Java unary operators require only one operand.
• Unary operators are used to perform various operations i.e.
1. incrementing/decrementing a value by one
2. negating an expression
3. inverting the value of a Boolean
Operator Categor Precedence
Type y
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr
~!
Binary Operator
• It contains one operator and two operands
Example: 2 + 3
Ternary Operator (Conditional Operator)
• The ternary operator (? :) is the only conditional operator that accepts three operands.
• It is used to evaluate Boolean expressions.
• The ternary operator decides which value will be assigned to the variable.
• It can be used instead of the if-else statement. It makes the code much more easy, readable, and
shorter.
Note: Every code using an if-else statement cannot be replaced with a ternary operator.
Syntax:
variable = (condition)?: expression1 : expression2
• The above statement states that if the condition returns true, expression1 gets executed, else the
expression2 gets executed and the final result stored in a variable.

Example:
int n1 = 50;
int n2 = 70;
int bigger = n1>n2?n1:n2;
Output:
70
KEYWORDS

● Java keywords are also known as reserved words.


● These are predefined words by Java so it cannot be used as a variable or object name.

● All keywords must be in lowercase.

Keywords related with Data type (9)


boolean byte char short int
long float double enum void
Keywords related with Branching and Looping Statements (12)
if else switch case default break
goto for while do continue return
Keywords related with Access Specifier (3)
private protected public
Keywords related with Non Access Specifier (8)
Abstract static final native
synchronized transient volatile stictfp
Keywords related with Class and Object (5)
class interface new this instanceof
Keywords related with Inheritance (3)
extends implements super
Keywords related with Exception Handling (6)
try catch throw throws finally assert
Keywords related with Package (2)
package import
Miscellenous (1)
const
CONTROL FLOW:
Control flow in Java refers to the order in which individual statements, instructions, or function calls
are executed or evaluated. Java provides control flow statements to manage how the program executes under
different conditions.
Types of control flow:
Java provides control flow statements to manage the execution flow of a program. These are
categorized into three main types:
Decision-Making Statements
• As the name suggests, decision-making statements decide which statement to execute and when.
• There are two types of decision-making statements in Java
– if statement
– switch statement.
if Statement
• In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if Statement
• It is the most basic statement among all control flow statements in Java.
• It evaluates a condition and enables the program to enter a block of code if the expression evaluates
to true.
• The condition of the ‘if’ statement gives a boolean value, either true or false.
2) if-else Statement
• The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block.
• The else block is executed if the condition of the if-block is evaluated as false.

3) if-else-if ladder Statement


• The if-else-if statement contains the if-statement followed by multiple else-if statements.
• We can also define an else statement at the end of the chain.
4) Nested if-statement
• In nested if-statements, the if statement can contains an if or if-else statement inside another if or
else-if statement.
Example:
public class Test {
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output:
X = 30 and Y = 10
Switch Statement
• In Java, Switch statements are similar to if-else-if statements.
• The switch statement contains multiple blocks of code called cases and a single case is executed based
on the variable which is being switched.
• The switch statement is easier to use instead of if-else-if statements.
Important Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration.
• String type is also supported since version 7 of Java.
• Cases cannot be duplicate.
• Default statement is executed when any of the case doesn't match the value of expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied. It is optional, if not used,
next case is executed.
• While using switch statements, we must notice that the case expression will be of the same type as the
variable.
Loop Statements
• The process of repeatedly executing a collection of statement is called looping.
• But if the condition is given in such logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
• Java supports following types of loops:
Let's understand the loop statements one by one.
for Loop
• The Java for loop is used to iterate a part of the program several times.
• If the number of iteration is fixed, it is recommended to use for loop.
• There are four types of for loops in Java.
– Simple for Loop
– For-each or Enhanced for Loop
– Labelled for Loop
– Infinitive for Loop
1) Simple for Loop
• It consists of four parts:
1. Initialization: Which is executed once when the loop starts. Here, we can initialize the variable, or we
can use an already initialized variable.
2. Condition: Which is executed each time to test the condition of the loop. It continues execution until
the condition is false. It must return boolean value either true or false.
3. Increment/Decrement: It increments or decrements the variable value.
4. Statement: The statement of the loop is executed each time until the second condition is false.
2) for-each Loop
• It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
• It works on the basis of elements and not the index.
• It returns element one by one in the defined variable.
• In the for-each loop, we don't need to update the loop variable.
Syntax:
for(data_type var : array_name/collection_name){
//statements
}
Example:
public class Calculation {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
3) Labeled For Loop
• A label is a valid variable name that denotes the name of the loop to where the control of execution
should jump.
• To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the label
is called a labeled loop.
• We can use label before the for loop.
• It is useful while using the nested for loop as we can break/continue specific for loop.
Syntax:
labelname:
for(initialization; condition; incr/decr) {
//functionality of the loop
}
Example:
public class LabeledForLoop {
public static void main(String args[]) {
//outer loop
outer: //label
for(int i=1;i<=5;i++) {
System.out.println();
//inner loop
inner: //label
for(int j=1;j<=10;j++) {
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
Output:
123456789
123456789
123456789
123456789
123456789
4) Infinitive for Loop
• If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
• Now, you need to press ctrl+c to exit from the program.
while Loop
• The while loop is also used to iterate over the number of statements multiple times.
• However, if we don't know the number of iterations in advance, it is recommended to use a while loop.
• Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement
in while loop.
• It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
• If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.
do-while Loop
• The do-while loop checks the condition at the end of the loop after executing the loop statements.
• When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
• It is also known as the exit-controlled loop since the condition is not checked in advance.
Jump Statements
• Jump statements are used to transfer the control of the program to the specific statements.
• In other words, jump statements transfer the execution control to the other part of the program.
• There are two types of jump statements in Java.
1. break
2. continue
break Statement
• As the name suggests, the break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement.
• However, it breaks only the inner loop in the case of the nested loop.
• We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
• The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Example:
public class BreakExample {
public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
continue Statement
• Unlike break statement, 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 immediately.
• We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Example:
public class ContinueExample {
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);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
• As you can see in the above output, 4 is not printed on the console. It is because the loop is continued
when it reaches to 4.
ARRAYS

● Java provides a data structure, the array, which stores a fixed-size sequential collection of elements

of the same type.

● Arrays are used to store multiple values in a single variable, instead of declaring separate variables

for each value.

● The elements of an array are stored in a contiguous memory location.

Note:
• Array indices always start from 0. That is, the first element of an array is at index 0.
• If the size of an array is n, then the last element of the array will be at index n-1.
Types of Arrays in java

● There are two types of arrays.

1) Single Dimensional Array


2) Multidimensional Array
Single Dimensional Array in Java
• Single dimensional array of Java is a normal array where, the array contains sequential elements (of
same type).
• It is also known as a linear array or 1D or one Dimensional array, the elements are stored in a single
row.
• One dimensional array use single index to store elements.
Declaring 1D Array Variables in Java
• To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference.
Syntax:
dataType[] arr; (or) //Preferred
dataType []arr; (or)
dataType arr[];
• dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
• arrayName - it is an identifier
Example:
double[] data;
• Here, data is an array that can hold values of type double.
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Ex: int num = new int[5];
Array declaration and instantiation
– datatype[] arrayname = new datatype[size];
– Ex : Int[] a=new int[5];
Array Initialization
a[0]=10;
a[1]=20;
a[2]=70;
Declaration, Instantiation and Initialization
int a[]={33,3,4,5};//declaration, instantiation and initialization
Accessing 1D Array elements in Java
• We can access the element of an array using the index number.
Syntax:
// access array elements
array[index]
Multiple Dimensional Array in Java
• A multidimensional array is an array of arrays.
• It is also known as N-Dimensional array.
Declaring Multiple Dimensional Array Variables in Java
Syntax:
datatype[1st dimension][2nd dimension][]…[nth dimension] arrayname = new datatype[size1][size2][]….
[sizeN];
where:
• data_type: Type of data to be stored in the array.
• dimension: The dimension of the array created. For example: 1D, 2D, 3D etc.
• array_name: Name of the array
• size1, size2, …, sizeN: Sizes of the dimensions respectively.
Two Dimensional Array in Java
• In Java, the tabular representation of data is implemented using a two-dimensional array.
• The 2D array is organized as matrices which can be represented as the collection of rows and columns.

Declaring 2D Array Variables in Java


• A 2D array consists of rows and columns, we need two indices, one to refer rows and the other to a
particular column in that row.
• Hence, the syntax of declaring a 2D array is similar to that of a one-dimensional array with the
exception of having two square brackets instead of one:
Syntax
datatype[ ][ ] arrayName;
• The above-described syntax only declares the array i.e., the memory is allocated for the array
object but the values will be added later.
Initializing 2D Array in Java
• Once the array is declared and created, it is time to initialize it with values.
• There are two methods of initializing the 2D array with values.
Method1:
• The first method is the traditional method of assigning values to each element.
Syntax:
arrayName[rowIndex][columnIndex] = value;
Accessing 2D Array elements in Java
• We can directly access any element from an array using indexing.
• In the case of 2D arrays, we use row and column indices to access a particular element from the
matrix.
Syntax:
arrayName[i][j];
• Here, the ArrayName[i][j] statement is used to access the element present at the intersection of ith
row and jth column in the 2D array ArrayName.
UNIT III METHODS AND PACKAGES
Methods in Java - Predefined and User Defined Methods - Types of Defining Methods -- Constructors -
Types of Constructors - Constructors OverLoading - Introduction to Packages - Creating Packages _
Importing Packages.

METHOD IN JAVA
• A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation.
• The method is executed only when we call or invoke it.
Advantages of methods
• It is used to achieve the code reusability.
• It also provides the easy modification and readability of code, just by adding or removing a chunk of
code.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined and User Defined Method

Predefined Method:

● A predefined method is a method that comes built-in with Java, defined inside Java library classes.

You don’t need to write the logic — you just call the method.We can directly use these methods just
by calling them in the program at any point.

● Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.

Benefits of Predefined Methods:


● Saves time (no need to write common logic)
● Reduces code complexity
● Increases productivity
● Well-tested and reliable
User-defined Method:

● A user-defined method is a method created by the programmer to perform a specific task. These

methods improve code reusability, clarity, and organization.

● These methods are modified according to the requirement.


● Functions defined inside the class definitions are called as methods.

Syntax:
returnType methodName(parameter1, parameter2, ...) {
// Method body
// Statements
return value; // if returnType is not void
}

Types of User-Defined Methods in Java


User-defined methods in Java can be classified based on:
● Whether they take parameters
● Whether they return a value

tMethod Name:

● While defining a method, remember that the method name must be a verb and start with a lowercase

letter.

● If the method name has more than two words, the first name must be a verb followed by adjective or

noun.

● In the multi-word method name, the first letter of each word must be in uppercase except the first

word.
Example:

⮚ Single-word method name: sum(), area()

⮚ Multi-word method name: areaOfCircle(), stringComparision()

Parameter List:
• The list of parameters separated by a comma and enclosed in the pair of parentheses.
• It contains the data type and variable name.
• If the method has no parameter, left the parentheses blank.
Method Body:
• It is a part of the method declaration.
• It contains all the actions to be performed.
• It is enclosed within the pair of curly braces.
How to Call or Invoke a User-defined Method
• Once we have defined a method, it should be called.
• To call a method in Java, write the method's name followed by two parentheses () and a semicolon
(;).
• If the method has parameters in the declaration, those parameters are passed within the parentheses ()
but this time without their datatypes specified.
• However, it is important to keep the sequence of arguments the same as defined in the method
definition.
• When we call or invoke a user-defined method, the program control transfer to the called method.
Example:
public class Addition {
public static void main(String[] args) {
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) { //n1 and n2 are formal parameters
int s;
s=n1+n2;
return s; //returning the sum
}
}
Output:
The sum of a and b is= 24

CONSTRUCTORS

● Constructor is a special type of method that can be used to initialize an object.

● When an object is created, the constructor invoked automatically.

Characteristics/ Rules for creating Java constructor


1. Constructor name must be the same as its class name.
2. It has no return type.
3. A class can have more than one constructors
4. It can take zero or more parameters.
5. It always called with the new operator.
6. A Java constructor cannot be abstract, static, final, and synchronized.
Types of of Constructors
1. Default Constructor
2. No argument Constructors
3. Parameterized Constructor
4. Constructor overloading
1.Default constructor

● If class does not provide any constructor then the compiler provide a constructor Default constructor

● Default constructor does not have any arguments.

● The default constructor provides the default values to the object like 0, null, etc., depending on the type.

● You will not see the default constructor in your source code (the .java file) as it is inserted during

compilation and present in the bytecode (.class file).

Example:
class Demo
{
int a;
void display()
{
System.out.println(a);
}
}
public class Sample
{
public static void main(String args[])
{
Demo t = new Demo();
t.display();
}
}
Output:
0
2. Argument Constructors

● No argument constructors of Java does not accept any parameters.

● These constructors the instance variables of a method will be initialized with fixed values for all

objects.
Example:
class Demo
{
int a;
Demo()
{
a = 100;
}
void display()
{
System.out.println(a);
}
}
public class Sample
{
public static void main(String args[])
{
Demo t = new Demo();
t.display();
}
}
Output:
100
Are no-arg constructor and default constructor same?
• The default constructor is inserted by compiler and has no code in it.
• no-arg constructor will creates by user in our class which looks like default constructor but we can
provide any initialization code in it.
3. Parameterized Constructor
• A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
• The parameterized constructor is used to provide different values to distinct objects.
• However, you can provide the same values also.
Example:
class demo
{
int a;
demo(int n)
{
a = n;
}
void display()
{
System.out.println(“Number is”+a);
}
}
public class Sample
{
public static void main(String args[])
{
demo t = new demo(200);
t.display();
}
}
Output: 200
Constructor Overloading
● Like methods, a constructor can also be overloaded.

● Overloaded constructors are differentiated based on their type of parameters or number of

parameters.

● Constructor overloading is not much different than method overloading.

● In case of method overloading program have multiple methods with same name and different

signature. Whereas in Constructor overloading program have multiple constructor with same name
and different signature.Only difference is that constructor have No return type.
Example:
class demo
{
int a;
demo()
{
a = 10;
}
demo(int n)
{
a = n;
}
void display()
{
System.out.println(a);
}
}
public class Sample
{
public static void main(String args[])
{
demo t1 = new demo();
demo t2= new demo(200)
t1.display();
t1.display();
}
}
Output
Number is 10
Number is 200
Role of Private Constructor
• If you make any constructor as private, you cannot create the instance of that class from outside the
class.
Example
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Introduction to Packages
Package in Java is a group of related classes, interfaces, and sub-packages. It helps:

● Organize classes neatly.


● Avoid name conflicts.
● Control access using access modifiers.
● Make maintenance easier.
• Think of it as a folder in a directory.
• We use packages to avoid name conflicts, and to write a better maintainable code.
• Packages are divided into two categories:
1. Built-in Packages
2. User-defined Packages
Built-in Packages/Java API packages:
• The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
• The library contains components for managing input, database programming, and much much more.
• Some of the inbuilt classes are shown below in the figure.

• The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.


• You can either import a single class (along with its methods and attributes), or a whole package that
contains all the classes that belong to the specified package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• To use a class or a package from the java library, you need to use the import keyword:
Syntax
import package.subpackagename.Classname; // Import a single class
import package.subpackagename.*; // Import the whole package
Import a Class
• If you find a class you want to use, for example, the Scanner class, which is used to get user input,
write the following code:
Example-1
import java.util.Scanner;
• In the example above java.util is a package, while Scanner is a class of 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.
• In the below example, we used the nextLine() method, which is used to read a complete line:
Example-2
Using the Scanner class to get user input:
import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
Output:
Enter username
Creating Packages
Rules for Creating Packages
● Package name = folder name
● All classes inside the package go in that folder
● File system must reflect the package structure
● Accessed using import keyword

Import a Packages
• In the previous example, we used the Scanner class from the java.util package.
• This package also contains date and time facilities, random-number generator and other utility classes.
• To import a whole package, end the sentence with an asterisk sign (*).
• The following example will import ALL the classes in the java.util package:
Example:
import java.util.*; // import the java.util package
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
Output:
Enter username
NOTE: •
● The package creation statement must be the first line in a source file.

● There can be only one package creation statement in source file.

● The import statement come next to the package creation statement and before the class declaration.

● There can be any number of import statement in a source file.


User-defined Packages
• To create your own package, you need to understand that java uses a file system directory to store
them.
• Just like folders on your computer:
Example
└── root(my computer)
└── mypack(floder)
└── MyPackageClass.java(java file)
• To create a package, use the package keyword
Syntax
package pkg-name;
class classname
{
}
Example:MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Output:
This is my package!
• Save the file as MyPackageClass.java,
• Then compile the package:
C:\Users\Your Name>javac -d . MyPackageClass.java
• This forces the compiler to create the "mypack" package.
• The -d keyword specifies the destination for where to save the class file.
• You can use any directory name, like c:/user (windows), or, if you want to keep the package within the
same directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class names.
• When we compiled the package in the example above, a new folder was created, called "mypack".
• To run the MyPackageClass.java file, write the following:
C:\Users\Your Name>java mypack.MyPackageClass
• The output will be:
This is my package!
Example
Write a java program to demonstrate the working of a banking-system. where we create a new
account ,check balance, deposit , withdraw amount from our account. Create an Account class which has
create a Account() deposit(), withdraw() and balanceEnquiry() methods.

BankManagement.java
import java.util.Scanner;
import java.util.Random;
import java.io.*;
class BankManagement
{
String accName;
int accNumber;
int balance;
void createAccount(String accName,int accNumber)
{
this.accName=accName;
this.accNumber=accNumber;
balance=500;
}
void withdraw( int amount)
{
if(balance>=amount)
{
balance=balance-amount;
}
else
{
System.out.println("Insufficient balance");
}
}
void deposit(int amount)
{
balance=balance+amount;
}
void display()
{
System.out.println("Account Name = "+accName);
System.out.println("Account Number = " +accNumber);
System.out.println("Available Balance = "+balance);
}
public static void main(String args[])
{
int choice,ch,number;
String name;
Scanner s=new Scanner(System.in);
Scanner input=new Scanner(System.in);
Random random=new Random();
BankManagement obj=new BankManagement();
do
{
System.out.println("-------------------------------");
System.out.println(" INDIAN BANK ");
System.out.println("-------------------------------");
System.out.println("1. Create Account");
System.out.println("2. WithDraw Amount");
System.out.println("3. Deposit Amount");
System.out.println("4. Balance Enquiry");
System.out.println("-------------------------------");
System.out.println("Enter your Choice : ");
choice=s.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter account name : ");
name=input.nextLine();
number=random.nextInt(1000000);
obj.createAccount(name,number);
obj.display();
System.out.println("your account is created successfully");
break;
case 2:
System.out.println("Enter account name : ");
name=input.nextLine();
System.out.println("Enter Amount");
number=s.nextInt();
obj.withdraw(number);
obj.display();
break;
case 3:
System.out.println("Enter account name : ");
name=input.nextLine();
System.out.println("Enter Amount");
number=s.nextInt();
obj.deposit(number);
obj.display();
break;
case 4:
System.out.println("Enter account name : ");
name=input.nextLine();
obj.display();
break;
default:
System.out.println("Invalid choice");
break;
}
System.out.println("Enter 0 to quit and 1 to continue ");
ch=s.nextInt();
}while(ch==1);
}
}

You might also like