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

24cs202 Java Progg Uniti Java Fundamentals to Stud

This document provides an overview of Java fundamentals, including its definition, types of applications, and object-oriented programming principles. It covers Java's features, history, version history, and the Java environment, detailing the stages of Java program development and execution. Additionally, it explains the structure of a Java program, the main method, and the syntax rules for writing Java code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

24cs202 Java Progg Uniti Java Fundamentals to Stud

This document provides an overview of Java fundamentals, including its definition, types of applications, and object-oriented programming principles. It covers Java's features, history, version history, and the Java environment, detailing the stages of Java program development and execution. Additionally, it explains the structure of a Java program, the main method, and the syntax rules for writing Java code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT 1 JAVA FUNDAMENTALS

An Overview of Java - Data Types, Variables, and Arrays –


Operators - Control Statements – Class Fundamentals –
Declaring objects – Methods – Constructors – this
keyword - Overloading methods - Overloading
constructors - Access Control – Static – Final

1
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Overview of JAVA
Introduction to Java and What is Java?
Java is a programming language and a platform.Java is a high level, robust, secured and object-oriented programming
language.
Platform: Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.

Types of Applications where in java is used?


There are mainly 4 type of applications that can be created using JAVA
1 Stand alone Applications : Desktop/window-based application. An application that we need to install on every
machine such as media player, acrobat reader, antivirus etc. AWT and Swing are used in java for creating standalone
applications
2. Web Applications : runs on the server side and creates dynamic page such as irct.co.in, javatpoint.com Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java
3. Enterprise Applications It is distributed in nature, such as banking applications etc. It has the advantage of high level
security, load balancing and clustering. EJB is used in java for creating enterprise applications
4. Mobile Applications : An application that is created for mobile devices such as Opera Mini, Signal, Spotify where java
is used..

2
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Object Oriented Programming Principles/concepts/features (Important)

A class represents the set of fields or methods that are common to all objects under a single name. A class is a blueprint or
Class prototype for objects. It is used to create user-defined data types.

An object is an instance (single occurrence) of a class. An entity that a has state and behaviour is known as an object. An object
Object is a real- world entity. An object is a run-time entity.

Abstraction is the process of hiding certain details and only showing the essential features of the object. In other words, it deals
Abstraction with the outside view of an object (interface).

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the
data it manipulates. Encapsulation is a protective shield that prevents the data from being accessed by the code outside this
Encapsulation shield.

Inheritance is the mechanism in java by which one class is allowed to inherit the features (fields and methods) of another class.
Super Class: The class whose features are inherited is known as a subclass (or a derived class, extended class, or child
class). The
subclass can add its own fields and methods in addition to the superclass fields and methods.
Inheritance
Polymorphism is the ability of an object to take on many forms. Polymorphism in java is a concept by which a single action can
be performed in different ways. The most common use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object.
There are two types of polymorphism in java:
1. Compile time polymorphism
Polymorphism 1. Runtime polymorphism or Dynamic Method Despatch. Polymorphism in java can be performed by method overloading
and
method overriding.

3
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Javascript and Java

JavaScript Java

Object – oriented. No Distinction between types of Class-based.


objects.
Objects are divided into classes and instances with all
Inheritance is through the prototype mechanism, inheritance through the class hierarchy.

properties and methods can be added to any object Classes and instances cannot have properties or methods
dynamically added dynamically
Variable data types are not declared Variable data types must be declared

Cannot automatically write to hard disk Can automatically write to hard disk

Tryit:
https://www.w3schools.com/js/default.asp
4
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, https://www.w3schools.com/js/js_intro.asp
Dept.of S&H (GE)
Features of JAVA – 8M
Features of JAVA includes:
1. Compiled and interpreted - java is both compiled and interpreted, but
Most of lang are either complied or interpreted
Firstly, java compiler translates source code to byte code
Secondly, java interpreter translates bytecode to machine lang
2. Platform-independent and portable -program can be easily moved from one system to another
changes and upgrades in OS, processes and system resources
3. Object-oriented - it supports object oriented
4. Robust and secure - java uses techniques such as garbage collection for memory management and
exception handling that deals with exceptional behaviour of a prog
5. Distributed - has string networking facilities
using java opening and using applications on internet is possible
6. Simple, small and familiar - simplified version of c++
features of c and c++
eg. java does not use pointer, pre-process header files, operator overloading concepts
7. Multithreaded and interactive – handling multiple task simultaniously
Eg. can listen to an audio cli while scrolling a page
8. High performance - the incorporation of multithreading enhances the overall execution speed of java prog.
Java architecture is designed to reduce overheads during runtime.
9. Dynamic and extensible - dynamic linking to new class lib,methods and object, supports methods writtern
in other language
C, c++ they are native methods, native methods are dynamically at runtime.
5
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
History of Java - James Gosling
The history of java starts from Green Team.
Green team members (James Gosling, Mike Sheridan,and Patrick Naughton) initiated a task to develop a language for
digital devices like Set-top boxes, Tv's etc.

Initially, it was called "Greentalk" by James Gosling and file ext .gt.
After that, it was called “Oak” and was developed as a part of the Green project.

Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany,
Romania etc. Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?


The team gathered to choose a new name for the language, wanted something that reflected the essence of the
technology, unique, and easy to spell, and fun to say. According to James Gosling, "Java was one of the top choices along with
Silk". Since most of the team members preferred Java. Java is an island in Indonesia where the first coffee was produced
(called Java coffee). It is a kind of espresso bean.
Java name was chosen by James Gosling while having a cup of coffee nearby his office. Notice that Java is just a name,
not an acronym.
Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released
in 1995. In 1995, Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features
added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications,
mobile applications, cards, etc. Each new version adds new features in Java.
6
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Version History

Version Release date End of Public Updates (Free) End of Extended Support (Paid)

JDK 1.0 23rd January 1996 May 1996 —


JDK 1.1 18th February 1997 October 2002 —
J2SE 1.2 4th December 1998 November 2003 —
J2SE 1.3 8th May 2000 March 2006 —
J2SE 1.4 13th February 2002 October 2008 —
J2SE 5.0 30th September 2004 October 2009 —

… … … …
Java SE 20 21st March 2023 September 2023 —
September 2026 for Oracle[15]
September 2029 for Eclipse Temurin[13]
September 2029 for Red Hat[7]
Java SE 21 (LTS) 19th September 2023 September 2031 for Oracle[14]
October 2030 for Amazon Corretto[12]
September 2031 for Azul[10]
March 2032 for BellSoft’s Liberica JDK[9]
Java SE 22 19th March 2024 September 2024 —

7
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Environment/Java Architecture - 8M

Java programs can typically be developed in five stages:


