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

Unit 1

The document outlines the Java Programming course objectives and learning outcomes, focusing on fundamental programming concepts, object-oriented principles, exception handling, multithreading, JDBC connectivity, and GUI design. It also provides a historical overview of Java's development, key features, and programming constructs such as data types, variables, input/output methods, and operators. Additionally, it explains the roles of JVM, JRE, and JDK in executing Java programs.

Uploaded by

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

Unit 1

The document outlines the Java Programming course objectives and learning outcomes, focusing on fundamental programming concepts, object-oriented principles, exception handling, multithreading, JDBC connectivity, and GUI design. It also provides a historical overview of Java's development, key features, and programming constructs such as data types, variables, input/output methods, and operators. Additionally, it explains the roles of JVM, JRE, and JDK in executing Java programs.

Uploaded by

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

1

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC

SY. B.Tech

PIMPRI CHINCHWAD UNIVERSITY


2

Course Objectives (CO):


• The objectives of Java Programming are:
To learn the fundamentals of the Java programming language.
To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.

To apply the concepts of exception handling, multithreading and collection


classes using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
3

Course Learning Outcomes (CLO):


• Students would be able to:
To grasp the fundamentals programming concepts of Java programming
language.
To apply object-oriented principles like abstraction, encapsulation,
inheritance, polymorphism in solving problems using java.
To perform exception handling, multithreading code using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- I
Introduction to Java Programming
5

History of Java
Developers: Java was developed by James Gosling, Mike Sheridan, and Patrick
Naughton.

Organization: It was created as part of a project at Sun Microsystems (later acquired


by Oracle Corporation).

Start Date: The project began in 1991 and was originally called "The Green
Project".

Purpose: The goal was to create a platform-independent, object-oriented


programming language for electronic devices like set-top boxes and televisions.
PIMPRI CHINCHWAD UNIVERSITY
5

History of Java
• The language was initially named Oak, after an oak tree that stood outside
James Gosling's office.

• Later, it was renamed Java after the developers realized that the name
"Oak" was already trademarked. The name "Java" was inspired by the
coffee that the developers drank during the development process.

PIMPRI CHINCHWAD UNIVERSITY


5

History of Java

Year Event
The "Green Project" was initiated at Sun Release of Java 8, introducing streams,
1991 2014
Microsystems. lambdas, and other key features.
Java 9 introduced the modular system
1995Java 1.0 was officially released. 2017
(Project Jigsaw).
Java was formally standardized under the Java
1997 Oracle moved Java to a 6-month release cycle
Community Process (JCP). 2018
for quicker updates.
Release of Java 2 (J2SE 1.2), which introduced
1998 Java 17 became the next Long-Term Support
significant enhancements. 2021
(LTS) version.
Release of Java 5 (J2SE 5.0), adding generics,
2004
annotations, and more.
Oracle acquired Sun Microsystems, taking over Java
2010
development.
PIMPRI CHINCHWAD UNIVERSITY
5

History of Java
1. Java 1.0 (1995):
o First official release.
o Introduced the write-once-run-anywhere (WORA) principle.
o Included the first version of the JVM.
2. Java 2 (1998):
o Introduced Swing for graphical user interfaces (GUIs).
o Split into three editions:
▪ J2SE (Java 2 Standard Edition)
▪ J2EE (Java 2 Enterprise Edition)
▪ J2ME (Java 2 Micro Edition)
PIMPRI CHINCHWAD UNIVERSITY
5

History of Java
1. Java 5 (2004):
o Significant update with generics, enhanced for-loop, autoboxing/unboxing, and annotations.
o Introduced the enum type.
2. Java 8 (2014):
o Introduced lambda expressions, streams API, and a new date-time API.
o Revolutionized functional programming in Java.
3. Java 9 (2017):
o Introduced the modular system (Project Jigsaw) for better dependency management.
4. Java 17 (2021):
o Long-Term Support (LTS) version.

o Added sealed classes, pattern matching for switch, and more.


