24cs202 Java Progg Uniti Java Fundamentals to Stud
24cs202 Java Progg Uniti Java Fundamentals to Stud
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.
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
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.
Version Release date End of Public Updates (Free) End of Extended Support (Paid)
… … … …
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
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
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
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.
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.
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
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.
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.
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));
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”+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
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
}
}
import java.util.Arrays;
import java.util.Comparator;
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;
// Initialize variables
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int sumOfOdd = 0;
int sumOfEven = 0;
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.
Variable
Methods
Constructors
Blocks
Nested class and interface
Example
class Sample
{
int a,b; //variable declaration
public:
void get(); //method1
void display(); //method2
}
Declaring Objects
Syntax
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
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
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
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
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) {
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
Example
final class Finalclass{
void myMethod() {
System.out.println("We are in the final class we just created");
}
}
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