1. Edit: Use an editor to type the source code
(Simple.java)
2. Compile: javac, the Java compiler is used to translate
the source code to machine independent, bytecode
Bytecodes are called class file(an intermediate code)
3. Loading: Class loader loads the bytecodes from class
and other libraries file into main memory
4. Verify: Verifier make sure, whether the bytecodes
are valid and do not violate security restrictions
5. Execute: Java Virtual Machine (uses a combination
of interpretation and just in time compilation to
translate bytecodes into machine language
Applications are run on user's machine, i.e.,
executed by interpreter with java command (java
Simple)

8
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Virtual Machine (JVM) - 2M

JVM interprets the bytecode into machine language format on which it is running
JVM is not a real machine, its just a vitual machine
JVM contains class loader and execution engine
loads bytecode interprets bytecode

Note: JVM is machine specific, java progg. can be executed in any platform provided the corresponding
JVM and OS is available
Garbage collection in Java is an automatic memory management process performed by the Java Virtual Machine (JVM). It
identifies and removes objects that are no longer reachable or in use by the program. The process involves three main steps:
marking, sweeping, and optionally, compacting. Java's garbage collection feature eliminates the need for manual memory
deallocation, making memory management easier and less error-prone for developers.
9
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Structure of Java Program – 8M
1.Documentation Section
- It comprises a set of comment lines giving the name of the prog, author and other
details //single line comment
/* ……*/ multi line comment
Documentaiton comment
/* *
* documentaiton comments
* For generating documentaoitn
*/
2. Pacakage statement
-it declares a package name and informs a compiler that the classes defined in the
prog belongs to this package Eg. package student;
3. Import statement
Can have access to classes that are part of packages
Eg. import java.io.*;
import java.util.date;
import student.test;
4. Class definition – contains multiple class definitons
5. Interface statement – it is optional, and used only when we need to implement
multiple inheritance.
6. Main method class – is the starting point for any java program
It creates object of various classes and establishes communications between them.

10
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Main Method Class
The main method is from where the execution starts and follows the order specified for the following statements
Structure of main method class
//class declaration
public class Classname{
//main method declaration
public static void main(String args []) {
System.out.println("”);}
}

Example Structure of Java Source File class keyword is used to declare a class in java, by default
public class Simple public class
{ public keyword is an access modifier which represents
public static void main(String args[]) visibility. (private/protected)
{ static is a keyword, will not create any object, so it saves
memory.
System.out.println(“Hellow Java!”); // Prints Hellow Java!
void is the return type of the method, it means it doesn't
} return any value.
} main represents startup of the program.
$ javac Simple.java -Complile command String[] args is used for command line argument.
$ java Simple -Run command System.out.println() is used print statement.
11
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Program… Basic Syntax
It is very important to keep in mind the following points.
1) Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
2) Class Names - For all class names the first letter should be in Upper Case.If several words are used to form a name of the
class, each inner word's first letter should be in Upper Case Example class MyFirstJavaClass
3) Method Names - All method names should start with a Lower Case letter.If several words are used to form the name of the
method, then each inner word's first letter should be in Upper Case Example public void myMethodName()
4) Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it
using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match your program will not compile).
Example : Assume ‘Simple’ is the class name. Then the file should be saved as ‘Simple.java'.
5. public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of
every Java program..

12
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Program Execution

Java Program Can be executed using the following means


1. command prompt (tobe downloaded)
2. IDE (tobe downloaded)
3. Online compilers

1. Command Prompt Execution


(Refer:https://www.youtube.com/watch?v=zBF1M8dTftk)

1. Download and Install JDK


(Refer: https://www.oracle.com/java/technologies/javase-downloads.html )
Installed C:\Program Files\Java\JDK\Bin
Save the Source Code in any working space
Let Working Space be D:\MyJavaPrograms\Week1
3. Set the Path in Command Prompt
D:\MyJavaPrograms\Week1> set path = “C:\Program Files\Java\JDK\Bin”
4. Compile the Source Code
D:\MyJavaPrograms\Week1> javac Simple.java
On successful Compilation
Simple.class (Byte Code) is created
5. Interpret / Execute the Class File (Byte Code)
D:\MyJavaPrograms\Week1> java Simple
13
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
2. IDE Execution
Many Integrated Development Environment (IDE) are available, that helps in development
and execution of Java applications For E.g., Lunar Eclipse, JCreator, CodeBlocks, etc
Refer: https://www.youtube.com/watch?v=4WwBvnH9KCA
1. Download and Install IDE(Eclipse) https://www.eclipse.org/downloads/)
2. Open a new Java Project using the IDE.
3. Open a new class.
4. Add main method.
5. Compile and run using menus.

3. Online Compilers
Many online compilers are available for practicing Java program, which are simple to use.
1. https://www.onlinegdb.com/online_java_compiler
2. https://www.tutorialspoint.com/compile_java_online.php
3. https://compiler.javatpoint.com/opr/online java_compiler.jsp
4. https://www.jdoodle.com/online java compiler/
5. https://www.codechef.com/ide

14
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Relationship between JDK, JRE, JVM

Java Virtual Machine (JVM)


Java Development Kit (JDK)
JVM (Java Virtual Machine) is an abstract machine.
JDK is an acronym for Java Development Kit.It physically
It is a specification that provides runtime environment in which
exists.It contains JRE + development tools.
java bytecode can be executed.JVMs are available for many
hardware and software platforms.
JVM, JRE and JDK are platform dependent because
configuration of each OS differs.Java is platform
independent.The JVM performs following main tasks:Loads
codeVerifies codeExecutes codeProvides runtime environment

Java Runtime Environment(JRE)


JRE is an acronym for Java Runtime Environment.It is used to
provide runtime environment.It is the implementation of
JVM.It physically exists.It contains set of libraries + other files
that JVM uses at runtime.Implementation of JVMs are also
actively released by other companies besides Sun Micro
Systems.

15
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Tokens
The Smallest individual units in a program are called tokens.
Java language includes 5 types of tokens
Reserved words/Keywords
Identifiers
Literals
Operators
Separators
Java Keywords
A Java keyword is one of 50 reserved terms that have a special function and a set definition in the Java
programming language. The fact that the terms are reserved means that they cannot be used as identifiers for any
other program elements, including classes, subclasses, variables, methods, and objects.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** Instance return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

16
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java Identifiers & Literals
Java Identifiers
Names given to variables, objects, methods
Must not be a Java keyword, Must begin with a letter.
Followed by any number of characters, digits, or _ (Underscore)
Identifiers should be well chosen, use complete words (even phrases) this helps program documentation
Iiterals
Integers 4, 19, -5, 0, 1000
Doubles 0.0,
Strings “Hi Mom” “Enter the number : “
Character 'A' 'X' '9' '$' '\n‘
Boolean true, false
null absence to an object
In Java, null is a special literal that represents the absence of a value or a reference to an object. It is used to indicate that a reference variable
does not currently point to any object in memory.
i) Default Value for Object References
If an instance variable (class-level variable) of a reference type is not initialized, it defaults to null.
Example: class Example {
static String str; // Defaults to null
public static void main(String[] args) {
System.out.println(str); // Prints: null
}}
ii) Cannot Be Assigned to Primitive Types
null can only be assigned to reference types, not primitive types like int, double, or boolean.
Example (Invalid Code):
int x = null; // Compilation error
17
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Variable and Data Types
Variable : It is name of reserved area allocated in memory.
 Java is a statically typed programming language. It means, all variables must be declared before its use. Java is also a strictly