PIMPRI CHINCHWAD UNIVERSITY
6

Comments in Java
• Single-line comments: // This is a single-line comment
• Multi-line comments:
• /* This is a
• multi-line comment */

PIMPRI CHINCHWAD UNIVERSITY


7

Java Buzzwords
• Simple: Easy to learn and implement.
• Object-Oriented: Based on classes and objects.
• Secure: Prevents unauthorized access via bytecode verifier and Security Manager.
• Portable: Write Once, Run Anywhere (WORA) with JVM.
• Robust: Strong memory management, exception handling, and garbage collection.
• Multithreaded: Supports concurrent programming.
• High Performance: Enabled via Just-In-Time (JIT) compiler.
• Architectural Neutral: Java's bytecode is not specific to any processor or operating system, making it
platform-independent.
• Distributed Applications: Facilitates the development of distributed systems using tools like Remote
Method Invocation (RMI) and support for networked applications via APIs.

PIMPRI CHINCHWAD UNIVERSITY


8

OOP's Concepts
• Object
• Class
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

PIMPRI CHINCHWAD UNIVERSITY


9

First Java Program | Hello World Example


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

PIMPRI CHINCHWAD UNIVERSITY


10

Parameters used in First Java Program


• class keyword is used to declare a class in Java.
• public keyword is an access modifier that represents visibility. It means it is visible to all.
• static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static
method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM,
so it does not require creating an object to invoke the main() method. So, it saves memory.
• void is the return type of the method. It means it does not return any value.
• The main() method represents the starting point of the program.
• String[] args or String args[] is used for command line argument. We will discuss it in coming section.
• System.out.println() is used to print statement on the console. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class. We will discuss the internal working of
System.out.println() statement in the coming section.

PIMPRI CHINCHWAD UNIVERSITY


JRE

https://www.javatpoint.com/difference-between-jdk-jre-and-jvm
JDK
JVM
12

Role of JVM , JRE and JDK

PIMPRI CHINCHWAD UNIVERSITY


13

Role of JVM , JRE and JDK


• JVM: Java Virtual Machine loads the byte code, verifies it, and executes the code. It is
specific to every operating system, but why java code is called to Write Once and Run
Anywhere (WORA) because the byte code I. e .class file is compatible with running on all OS
with specific JVM.
• JRE: Java Program needs to associate with required libraries to execute the program and
guess what these libraries are part of JRE (Java Run Time Environment) which includes
ClassLoader, Byte Code verifier, and many other libraries.
• JDK: Java Development Kit, so we have written a java program but who is going to compile
that and debug the code if we have errors in the code and the Javadoc for the methods and
classes, so all these are embedded in the Java Development Kit.

PIMPRI CHINCHWAD UNIVERSITY


11

Execution of Java Program

PIMPRI CHINCHWAD UNIVERSITY


14

Keywords
In Java, keywords are reserved words that have a predefined meaning and cannot be used as
identifiers (such as variable names, class names, or method names).

These words are part of the Java language syntax and are used to define the structure and
behavior of a Java program.

Characteristics of Java Keywords:


1.Predefined: Keywords are part of the Java syntax and cannot be changed.
2.Case-sensitive: All Java keywords are written in lowercase.
3.Non-usable as Identifiers: Keywords cannot be used for naming variables, methods, classes, or
other identifiers.

PIMPRI CHINCHWAD UNIVERSITY


14

Keywords

PIMPRI CHINCHWAD UNIVERSITY


15

Naming Conventions
• Name should not match with keywords
• Class:
• Begin with capital letter (Single Word)
• Every first letter must be capital (Multiple Words)
• Method:
• Begin with lower case letter (Single Word)
• Every first letter of other word must be capital (Multiple Words)
• Variable:
• Begin with alphabet or underscore
• Should not begin with a dight
• It may contain alphanumeric letters but special symbols are not allowed except
underscore

PIMPRI CHINCHWAD UNIVERSITY