typed language.
 A variable is a container that holds the value while the Java program is executed.
 A variable is assigned with a data type.
Variable declaration
<datatype> <variablename> or
<datatype> <variablename> = <value>
Rules for Variable Names
• Variable names are case sensitive
• A variable's name can be any legal identifier an unlimited length sequence of Unicode letters and digits, beginning with a letter,
the dollar sign or the underscore character
• Subsequent characters may be letters, digits, dollar signs, or underscore characters
• White space is not permitted, keyword or reserved word should not be used as variable names
There are three types of variables in java
1. local variable : Variable that is declared inside the method is called local variable
2. instance variable : Variable that is declared inside the class but outside the method is called instance variable . It is not declared
as static.
3. static variable : A variable that is declared as static is called static variable. It cannot be local.

class A{
int data=50; //instance variable
static int m=100; //static variable
void method() {
int n=90; //local variable
} //end of method
22CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 18
}//end of class
The Scope and Lifetime of Variables
Java allows variables to be declared within any block a block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope. A scope determines what objects are visible to other parts of your
program. It also determines the lifetime of those objects. In Java, the two major scopes are those defined by a
class and those defined by a method.
Variables declared inside a scope are not visible to code that is defined outside that scope. Thus, when you
declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
//Demonstrate block scope
class Scope{ A variable will not hold its value
public static void main(String[] args){ once it has gone out of scope.
int x =10; //known to all code witin main A variable declared within a block
x=10; will lose its value when the block
if(x==10){ //start new scope is left. The lifetime of a variable is
int y=20; //known only to this block confined to its scope.
//x and y both known here If a variable declaration includes an
System.out.println("x and y:" +x+" " +y); x=y*2; initializer, then that variable will be
} reinitialized each time the block in
y=100; //Error y not known here which it is declared is entered.
System.out.println("x is"+x); //x is still known here
}
}
22CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 19
Data Types
Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: It holds the value of the data item. The primitive data
types include Boolean, char, byte, short, int, long, float, and double.
2. Non-primitive data types: It holds the memory address where the data item (object) is stored. It is also
known as Reference datatypes. The non-primitive data types include Classes, Interfaces, and Arrays.

22CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 20


Java Primitive Data Types – 8/13 M
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. There are 8 types of primitive data types:

22CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 21


Boolean Data Type
boolean is a special datatype which can have only two values ‘true’ and ‘false’. It has a default value of ‘false’ and a size of 1 byte.
It comes in use for storing flag values.
Example- boolean flag=true;

Byte Data Type


The byte data type is an example of a primitive data type. It is an 8-bit signed integer. Its value range lies between -128 to
127 (inclusive). Its default value is 0. The byte data type is used to save memory in large arrays where memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of the "int" data type.
Example:
byte a = 10, byte b = -20;

Short Data Type


The short data type is a 16-bit signed integer. Its value range lies between -32,768 to 32,767 (inclusive) Its default value is 0.
The short data type can also be used to save memory just like the byte data type. A short data type is 2 times smaller than
an integer.
Example:
short s = 10000, short r = -5000;

Int Data Type


int is used for storing integer values. Its size is 4 bytes and has a default value of 0. The maximum values of integer is 2^31 and
the minimum value is -2^31. It can be used to store integer values unless there is a need for storing numbers larger or smaller
than the limits
Example- int a=56; 22CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 22
Long Data Type
The long data type is a 64-bit integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1) (inclusive). Its default value is 0. The long data type is used when you need a range
of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L;
Float Data Type
float is used for storing decimal values. Its default value is 0.0f and has a size of 4 bytes. It has an infinite value range. However
its always advised to use float in place of double if there is a memory constraint. Currency should also never be stored in float
datatype. However it has a single precision bit.
Example- float a=98.7f;

Double Data Type


The double data type is a double-precision 64-bit floating point. Its value range is unlimited. The double data type is
generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
double d1 = 12.3d;

Char Data Type


char as the name suggests is useful for storing single value characters. Its default value is ‘\u0000’ with the max value being
‘\uffff’ and has a size of 2 bytes.
Example- char a=’D’;
It must be confusing for you to see this new22CS202
kind of data
JAVA ‘/u000’.
PROGG This is the
UNIT I - Meenakshi, unicode
Dept.of S&H (GE) format which java uses inplace of 23
ASCII.
Java program to illustrate the different types of datatypes:

import java.io.*;
class Main
{
public static void main(String[] args) throws IOException
{
int a = 10;
short s = 2; javac Main.java - compile
byte b = 6; java Main - run
long l = 125362133223l;
float f = 65.20298f;
double d = 876.765d;
System.out.println("The integer variable is " + a);
System.out.println("The short variable is " + s);
System.out.println("The byte variable is " + b); Output
System.out.println("The long variable is " + l); The integer variable is 10
System.out.println("The float variable is " + f); The short variable is 2
System.out.println("The double variable is " + d); The byte variable is 6
} The long variable is 125362133223
} The float variable is 65.20298
The double variable is 876.765
24
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
25
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Data Type Conversion, Type Casting - 2M

The process of changing a value from one data type to another type is known as data type conversion. Data Type
conversion is of two types:

Widening: The lower size datatype is converted into a higher size data type without loss of information.
Narrowing: The higher size datatype is converted into a lower size data type with a loss of information.

// Widening (byte<short<int<long<float<double)
int i = 10; //int--> long
long l = i; //automatic type conversion or widening

// Narrowing (byte>short>int>long>float>double)
double d = 10.02;
long l = (long)d; //explicit type casting or narrowing

26
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Operators and Types of Operators – 8/13M
precedenceof Operators and associativity
Operators
Operators are used to performing specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands. In Java, operators are used to compare values, perform operations, etc

Types of Operators
1. Arithmetic Operators
2. Relational / Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Conditional/Ternary Operators
6. instanceOf Operator
7. Bitwise Operator
Arithmetic Operators
The basic arithmetic operators (+, -, *, /, and %) are binary operators,
because they each operate on two operands
JavaScript provides the remainder operator, %, which yields the
remainder after division
Arithmetic expressions in JavaScript must be written in straight-line form
to facilitate entering programs into the computer

27
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Comparison Operators /Relational Operators
 if statement allows a script to make a decision based on the truth
or falsity of a condition
If the condition is met (i.e., the condition is true), the statement
in the body of the if statement is executed
If the condition is not met (i.e., the condition is false), the
statement in the body of the if statement is not executed
 Conditions in if statements can be formed by using the equality
operators and relational operators
 Equality operators both (==, !==) have the same level of precedence,
which is lower than the precedence of the relational operators.
The equality operators associate from left to right.

Assignment Operators Logical Operators


The assignment operators are used to assign values to the The Logical operator return either True or False
variable. deponding upon the expression,its commonly used
in decision making

28
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Conditional (Ternary) Operator instanceOf Operators
This operator is used only for object reference variable. The operator
The conditional operator assigns a value check whether the object is of a particular type (class/interface type).
to a variable based on a condition.
(object reference variable) instanceOf (Class/interface type)
Eg.
Syntax Example
String name == ‘James’;
(condition) ? x : y (z < 18) ? x : y Boolean result = name instanceOf String;
Output
true
This will return true since name is type of string
Bitwise Operator
bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into
binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise
operators. The result is then returned in decimal format

29
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Precedence of Operators
Operator precedence defines the order in which statements or operations are evaluated. The operator with higher
precedence is evaluated first than the operator with the lower precedence like in mathematics we will do multiplication prior
to addition or subtraction. In other words we can also state that operator precedence works as the same way
of PEMDAS where 1parenthesis is evaluated first then 2exponents or power then 3multiplication and thereafter division,
4addition, and subtraction. It is to ensure that when your code is compiled, JavaScript returns correct output like standard
mathematical calculation.
Order of Operations PEMDAS
public class preced {
Order of operation in PEDMAS are,
public static void main(String[] args)
P stands for Parentheses ( ), { }, [ ]
{
E stands for Exponents (ab)
int x = 5 + (3*3);
M stands for Multiplication (×)
System.out.println(x);
D stands for Division (÷)
var y = 4*5+10-24/4;
A stands for Addition (+)
System.out.println(y);
S stands for Subtraction (-)
}
What if you encounter an expression where there are operators with
}
same level of precedence. You will be confused on which operation to
perform first in such scenarios. In order to solve this issue, there is
another concept called Associativity, that determines the direction in
which the operation is to be performed. There is two types of Output:
associativity: Left-to-right and Right-to-left associativity. Above is 14
operator precedence table in JavaScript that you can use to 24
understand and evaluate the expression. 30
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Java program that demonstrates the use of 8 different OUTPUT :
operators: arithmetic, relational, logical, assignment, // Conditional (Ternary) operator
conditional (ternary), bitwise, unary, and instanceof operators int max = (a > b) ? a : b;
System.out.println("\nTernary Operator:");
Operators.java System.out.println("Max between a and b: " + max);
public class Operators {
public static void main(String[] args) { // Bitwise operators
int a = 10, b = 4; int bitwiseAND = a & b;
// Arithmetic operators int bitwiseXOR = a ^ b;
System.out.println("Arithmetic Operators:"); int bitwiseComplementA = ~a;
System.out.println("a + b = " + (a + b)); System.out.println("\nBitwise Operators:");
System.out.println("a * b = " + (a * b)); System.out.println("a & b = " + bitwiseAND);
System.out.println("a % b = " + (a % b)); System.out.println("a ^ b = " + bitwiseXOR);
System.out.println("~a = " + bitwiseComplementA);
// Relational operators
System.out.println("\nRelational Operators:"); // Unary operators
System.out.println("a > b: " + (a > b)); int unaryMinusA = -a;
System.out.println("a <= b: " + (a <= b)); boolean logicalNotX = !x;
System.out.println("a == b: " + (a == b)); System.out.println("\nUnary Operators:");
System.out.println("-a = " + unaryMinusA);
// Logical operators System.out.println("!x = " + logicalNotX);
boolean x = true, y = false;
System.out.println("\nLogical Operators:"); // instanceof operator
System.out.println("x && y: " + (x && y)); String str = "Hello";
System.out.println("x || y: " + (x || y)); System.out.println("\ninstanceof Operator:");
System.out.println("Is str an instance of String? " + (str instanceof String));
// Assignment operators }
int result = 0; }
result += 5;
System.out.println("\nAssignment Operator:");
System.out.println("result = " + result); 31
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
CONTROL STATEMENTS -8/13M
JavaScript Control Statements also known as Control Structures or Flow Control statements are statements which decide
the execution flow of the program. Typically the program execution begins from the first line in the to the last line of that JS
code. However, in between this the flow of the execution can be branched(based on some condtion) or re-iterated(loops) based
on some criterias. This the functionality that is provided by Control Statements in JavaScript.
They are mainly categorized in 2 types –
Conditional Control Statements
Whenever a condition is to be tested depending on which particular tasks are to be performed, Conditional control
statements are used.
Looping / Iterative Control Statements
Whenever a particular task has to be iterated for a particular number of times or depending on some condition, Looping
control statements are used.
Apart from these we have 3 jump statements as – break, continue and return which assist in the flow controlling mechanism.

32
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Conditional Control Statements
Conditional statements are used to perform different actions based on various conditions
The conditional statement evaluates a condition before the execution of instructions

If Statement If – Else Statement


IF statement is a conditional branching statement. If – Else is a two-way decision statement.
In 'IF' statement, if the condition is true a group of It is used to make decisions and execute statements
statement is executed. And if the condition is false, the conditionally.
following statement is skipped. Syntax : If-Else statement
if (condition)
Syntax : If statement {
if(condition) //Statement 1;
{ }
//Statement 1; else if(condition)
//Statement 2; {
} //Statement 2;
}
else
{
//Statement 3;
}

24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE) 33
Switch Statement
Switch is used to perform different actions on different conditions. It is For-Each Loop
used to compare the same expression to several different values. The For-each style is also referred to as enhanced for loop.
Syntax For-in loop is used to traverse all the properties of an object.
switch(expression) It is designed for looping through arrays, collections. The
{ code block inside the loop is executed once for each
case condition 1: property.
//Statements;
break;

Syntax
case condition n: for (type itr-val:collection) statement-block;
//Statements; {
break; //Statements;
default: }
//Statement; With each iteration of the loop, the next element in the
} collection is retrieved and stored in itr-var.
For Loop
For loop is a compact form of looping.
Loop repeats until all elements in the collection have been
It includes three important parts: obtained.
1. Loop Initialization, 2. Test Condition, 3. Iteration
All these three parts come in a single line separated by semicolons(;). Note:
Syntax Unlike the traditional for loop that relies on a counter to
for(initialization; test-condition; increment/decrement) navigate through elements, the enhanced for loop
{ abstracts the counter, providing direct access to each
//Statements;
element.
} 34
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
While Loop Do-While Loop
While loop is an entry/counter-controlled loop statement. Do-While loop is an exit-controlled loop statement.
It is the most basic loop in JavaScript. Similar to the While loop, the only difference is condition will
It executes a statement repeatedly as long as expression is be checked at the end of the loop.
true. Once the expression becomes false, the loop The loop is executed at least once, even if the condition is false.
terminates.
Syntax Syntax
while (condition) do
{ {
//Statements; //Statements;
} }
while(condition);
Break Statement
Break statement is used to jump out of a loop.
It is used to exit a loop early, breaking out of the Return
enclosing curly braces. The Return statement is to explicitly return from a method
Syntax: Program control transfer back to the caller of the method.,
break; Immediately terminates the method in which it is executed.

Continue Statement Syntax


Continue statement causes the loop to continue with the next return ; //optional, with void method, exit from method
iteration. return value;
It skips the remaining code block. return variable/expression;
Syntax:
continue; 35
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Example Using return; for early exit, If num is negative, the method terminates early, skipping the last println.
public void checkNumber(int num) {
if (num < 0) {
System.out.println("Negative number detected!");
return; // Exits the method early
}
System.out.println("Number is positive: " + num);
}

Difference between While Loop and Do – While Loop