16

Data Types

PIMPRI CHINCHWAD UNIVERSITY


16

Numeric Data Types


Type Size Default Value Description
byte 1 byte 0 Stores whole numbers from -128 to 127.
short 2 bytes 0 Stores whole numbers from -32,768 to 32,767.
int 4 bytes 0 Stores whole numbers from -2³¹ to 2³¹-1.
long 8 bytes 0L Stores whole numbers from -2⁶³ to 2⁶³-1.
Stores fractional numbers, up to 7 decimal
float 4 bytes 0.0f
digits.
Stores fractional numbers, up to 15 decimal
double 8 bytes 0.0d
digits.

PIMPRI CHINCHWAD UNIVERSITY


16

Non-Numeric Data Types

Type Size Default Value Description


Stores a single 16-bit
char 2 bytes '\u0000'
Unicode character.

Type Size Default Value Description


Stores one of two
boolean 1 bit (virtual) false
values: true or false.

PIMPRI CHINCHWAD UNIVERSITY


16

Non-Premitive Data Types

Non-primitive types (or reference types) include objects, arrays, and classes. They do not store the value directly
but rather a reference to the memory location.
Examples of Non-Primitive Data Types
1. Strings (e.g., String name = "Java";)
2. Arrays (e.g., int[] numbers = {1, 2, 3};)
3. Classes (e.g., MyClass obj = new MyClass();)
Interfaces (e.g., Runnable task = new MyRunnable();)

PIMPRI CHINCHWAD UNIVERSITY


16

Key Differences Between Primitive and


Non-Primitive Data Types

Feature Primitive Non-Primitive


No (defined by the
Predefined Yes
programmer)
Memory Size Fixed Variable
Null Value Not applicable Can be null
Operations Direct operations (e.g., +, -) Methods can be invoked

PIMPRI CHINCHWAD UNIVERSITY


17

Data Types - Example


public class DataTypeExample {
public static void main(String[] args) {
// Primitive Types
int age = 30;
float height = 5.9f;
char grade = 'A';
boolean isEligible = true;

// Non-Primitive Types
int[] marks = {90, 85, 88};
String name = "Alice";

// Display values
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Eligibility: " + isEligible);
System.out.println("First Mark: " + marks[0]);
}
} PIMPRI CHINCHWAD UNIVERSITY
20

Constants

• - Defined using the final keyword.


• - Example:
final double PI = 3.14159;