While Loop Do – While Loop


In while loop, first it checks the condition and then In Do – While loop, first it executes the program and
executes the program. then checks the condition.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the body. The condition will come after the body.
It runs at least once, even though the conditional is
If the condition is false, then it terminates the loop.
false.
It is a counter-controlled loop. It is a iterative control loop

36
24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Single program for statements in java // While loop
System.out.println("\nWhile Loop:");
public class Statements{ int j = 1;
public static void main(String[] args) { while (j <= 5) {
int a = 5; int b = 10; System.out.println(j);
// If-else statement j++;
System.out.println("\nIf-Else Statement:"); }
if (a > b) { OUTPUT :
System.out.println("a is greater than b"); // For loop
} else { System.out.println("\nFor Loop:");
System.out.println("a is not greater than b"); for (int k = 1; k <= 5; k++) {
} System.out.println(k);
// If-else if-else statement }
System.out.println("\nIf-Else If-Else Statement:");
if (a > b) { // For-each loop
System.out.println("a is greater than b"); System.out.println("\nFor-Each Loop:");
} else if (a < b) { int[] numbers = {1, 2, 3, 4, 5};
System.out.println("a is less than b"); for (int num : numbers) {
} else { System.out.println(num);
System.out.println("a is equal to b"); }
} // Return statement
// Switch statement System.out.println("\nReturn Statement:");
System.out.println("\nSwitch Statement:"); int sum = addNumbers(3, 7);
int dayOfWeek = 3; System.out.println("Sum: " + sum);
switch (dayOfWeek) { }
case 1:
System.out.println("Monday"); // Method with a return statement
break; private static int addNumbers(int x, int y) {
case 2: return x + y;
System.out.println("Tuesday"); }
break; }
default:
System.out.println("Other day"); 37
} 24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
Calculator program in java
import java.util.Scanner; default:
public class SimpleCalculator { System.out.println("Invalid choice");
public static void main(String[] args) { System.exit(0);
Scanner scanner = new Scanner(System.in); }
System.out.print("Enter the first number: "); System.out.println("Result using switch: " + result);
double num1 = scanner.nextDouble(); scanner.close();
System.out.print("Enter the second number: "); }
double num2 = scanner.nextDouble(); }
System.out.println("Select operation:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter choice (1, 2, 3, or 4): ");
int choice = scanner.nextInt();
double result = 0.0;
// Using switch statement
switch (choice) { Output:
case 1:
result = num1 + num2; Enter the first number: 1
break; Enter the second number: 3
case 2:
result = num1 - num2; Select operation:
break; 1. Addition
case 3:
result = num1 * num2; 2. Subtraction
break; 3. Multiplication
case 4:
if (num2 != 0) { 4. Division
result = num1 / num2; Enter choice (1, 2, 3, or 4): 1
} else {
System.out.println("Error: Division by zero"); Result using switch: 4.0
System.exit(0);
} 38
break; 24CS202 JAVA PROGG UNIT I – Java Fundamentls - Meenakshi, Dept.of S&H (GE)
I/O statements in Java
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast.

Java Scanner Class


Java Scanner class allows the user to take input from the console. It belongs to java.util
package. It is used to read the input of primitive types like int, double, long, short, float, and byte. It is
the easiest way to read input in a Java program.
Syntax
Scanner object_name=new Scanner(System.in);
Example
Scanner s=new Scanner(System.in);

Methods of Java Scanner Class


Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double It is used to scan the next token of the input as a double.
nextDouble()
byte nextByte() It is used to scan the next token of the input as a byte.
String next() Reads the individual string
String nextLine() Reads the string until enter

Example The difference between the Java Scanner's next() and


import java.util.*; nextLine() methods is that nextLine() returns every
public class Main character in a line of text right up until the carriage
{ return, while next() splits the line up into individual
public static void main(String args[]) words, returning individual text Strings one at a time.
{
String s = "Hello, This is Java.";
Scanner sc = new Scanner(s);
System.out.println("--------Static Details-------- ");
//System.out.print("Name: " + sc.next());
System.out.println("Name: " + sc.nextLine());

System.out.println("--------Enter Your Details-------- ");


Scanner in = new Scanner(System.in);

System.out.print("Enter your name: ");


String name2 = in.next(); Output
System.out.println("Name: " + name2);
--------Static Details--------
Name: Hello, This is Java.
System.out.print("Enter your age: ");
--------Enter Your Details--------
int age = in.nextInt();
Enter your name: ECE
System.out.println("Age: " + age);
Name: ECE
}
Enter your age: 11
}
Age: 11
1

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Wrapper Class in Java
A wrapper class in Java is an object-oriented way to work with primitive data types. Each primitive data type in Java has
a corresponding wrapper class in the java.lang package, allowing primitive values to be treated as objects.

These classes are available in java.lang package

Primitive -> int float char long double


Wrapper Integer Float Character Long Double

Features of Wrapper Classes


Object Representation: Wrapper classes allow primitive types to be converted into objects.
Utility Methods: Provide methods for parsing, converting, and performing operations.
Autoboxing and Unboxing:
Autoboxing: Automatically converting a primitive type into its corresponding wrapper class.
Unboxing: Automatically converting a wrapper class object back to its primitive type.

public class Wrapper{

public static void main(String[] args) {

// Autoboxing: converting primitive to wrapper CLASS


int num = 10;
Integer numwrapper = num; // Autoboxing (primitive int DT to Integer CLASS)
System.out.println("Autoboxing: " + numwrapper); // 10

// Unboxing: converting wrapper CLASS back to primitive


int numunboxed = numwrapper; // Unboxing (Integer CLASS to primitive int DT)
System.out.println("Unboxing: " + numunboxed); // 10

// Using parseInt to convert string CLASS to int DT


String str = "123";
int parsedvalue = Integer.parseInt(str); // Parsing string to primitive int
System.out.println("parseInt: " + parsedvalue); // 123
System.out.println(((Object) parsedvalue).getClass().getName());

// Using valueOf to convert string to Integer


Integer valueofwrapper = Integer.valueOf(str); // valueOf returns an Integer object
System.out.println("valueOf: " + valueofwrapper); // 123

// Using toString to convert Integer to string


String numstring = numwrapper.toString(); // Converting Integer object to string
System.out.println("toString: " + numstring); // "10“
System.out.println(numstring.getClass().getName()); Output
} Autoboxing: 10
} Unboxing: 10
parseInt: 123
java.lang.Integer
valueOf: 123
toString: 10
In Java, you can find the datatype or class of an object using the getClass() method
java.lang.String
For class/object - var.getClass().getName()
For primitive DT - ((Object) var).getClass().getName()

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can
be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader
class.
Syntax
BufferedReader Object_name=new BufferedReader(new InputStreamReader(System.in));

Example
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[]) throws Exception
{
//Create scanner Object and pass string in it
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));

System.out.println("--------Enter Your Details-------- ");


System.out.print("Enter your name: ");
String name = sc.readLine();
System.out.println("Name: " + name);

System.out.print("Enter your age: ");


int i = Integer.parseInt(sc.readLine());
System.out.println("Age: " + i);