• A final variable can only be assigned once, either at the time of declaration or in the
constructor (if it's a class field).
• Use UPPERCASE letters with underscores for separating words in the constant name.
• Declare constants as static final in classes if they are shared across multiple instances.

PIMPRI CHINCHWAD UNIVERSITY


18

Variables
• Declaration: dataType variableName = value;
• Types:
• Instance variables: Defined outside methods; specific to an object.
• Static variables: Defined with static keyword; shared across all objects.
• Local variables: Declared inside a method, constructor, or block; exist
during method execution.

PIMPRI CHINCHWAD UNIVERSITY


19

Variables - Example
class Example {
int instanceVar;
static int staticVar;
void method() {
int localVar = 10;
}
}

PIMPRI CHINCHWAD UNIVERSITY


21

Input / Output
• IO Stream
Is associated with java.lang.*; package. This package is imported by default
in java code.
• System.in: Read data from keyboard
• System.out: Display data on screen
• System.err: Display error message
• Output methods
• System.out.print(): Print everything on a single line
• System.out.println(): Prints statements on next line
• System.out.printf(): Similar to C language function, used for formatted
output

PIMPRI CHINCHWAD UNIVERSITY


22

Scanner Class
• The Scanner class in Java is part of the java.util package and is used to take
input from various input sources like keyboard input, files, strings, etc. It
provides methods to parse primitive types (e.g., int, float, boolean) and
strings from the input source.

• How to Use the Scanner Class


Import the Class:
import java.util.Scanner;

PIMPRI CHINCHWAD UNIVERSITY


23

Scanner Class
Create a Scanner Object:
Scanner scanner = new Scanner(System.in);

Use Methods to Read Input:


int number = scanner.nextInt();
String text = scanner.nextLine();

Close the Scanner:


scanner.close();

PIMPRI CHINCHWAD UNIVERSITY


24

Commonly Used Methods of Scanner


Method Description
nextInt() Reads an int value.
nextFloat() Reads a float value.
nextDouble() Reads a double value.
nextBoolean() Reads a boolean value (true/false).
next() Reads a single word (delimited by whitespace).
nextLine() Reads an entire line, including spaces.
nextShort() Reads a short value.
nextLong() Reads a long value.
hasNextInt() Checks if the next token can be interpreted as an int.
hasNext() Checks if there is another input token available.
PIMPRI CHINCHWAD UNIVERSITY
25

Operators
• Arithmetic: +, -, *, /, %
• Relational: ==, !=, <, >, <=, >=
• Logical: &&, ||, !
• Bitwise: &, |, ^, ~, <<, >>
• Assignment: =, +=, -=, etc.

PIMPRI CHINCHWAD UNIVERSITY


26

Type Conversion and Casting


• Implicit Casting (Widening)
• Converting smaller data types to larger types automatically.

• Example:
int a = 100;
double b = a; // int to double
System.out.println(b); // Output: 100.0

PIMPRI CHINCHWAD UNIVERSITY


27

Type Conversion and Casting


• Explicit Casting (Narrowing)
• Converting larger data types to smaller types explicitly.
• Example:
double x = 99.99;
int y = (int) x; // double to int
System.out.println(y); // Output: 99

PIMPRI CHINCHWAD UNIVERSITY


28

Enum
• An enum is a special "class" that represents a group
of constants (unchangeable variables, like final variables).
• To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma. Note that they should be in uppercase
letters:

PIMPRI CHINCHWAD UNIVERSITY


Syntax:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3, ...
}

Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Features of Enums

1. Fixed Set of Constants: Values are predefined and cannot be modified.


2. Type-Safe: Ensures only valid values are used.
3. Implicitly public static final: Enum constants are implicitly public, static, and final.
4. Can Include Methods and Fields: Enums can have methods, constructors, and fields.
5. Supports Iteration: You can iterate over enum constants using the values() method.
29

Enum : Example 1
1. Accessing Enum Values
You can access enum values using the dot (.) operator.
Day today = Day.MONDAY;
System.out.println(today); // Output: MONDAY

2. Looping Through Enum Values


Use the values() method to get all the constants of an enum.
for (Day day : Day.values()) {
System.out.println(day);
}

PIMPRI CHINCHWAD UNIVERSITY


29

Enum : Example 1
• enum Level {
• LOW,
• MEDIUM,
• HIGH
• }

• public class Main {


• public static void main(String[] args) {
• Level myVar = Level.MEDIUM;
• System.out.println(myVar);
• }
• }

PIMPRI CHINCHWAD UNIVERSITY


30

Enum : Example 2
• enum Level {

• LOW,

• MEDIUM,

• HIGH

• }

PIMPRI CHINCHWAD UNIVERSITY


31

Enum : Example 2
• public class Main {

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

• Level myVar = Level.MEDIUM;

• switch(myVar) {

• case LOW:

• System.out.println("Low level");

• break;

• case MEDIUM:

• System.out.println("Medium level");

• break;

• case HIGH:

• System.out.println("High level");

• break;

• }

• }

• }

PIMPRI CHINCHWAD UNIVERSITY


Built-in Methods for Enums
Java provides several built-in methods for enums:
1. values(): Returns an array of all enum constants.
Level[] levels = Level.values();
2. ordinal(): Returns the zero-based position of the enum constant.
System.out.println(Level.HIGH.ordinal()); // Output: 2
3. name(): Returns the name of the enum constant as a String.
System.out.println(Level.HIGH.name()); // Output: HIGH
4. valueOf(String name): Converts a string to its corresponding enum constant.
Level l = Level.valueOf("MEDIUM");
System.out.println(l); // Output: MEDIUM
Advantages of Enums
1. Readable Code: Enums provide a clear way to define and use a fixed set of constants.
2. Compile-Time Safety: Prevents invalid values at compile time.
3. Type Safety: Ensures only valid values are assigned to variables.

Limitations of Enums
1. Cannot extend other classes (because enums implicitly extend java.lang.Enum).
Cannot create an instance of an enum using the new keyword.
32

Control Flow
• Block Scope: Variables defined inside {} are not accessible outside.
• Example:
public class BlockScopeExample {
public static void main(String[] args) {
{
int x = 10; // x is accessible only within this block
System.out.println("Value of x: " + x); // Output: 10
}
// System.out.println(x); // Error: x cannot be resolved to a variable
}
}

PIMPRI CHINCHWAD UNIVERSITY


33

Conditional Statements
• if-else : Executes a block of code based on whether a condition is true or false.
• Example:
public class IfElseExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


34

Conditional Statements
• switch-case : Allows selection from multiple options based on the value of an expression.
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday"); // Output: Wednesday
break;
default:
System.out.println("Invalid day");
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


35

Loops
• for : Executes a block of code a specific number of times.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


36

Loops
• while : Repeats a block of code as long as the condition is true.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


37

Loops
• do-while : Executes a block of code at least once and then repeats as long
as the condition is true.
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
}
}
PIMPRI CHINCHWAD UNIVERSITY
38

Break and Continue


• break: Exits a loop immediately when encountered.
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i is 3
}
System.out.println("Count: " + i);
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


39

Break and Continue


• continue: Skips the current iteration of the loop and proceeds to the next one.
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
System.out.println("Count: " + i);
}
}
}

PIMPRI CHINCHWAD UNIVERSITY


40

Arrays
• Arrays in Java: An array is a collection of elements of the same type. It is
used to store multiple values in a single variable.
• Steps to Use Arrays
🞄 Declare the array:
dataType[] arrayName;
• Initialize the array:
arrayName = new dataType[size];
🞄 OR
dataType[] arrayName = {value1, value2, value3};
• Access elements using their index:
• Array indexing starts from 0.

PIMPRI CHINCHWAD UNIVERSITY


41

Example: Adding All Elements in an Array


public class ArrayAddition {
public static void main(String[] args) {
// Step 1: Declare and initialize the array
int[] numbers = {10, 20, 30, 40, 50};

// Step 2: Variable to store the sum


int sum = 0;

// Step 3: Loop through the array to add each element


for (int i = 0; i < numbers.length; i++) {
sum += numbers[i]; // Add each element to sum
}

// Step 4: Print the result


System.out.println("The sum of all elements in the
array is: " + sum);
}
}
42

Standalone Programs
1. Write a program to print "Welcome to Java Programming".
2. Write a program to add two numbers entered by the user.
3. Write a program to calculate the difference, product, and division of two numbers.
4. Write a program to find the square of a number.
5. Write a program to check if a number is even or odd.
6. Write a program to check if a number is positive, negative, or zero.
7. Write a program to find the largest of three numbers entered by the user.
8. Write a program to print the multiplication table of a given number.
9. Write a program to calculate the factorial of a number.
PIMPRI CHINCHWAD UNIVERSITY
43

Standalone Programs
10. Write a program to print all even numbers from 1 to 100.
11. Write a program to check if a given string is a palindrome.
12. Write a program to count the number of vowels in a given string.
13. Write a program to reverse the digits of a number.
14. Write a program to check if a given number is a palindrome.
15. Write a program to find the sum of digits of a number.
16. Write a program to print the Fibonacci series up to n terms.
17. Write a program to calculate the sum of the first n natural numbers.
18. Write a program to check if a given number is prime.
PIMPRI CHINCHWAD UNIVERSITY

You might also like