System.out.print("Enter your salary: ");


double d = Double.parseDouble(sc.readLine());
System.out.println("Salary: " + d);
}
}
Output
--------Enter Your Details--------
Enter your name: ECA&V
Name: ECA&V
Enter your age: 19
Age: 19
Enter your salary: 100000
Salary: 100000.0

Output Statement
In Java, System.out.println() is a statement that prints the argument passed to it. The println() method
display results on the monitor.

Example

System.out.println(“Welcome to Java Output”);

System.out.println(“Welcome”+a);
Note: In Java, the key difference between the Scanner class and BufferedReader is that Scanner is designed to
not only read input but also parse it into different data types like integers, doubles, and strings using
regular expressions, while BufferedReader primarily reads text data from a stream as characters, requiring
additional parsing to extract specific data types; making Scanner more user-friendly for basic input parsing
and BufferedReader better for efficient large-scale text reading.
3

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Arrays
Java array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on the 1st Index, and so on.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It does not grow its size at runtime. To solve this problem, a collection framework is used in Java
which grows automatically.

Types of Arrays in java


There are two types of arrays.
 One Dimensional Array
 Two-Dimensional Array
One Dimensional Array in Java Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
or
int intArray[] = new int[20]; // combining both statements in one
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class TestArray{
public static void main(String args[]){
int a[]=new int[2]; //declaration and instantiation Output
a[0]=10;//initialization 10
a[1]=20;
//traversing array
20
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array using Scanner to take input from the user and store it in an integer array.

import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Define the size of the array Output
System.out.print("Enter the size of the array: ");
int size = sc.nextInt();
// Declare the array Enter the size of the array: 3
int[] numbers = new int[size]; Enter 3 integers:
// Take input for each element in the array
System.out.println("Enter " + size + " integers:"); Enter element 1: 1
for (int i = 0; i < size; i++) { Enter element 2: 3
System.out.print("Enter element " + (i + 1) + ": ");
numbers[i] = sc.nextInt(); // Storing the input in the array
Enter element 3: 2
} Entered integers are:
// Display the entered array elements 132
System.out.println("Entered integers are:");
for (int num : numbers) {
System.out.print(num + " ");
}
sc.close(); // Close the scanner
}
}

Two-Dimensional Array in Java


In such cases, data is stored in a row and column-based index (also known as matrix form).
Syntax
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; - preferred
4
Example to instantiate Multidimensional Array in Java
Int arr[][]=new int[3][3]; //3 row and 3 column
24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)
Example: Program for 1Dimnl array – sorting, searching array
elements.
sorting and searching in Java, along with examples:
Sorting in Java
Java provides a variety of ways to sort data. The most common methods are: Using Arrays.sort()
This method is part of the java.util.Arrays class and works for arrays.

import java.util.Arrays;
import java.util.Comparator;

public class Main {


public static void main(String[] args) {
// Example 1: Sorting an array of integers
int[] numbers = {5, 2, 9, 1, 7};
Arrays.sort(numbers);
System.out.println("Sorted numbers: " + Arrays.toString(numbers));

// Example 2: Sorting an array of strings


String[] names = {"Alice", "Bob", "Charlie"};
Arrays.sort(names);
System.out.println("Sorted names: " + Arrays.toString(names));

// Example 3: Custom sorting with Comparator


Arrays.sort(names, Comparator.reverseOrder());
System.out.println("Reverse sorted names: " + Arrays.toString(names));
} Output
}
Sorted numbers: [1, 2, 5, 7, 9]
Sorted names: [Alice, Bob, Charlie]
Reverse sorted names: [Charlie, Bob, Alice]
Binary Search
Binary search is efficient but works only on sorted arrays or lists. If the array isn't sorted, you'll need to sort it first.
Using Arrays.binarySearch()
import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;

// Perform binary search


int index = Arrays.binarySearch(numbers, target);

if (index >= 0) {
System.out.println("Element "+ target + " found at
index: " + index);
} else { Output
System.out.println("Element not found.");
} Element 30 found at index: 2
}

5
Program for largest, smallest, sum of odd, and even numbers in Java. This
code demonstrates all the calculations using a single array of numbers.
import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] numbers = {12, 7, 5, 8, 19, 24, 33, 42, 3};

// Initialize variables
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int sumOfOdd = 0;
int sumOfEven = 0;

// Loop through the array


for (int num : numbers) {
// Find largest and smallest
if (num > largest) largest = num;
if (num < smallest) smallest = num;

// Calculate sum of odd and even numbers


if (num % 2 == 0) {
sumOfEven += num;
} else {
sumOfOdd += num;
}
}

// Output the results Output


System.out.println("Numbers: " + Arrays.toString(numbers));
System.out.println("Largest number: " + largest); Numbers: [12, 7, 5, 8, 19, 24, 33, 42, 3]
System.out.println("Smallest number: " + smallest); Largest number: 42
System.out.println("Sum of odd numbers: " + sumOfOdd);
Smallest number: 3
System.out.println("Sum of even numbers: " + sumOfEven);
} Sum of odd numbers: 67
Sum of even numbers: 86

6
Example: Program for 2Dimnl array - Matrix addition,
subtraction, multiplication
Main.java
import java.util.*; case 3:
class Main System.out.print("Multiplication of two
{ matrices\n");
public static void main(String args[]) for (int i=0;i<2;i++)
{ {
int a[][]={{1,3},{5,7}}; for (int j=0;j<2;j++)
int b[][]={{2,4},{6,8}}; {
int c[][]=new int[2][2]; c[i][j]=0;
int choice; for (int k=0;k<2;k++)
System.out.println("\nMatrix Menu"); {
System.out.println("\nAddition"); c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
System.out.println("Subtraction"); }
System.out.println("Multiplication"); System.out.print(c[i][j]+" ");
System.out.println("\nEnter your choice"); }
Scanner in=new Scanner(System.in); System.out.print("\n"); //System.out.println();
choice=in.nextInt(); }
switch (choice) break;
}
{ }
case 1: }
System.out.print("Addition of two matrices\n");
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.print("\n");
}
break;
case 2:
System.out.print("Subtraction of two matrices\n");
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
c[i][j]=a[i][j]-b[i][j];
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.print("\n");
} 7
break;
24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)
Class in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It cannot be physical.

A class in Java can contain:

 Variable
 Methods
 Constructors
 Blocks
 Nested class and interface

Syntax to declare a class:


class <class_name>
{
variable;
method;
}

Example
class Sample
{
int a,b; //variable declaration
public:
void get(); //method1
void display(); //method2
}

Declaring Objects
Syntax

classname objectname=new classname();

Example for declaring object

Sample s=new Sample();

Declaring Methods Syntax


return_type method_name(argument_list)
{
//statements;
}

Example for declaring method

void add(int a,int b)


{
int c=a+b;
System.out.println( c );
}
8

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Example Program to print the area of rectangle using class, method

class Rectangle
{
int mlength; int mwidth; //instance variable
void get(int length, int width) // local variable
{
mlength=length; mwidth=width;
}
void calculateArea()
{
System.out.println(mlength*mwidth);
}
}
class Main
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();

r1.get(11,5);
r1.calculateArea();

r2.get(3,15);
r2.calculateArea();
}
}

Output

55
45

Note:
Feature Program (Instance Variables)
Data Storage Uses instance variables (mlength, mwidth)
Persistence Stores values inside object
Method Calls Calls get() to set values first, then calculateArea()
Object State Each Rectangle object maintains its own dimensions

Code
More complex due to storing state
Simplicity

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Program to manage employee payroll, Create classes for employees with variables for
salary,allowance,and deduction. Implement methods to calculate net pay and control
statements for payroll processing.

import java.util.Scanner;
class Employee {
private String name;
private double salary;
private double allowance;
private double deduction;
public Employee(String name, double salary, double allowance, double deduction) {
this.name = name;
this.salary = salary;
this.allowance = allowance;
this.deduction = deduction;
}
public double calculateNetPay() {
return salary + allowance - deduction;
}
public String getName() {
return name;
}
}
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter employee name: ");
String name = sc.nextLine();
System.out.print("Enter salary: ");
double salary = sc.nextDouble();
System.out.print("Enter allowance: ");
double allowance = sc.nextDouble();
System.out.print("Enter deduction: ");
double deduction = sc.nextDouble();
Employee empl = new Employee(name, salary, allowance, deduction);
System.out.println("Employee Name: " + empl.getName());
System.out.println("Net Pay: " + empl.calculateNetPay());
sc.close(); Output
}
Enter employee name: ECA&V
}
Enter salary: 10000
Enter allowance: 1000
Enter deduction: 900
Employee Name: ECA&V
Net Pay: 10100.0

10
Access Controls / Access Specifier / Access
Modifier
Java provides four Access Modifiers to set access levels for classes, variables, methods, and constructors.
The four access levels are
1. default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package No modifiers are needed.
2. private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
3. public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
4. protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot be accessed from outside the
package.
Within Package
(Both sub class Outside Outside Package
Access Within Class and non-sub Package (Sub (Non-sub class Only)
Modifier class) class Only)
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes

class AccessSpecifier{
public String publicVar = "Public Variable"; // Public variable
private String privateVar = "Private Variable"; // Private variable
protected String protectedVar = "Protected Variable"; // Protected variable

public void publicMethod() { // Public method


System.out.println("This is a public method.");
}
private void privateMethod() { // Private method
System.out.println("This is a private method.");
}
protected void protectedMethod() { // Protected method
System.out.println("This is a protected method.");
}
// Method to demonstrate access within the same class
public void demonstrateAccess() {
System.out.println("Accessing within the same class:");
System.out.println(publicVar); // Public variable
System.out.println(privateVar); // Private variable
System.out.println(protectedVar); // Protected variable
publicMethod();
privateMethod();
protectedMethod();
}
}
public class Main {
public static void main(String[] args) {
AccessSpecifier as = new AccessSpecifier();
// // Demonstrating all access outside class
// Accessing variables OUTPUT
System.out.println("Accessing from outside class:");
Accessing from outside class:
System.out.println("Public Variable: " + as.publicVar);
Public Variable: Public Variable
// System.out.println("Private Variable: " + as.privateVar); // Error: privateVar is private
Protected Variable: Protected Variable
System.out.println("Protected Variable: " + as.protectedVar);
This is a public method.
This is a protected method.
// Accessing methods
as.publicMethod();
Accessing within the same class:
// as.privateMethod(); // Error: privateMethod is private
Public Variable
as.protectedMethod();
Private Variable
Protected Variable
// Demonstrating all access from within the same class
This is a public method.
as.demonstrateAccess();
11 This is a private method.
}
This is a protected method.
}

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


this keyword in Java
In Java, this is a reference variable that refers to the current object.

Usage of Java this keyword


1. this can be used to refer current class instance variable, invoke the current class method (implicitly)
2. this() can be used to invoke the current class constructor.
3. this can be passed as an argument in the method call, constructor call.
4. this can be used to return the current class instance from the method.

this: to refer current class instance variable


The “this” keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters variable, this keyword resolves the problem of ambiguity.
Example
With this keyword
class Student {
String name;
void data(String name){
this.name=name; // current class instance variable
}
void disp(){
System.out.println("Name:"+name);
}
public static void main(String args[]){
Student s1=new Student();
s1.data("A");
s1.disp();
}}
Now Output will be
Output:- Name:A
Without this keyword

class Student{
String mname; // instance variable
void data(String name){
mname=name;
}
void disp(){
System.out.println("Name:"+mname);
}
public static void main(String args[]){
Student s1=new Student();
s1.data("A");
s1.disp();
}}
Output
Output:- Name: A

Note: difference between parameter and instance variable in Java?


If the data is only used during a computation, pass it as a parameter.
If the data is bound to the lifetime of the object use an instance variable
12

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Constructors
Java supports a special kind of function, called “constructor,” which enables an object to
initialize itself when the object is created. Constructors have a similar name as the class itself.
They do not have a return type; the void is also not used as a return type.
There are several types of constructors in Java:
Default Constructor:
A default constructor is provided by the Java compiler if no other constructor is defined.
It has no parameters and does minimal initialization, typically setting default values.
public class MyClass {
Example:
// Default constructor Complex() { // default constructor
public MyClass() { real = 0.0;
// Initialization code, if any imag = 0.0;
} }
}
Parameterized Constructor:
A parameterized constructor is a constructor with parameters that allows you to initialize an
object with specific values. Example:
Complex(double real, double imag) { // Parameterized constructor
public class MyClass {
this.real = real;
// Parameterized constructor this.imag = imag;
public MyClass(int value) { }
// Initialization code using the provided parameter
}
}
Copy Constructor:
A copy constructor creates a new object by copying the values of an existing object of the same
class. Example:
public class MyClass { Complex(Complex obj) { // copy constructor
this.real = obj.real;
// Copy constructor this.imag = obj.imag; }
public MyClass(MyClass exobject) {
// Initialization code to copy values from the exobject
}
}
Constructor Overloading / method overloading
Constructor overloading
allows a class to have multiple constructors having the same name with different parameter lists.
Method Overloading in Java
If a class has multiple methods having the same name but different parameters, it is known as
Method Overloading. Example: Complex() is a method and a constructor overloaded
Complex() { // default constructor
public class MyClass { real = 0.0;
// Constructor with no parameters imag = 0.0;
public MyClass() { }
// Initialization code Complex(double real, double imag) { // Parameterized constructor
} this.real = real;
// Constructor with parameters this.imag = imag;
public MyClass(int value) { }
// Initialization code using the provided parameter Complex(Complex obj) { // copy constructor
} this.real = obj.real;
this.imag = obj.imag; }
}
}

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE) 13


Example : Constructors in JAVA
ONE PROGRAM FOR CONSTRUCTORS , TYPES OF CONSTRUCTORS (default
Constructor and Parameterized Constructor, copy constructor in JAVA)
AND METHOD OVERLOADING/CONSTRUCTOR OVERLOADING – Addition of
two complex numbers
The default constructor will not have any parameters whereas parameterized constructor can have one or more
parameters. A copy constructor is a special kind of constructor where the old object is passed as an argument for
the new object.

public class Complex {


private double real;
private double imag;

Complex() { // default constructor


real = 0.0;
imag = 0.0;
}

Complex(double real, double imag) { // Parameterized constructor


this.real = real;
this.imag = imag;
}

Complex(Complex num1, Complex num2) { // Copy constructor with addition


this.real = num1.real + num2.real;
this.imag = num1.imag + num2.imag;
}

public void display() { // Method to display the complex number


System.out.println(real + " + " + imag + "i");
}

public static void main(String[] args) {


Complex num1 = new Complex(3, 4); // Create two complex numbers
Complex num2 = new Complex(1, 2);

Complex sum = new Complex(num1, num2); // Use copy constructor to add two complex numbers

System.out.print("The sum of the two complex numbers is: "); // Display the result

sum.display();
}
}

OUTPUT :
The sum of the two complex numbers is: 4.0 + 6.0i

•Computes the product of two complex numbers using the formula: (a+bi)×(c+di)=(ac−bd)+(ad+bc)i
•realPart = (num1.real * num2.real) - (num1.imag * num2.imag)
•imagPart = (num1.real * num2.imag) + (num1.imag * num2.real)
14
24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)
ONE PROGRAM FOR CONSTRUCTORS , TYPES OF CONSTRUCTORS (default,
Parameterized, copy constructor in JAVA), AND METHOD OVERLOADING
/CONSTRUCTOR OVERLOADING for complex nos (add, sub,multiplication)
public class Complex {
private double real; // Real part of the complex number
private double imag; // Imaginary part of the complex number

Complex() { // Default constructor


real = 0.0;
imag = 0.0;
}
Complex(double real, double imag) { // Parameterized constructor
this.real = real;
this.imag = imag;
}
Complex(Complex num1, Complex num2) { // Copy constructor with addition
this.real = num1.real + num2.real;
this.imag = num1.imag + num2.imag;
}
// Method for subtracting two complex numbers
public static Complex subtract(Complex num1, Complex num2) { // subtract() is a method,
double realPart = num1.real - num2.real; // Complex(Complex num1, Complex num2)
double imagPart = num1.imag - num2.imag; // since Complex constructor can’t be overloaded
return new Complex(realPart, imagPart);
}
// Method to multiply two complex numbers
public static Complex multiply(Complex num1, Complex num2) {
double realPart = (num1.real * num2.real) - (num1.imag * num2.imag);
double imagPart = (num1.real * num2.imag) + (num1.imag * num2.real);
return new Complex(realPart, imagPart);
}
// Method to display the complex number
public void display() {
System.out.println(real + " + " + imag + "i");
}
public static void main(String[] args) {
// Create two complex numbers
Complex num1 = new Complex(3, 4);
Complex num2 = new Complex(1, 2);

// Calculate the sum using the copy constructor


Complex sum = new Complex(num1, num2);
System.out.print("The sum of the two complex numbers is: ");
sum.display();

// Calculate the subtraction of the two complex numbers


Complex difference = Complex.subtract(num1, num2);
System.out.print("The difference of the two complex numbers is: ");
difference.display();

// Calculate the product of the two complex numbers


Complex product = Complex.multiply(num1, num2);
System.out.print("The product of the two complex numbers is: ");
product.display();
}
}
OUTPUT :
The sum of the two complex numbers is: 4.0 + 6.0i
The difference of the two complex numbers is: 2.0 + 2.0i
The product of the two complex numbers is: -5.0 + 10.0i

15
Java Static Keyword
The static keyword in Java is used for memory management mainly. We can apply static
keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Class
The static keyword is used when a member variable of a class has to be shared between all the instances of the class.
All static variables and methods belong to the class and not to any instance of the class

// Main.java
class Staticdemo{
static int staticvariable = 5; // Static variable
int nstaticvariable = 10; //non-static variable
static void staticmethod() { // Static method
System.out.println("This is a static method.");
}
}
class Main {
public static void main(String[] args) {

Staticdemo.staticvariable=50; //class loaded, direct access to without instance


System.out.println("Static Variable: " + Staticdemo.staticvariable);

//System.out.println("non Static Variable: " + Staticdemo.nstaticVariable); //ERROR not valid


Staticdemo sd = new Staticdemo();
sd.nstaticvariable = 200; //valid, set value for non static variable after instance
System.out.println("non Static Variable: " + sd.nstaticvariable); //valid non static

Staticdemo.staticmethod(); // Accessing static method


Nested.nestedmethod(); // Accessing static nested class, method
}

static class Nested { // Static nested class


static void nestedmethod() {
System.out.println("This is a static method inside a static nested class.");
}
}
}

Output
Static Variable: 50
non Static Variable: 200
This is a static method.
This is a static method inside a static nested class.

In this example:
1.staticvariable is a static variable, shared among all instances of the class.
2.staticmethod() is a static method, and it can be called without creating an instance of the class.
3.Nested is a static nested class, and it can be used without instantiating the outer class.
You can run this program to see how static variables, methods, and nested classes work in Java.
17

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Final Keyword in Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many
contexts. The Final can be:
1. Variable - final variable - stop value changes
2. Method - final Method - stop method overriding
3. Class - final Class - stop inheritance
In Java, the final keyword is used to restrict the modification of classes, methods, and variables.
Here's an example of a program that demonstrates the use of final with a final variable, a final
method, and a final class:.

Java final variable


If you make any variable final, you cannot change the value of a final variable (It will be constant).
Example of final variable
There is a final variable AGE, we are going to change the value of this variable, but it cannot be changed
because the final variable once assigned a value can never be changed.
Example
class Main{
public static void main(String[] args){
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
Output
cannot assign a value to final variable AGE AGE = 45;^
Using final with inheritance – final method, final class
Java final method
If you make any method final, you cannot override it.
Example
//Main.java
class Finaldemo {
// create a final method
public final void display(){
System.out.println("This is a final method.");
}
}
class Main extends Finalemo{
// try to override final method
public final void display(){
System.out.println("The final method is overridden.");
}
public static void main(String[] args){
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final method named display() inside the FinalDemo class. Here, the Main
class inherits the FinalDemo class. We have tried to override the final method in the Main class. When we run
the program, we will get a compilation error with the following message.
Output
display() in Main cannot override display() in FinalDemo public final void
display() {
^
overridden method is final 18

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)


Java final class
Java final class - When you declare a class as final, it cannot be extended. Final classes prevent
Inheritance. If you try, it gives a compile time error.

Example
final class Finalclass{
void myMethod() {
System.out.println("We are in the final class we just created");
}
}

class Subclass extends Finalclass{


void myMethod() {
System.out.println("We are in the subclass");
}
}

class Main{
public static void main(String arg[]){
Finalclass fc = new Subclass();
fc.myMethod();
}
}

Output :

Main.java:7: error: cannot inherit from final Finalclass class Subclass extends Finalclass{ ^ 1 error

19

24CS202 JAVA PROGG UNIT I - Meenakshi, Dept.of S&H (GE)

You might also like