0% found this document useful (0 votes)
9 views31 pages

Java Unit-1

The document provides an introduction to Java, covering its history, key components like JDK, JRE, and JVM, and basic programming concepts such as variables, data types, and operators. It details the evolution of Java from its inception by the Green Team to its current version, Java SE 8, and explains the structure of a simple Java program. Additionally, it outlines the different types of variables, data types, and operators used in Java programming.

Uploaded by

varayaramala
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)
9 views31 pages

Java Unit-1

The document provides an introduction to Java, covering its history, key components like JDK, JRE, and JVM, and basic programming concepts such as variables, data types, and operators. It details the evolution of Java from its inception by the Green Team to its current version, Java SE 8, and explains the structure of a simple Java program. Additionally, it outlines the different types of variables, data types, and operators used in Java programming.

Uploaded by

varayaramala
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

UNIT-I

Introduction to JAVA,Variables, Constants, Data types,Keywords,Operators and Expressions. Control


and Loop statements in JAVA,Functions in JAVA

History of Java
Java history is interesting to know. The history of java starts from Green Team. Java team members
(also known as Green Team), initiated a revolutionary task to develop a language for digital devices
such as set-top boxes, televisions etc. For the green team members, it was an advance concept at that
time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3)Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project. Why Oak name
for java language?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc. During 1991 to 1995 many people around the world contributed to the
growth of the Oak, by adding the new features. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank
Yellin, and Tim Lindholm were key contributors to the original prototype.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

Prepared by [Link]
Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun Microsystems in
1995. It is mostly used for building desktop applications, web applications, Android apps, and
enterprise systems.

Differences Between JDK, JRE and JVM

Understanding the difference between JDK, JRE, and JVM plays a vital role in
understanding how Java works and how each component contributes to the development and
execution of Java applications.

 JDK stands for Java Development Kit. It is a set of development tools and libraries used
to create Java programs. It works together with the JVM and JRE to run and build Java
applications.

 JRE stands for Java Runtime Environment, and it provides an environment to run Java
programs on the system. The environment includes Standard Libraries and JVM.

 JVM stands for Java Virtual Machine. It's responsible for executing the Java program.

Note: Java bytecode can run on any machine with a JVM, but JVM
implementations are platform-dependent for each operating system.

Sample program in java:-


public class HelloWorld { // class name
public static void main(String[] args) { // main method
[Link]("Hello, World!");
}
}

Prepared by [Link]
Explanation:-

1. Comments:-
 Anything after // is a comment.
 Comments are ignored by the compiler.
 They help you describe what your code does.
2. Class Declaration:-
 Every Java program must have at least one class.
 The class name must match the filename (so this file should be saved as
[Link]).
 public means the class can be accessed from any where.
[Link] Method:-

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

This is where your program starts [Link]’s break down the parts:

PublicThis is an access modifier. It means the method can be called from any
where the JVM (Java Virtual Machine) must be able to access it to start the
program.

StaticIt means the method belongs to the class, not to any object. The JVM doesn’t
need to create an object of the class to run it.

VoidThis means the method does not return any value. The main method just runs the
program — it doesn’t give any output to the JVM.

MainThis is the method name that the JVM looks for when it starts executing a Java
program. If it’s named differently, the program won’t run.

String[] argsThis is the parameter that holds command-line arguments. You can
pass arguments to your Java program when you run it from the terminal. Example:
java Main hello world
→ args[0] = "hello", args[1] = "world".

Prepared by [Link]
Java Variables
In Java, variables are containers used to store data in memory. Variables define how
data is stored, accessed, and manipulated.
A variable in Java has three components
 Data Type: Defines the kind of data stored (e.g., int, String, float).
 Variable Name: A unique identifier following Java naming rules.
 Value: The actual data assigned to the variable.
Variable Declaring
To create a variable in Java, you need to:
 Choose a type (like int or String)
 Give the variable a name (like x, age, or name)
Syntax:-

Type variableName=value; (int a=10)


Types of Variables :-
1. Local Variables
2. Instance Variables (Non-static)
3. Static Variables (Class Variables)

1. Local Variables
 Declared inside a method, constructor, or block.
 Created when the method is called and destroyed when it exits.
 Cannot be accessed outside the method or block.
 Must be initialized before use.
Example :-
public class Example {
void display() {
int i= 10; // local variable
[Link]("Number: " + i);
}
}
2. Instance Variables
 Declared inside a class, but outside any method.
 Each object (instance) of the class gets its own copy.
 Default values are assigned if not initialized (e.g., 0, false, null)
Example:-
Class Test{
Int i=10
Public static void main(String[] args){
Test t=new Test();
[Link](t.i);
}
}

Prepared by [Link]
3. Static Variables (Class Variables)

 Declared using the keyword static.


 Shared among all objects of the class (only one copy exists).
 Can be accessed using the class name.

Example:-

class Test
{
static int i=10;
public static void main(String[] args)
{
[Link](i);
}
}
Java Data Types
 Data type describe what type of value we want to store inside a variable
 Data type also tells how much memory has to be created for a variable
The Java data types are categorized into two main categories
 Primitive
 Non-Primitive

A. Primitive data types


Primitive data types are whose variables allows us to store only one value but they never allow us to store
multiple values of same type. This is a data type whose variables can hold maximum one value at a time.
Example:
int a;
a=10;//valid a=10,20,30;//invalid
B. Non Primitive Data Types or Derived

Prepared by [Link]
Derived data types are those which are developed by programmers by making use of appropriate features
of the language. User defined data types related variables allow us to store multiple values either of same
type or different type or both.
Example:
Student s=new Student();

Java defines some primitive types of data. They are:


 Integer types
 Character types
 Floating type
 Boolean type

[Link] Types :
This type indicates byte, short, int, long which are for whole-valued signed numbers.
The width and ranges of these integer types vary widely as shown in below :

Integer

Byte Short Int Long

Name Width Range


Long 64 -9,223,372,036,854,775,80 TO 9,223,372,036,854,775,807

Int 32 -2.147,483,648 to 2.147,483,647

Short 16 -32,768 to 32,767

Byte 8 -128 to 127

Byte :

 The smallest integer type is byte.


 This is a signed 8-bit type that has a range from –128 to 127
 byte are especially useful when you’re working with a stream of data from a network or file.
 Byte data type are declared by use of the byte keyword.
For example
byte b=120
byte c=-65 //where b and c are the identifiers

Short:

 Short is signed as 16 bit type


 It has range from -32,768 to 32,767
 It is declared by short keyword
For example:
short a=7426;

Prepared by [Link]
Int :

 The most commonly used type is integer type is int.


 It is signed as 32 bit type and has range from -2,147,483,648 to 2,147,483,647
 We can store byte and short values in an int
Example
int x=12;

Long:

 long is signed as 64-bit type and is useful for those occasions where as int.
 The range of long is quite large.
 This makes it useful when big, whole numbers are needed.

[Link] Point Types :

 This group includes float and double which represented numbers in


fractional precision.
 They are two types of floating point types ,float and double, which
represents single and double precision numbers

Name Width in bits Approximate range

Double 64 4.9e-324 to 1.8e+308


Float 32 1.4e-045 to 3.4e+038
3. Characters :
 In Java, the data type is used to store characters is char.
 Char in java is not same as C or C++
 In C/C++ char is 8 bit type whereas in java char is 16-bit type
4. Boolean Type :
 Java has a primitive data type called Booleans, for logical values.
 It can have only one of two possible values true or false.

OPERATORS AND EXPRESSIONS

 In java Operators are symbols that are used to perform some operations on the operands.
 Combination of operands and operators are known as Expressions.
 Java provides, a rich set of operators to manipulate the variables.
 There are three types of operators in java.
1. Unary operators
2. Binary operators
3. Ternary operators

Prepared by [Link]
Prepared by [Link]
UNARY OPERATORS:
In which we use one operand is called unary operator. It has two types:
1.1 Increment Unary operator
1.2 Decrement Unary operator
1.1 INCREMENT UNAY OPERATOR:
This is used to increase the value one by one. It has two types:
* Post-fix Increment operator
* pre-fix Increment operator
1.1.1 POST-FIX INCREMENT OPERATOR:
“++” symbol is used to represent Post-fix Increment operator. This symbol is used
after the operand.
In this operator, value is first assign to a variable and then incremented the value.
EX: int a , b;
a=10;
b=a++;
In the above example first the value of “a” is assign to the variable “b”, then I
Increment the value, so the value of b variable is “10”

1.1.2 PRE-FIX INCREMENT OPERATOR:

“++” symbol is used to represent Pre-Fix operator, this symbol is used after the
operand. In this operator value is incremented first and then assigned to a
variable.
EX: int a,b; a=10;
b=++a;
In the above example first the increment is done then the value of “a” variable is
assigned to the variable “b”, so the value of “b” variable is “11”.
1.2 DECREMENT UNARY OPERATOR:

“-” symbol is used to decrease the value by one. It has two types:
1. Post-fix decrement operator
2. pre-fix decrement operator
1.2.1 POST_FIX DECREMENT OPEATOR:
“-” symbol is used to represent post-fix decrement operator, this symbol is used
after the operand. In this operator, value is first assigned to a variable and then
decrement the value.
EX: int a , b; a=10;
b=a--;

In the above example first the value of “a” is assign to the variable ” b”, then
decrement the value. So the value of “b” variable is “10”.

Prepared by [Link]
1.2.2PRE-FIX DECREMENT OPERATOR:
“-” Symbol is used to represent the pre-fix decrement operator. This symbol
is used after the operand. In this operator, value is decremented first and then
decremented value is used in expression.
EX:int a,b;
a=10;
b=--a;
In the above example first the value of “a” is decrement then assign to the
variable “b”. So the value of b variable is “9”.
1. BINARY OPERATOR:
In which we use two operand is called Binary operator. Java supports many types of Binary operators:
* Assignment operator
* Arithmetic operator
* Logical operator
* Comparison operator
1.1 ASSIGNMENT OPERATOR:
This operator is used to assign the value. This symbol “=“ is used to assign the value .
EX: int a=12;
1.2 ARITHMETIC OPERATOR:
This operator is used to perform mathematical operand. Arithmetic operator are:

Operators Description Use

1. Additional operator Used to add the value of two a+b


(“+”) : operand.

2. Subtract operator (“- Used to subtract the value of a-b


“) : two operand.

3. Multiply operator Used to multiply the value of a*b


(“*”) : two operand.

4. Division operator Used to divide the value of two a/b


(“/”) : operand.

5. Modulus Used returns the remainder of a a%b


operator(“%”) : division operation.

Prepared by [Link]
LOGICAL OPERATOR:
The logical operator ||(conditional-OR),&&(conditional-AND),!(conditional-NOT)
operates on boolean expressions, here’s how they work:

LOGICAL NOT OPERATOR:


 Logical NOT operator is used to reverse the logical state of its operand. If
a condition is true then
 logical NOT operator will make false. If a condition is false then Logical
NOT operator will make true.
 Then NOT operator is probably the easiest to understand. It is simply the
opposite of what the condition says.
EX: boolean a=true; if(!a)
[Link](“u r win”); else
[Link](“u r not win”);
 In above example “if not true” is asking if the variable “a” variable is not
true, otherwise known as false.
 If “a” variable is false, java will displays ”u r win” “a” variable is not true
, so that code will not execute, then the else part is execute shown in output.

RELATIONAL OPERATOR:
 This operator is used to compare the two values, so this operator is also known as “comparison
operator”
 Conditional symbols and their meanings for comparison operator are below:

Prepared by [Link]
TERNARY OPERATOR:
In ternary operator use three operands. It is also called Conditional assignment
statement because the value assigned to a variable depends upon a logical
expression.
SYNTAX:
variable=(test expression)?Expression 1: Expression 2
EX
c=(a>b)?a:b
c= (a>b) ? a:b
Test condition ? Expression1 : Expression2;
BITWISE OPERATORS:
Java provides 4 bitwise and 3 bit shift operators to perform bit operations.
* | Bitwise OR
* & Bitwise AND
* - Bitwise Complement
* ^ Bitwise XOR
* << Left shift
* >> Right shift
* >>> Unsigned Right Shift
Bitwise and bit shift operators are used on integral types (byte, short, int
and long) to perform bit-level operations.

BITWISE OR:
Bitwise OR is a binary operator(operates on two operands). It’s denoted by |. The
| operator compares corresponding bits of two operands. If their of the bits is 1. If
not, it gives 0.
BITWISE AND :
Bitwise AND is a binary operator (operates on two operands). It’s denoted by &.
The & operator compares corresponding bits of two operands. If both bits are
BITWISE COMPLIMENT :
Bitwise compliment is an unary operator(works on only one operand). It is denoted by
~. The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.

Prepared by [Link]
Control Statements
The control statements are used to control the flow of execution in a program they help in making decisions,
repeating tasks, and jumping to specific parts of the program
The control statements in Java are categorized into 3 categories
1) Selection Statements/Decision statement
2) Iteration Statements/Looping Statement
3) Jump Statements/Branching statement
1) Selection Statements
A selection Statement is the part of Control Statement that allows the program to select and execute a
specific block of code based on a given condition it helps in making decisions during program
a) if statement
b) if-else statement
c) nested if-else statement
d) else if
e) switch

if statements :-

 The if-statement is the simplest decision-making statement it execute a block of code only if a given
condition is true
 if the expression is true, the statement block will be executed, otherwise the
statement block will be skipped to the statement-x.

Syntax:-
if<expression>
{
Statement-block;
}
Statement-x
Flow Diagram:-

false
condition

True

Statement-block

Statement block-X
Example:
import [Link].*;

Prepared by [Link]
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link](“Enter a Number”);
int n=[Link]();
if(n%2==0)
{
[Link](“even number”);
}
[Link](“Statement-X”);
}
}

if else statement:-
 An if else statement is a decision making control statement in java that executes one block of code
when the condition is true, and another block of code when the condition is false
 if the test expression is true, then the true-block statements immediately following the if statement
are executed. Otherwise, the false-block statements are executed

Syntax:-
if ( condition )
{
// true action
}
else
{
// false action
}

false
condition

True

True block
False block

Statement -X

Prepared by [Link]
Example:
import [Link].*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link](“Enter a Number”);
int n=[Link]();
if(n%2==0)
{
[Link](“even number”);
}
else
{
[Link](“odd number”);
}
}

Nested if statement :-

 A nested if statement is an if statement placed inside another if statement


 It is used when we need to check multiple conditions one inside another
 The inner if statement executed only if the outer if condition true

Syntax:-

if (condition1) {

// statements

if (condition2) {

// statements

Prepared by [Link]
Flow diagram:-

Example:-
public class NestedIfExample {
public static void main(String[] args) {

int age = 20;


String nationality = "Indian";

if (age >= 18) { // Outer if


[Link]("Age verified.");

if ([Link]("Indian")) { // Inner if
[Link]("You are eligible to vote in India.");
} else {
[Link]("You are not an Indian citizen.");
}

} else {
[Link]("You must be at least 18 years old to vote.");
}
}
}

Prepared by [Link]
else if -statement:-
 The else if statement is used to check multiple conditions one by one
 It is used when more than one condition needs to be tested, and only one block of code
Should execute based on the first true condition
Syntax:-
if (condition1) {
// executes when condition1 is true
} else if (condition2) {
// executes when condition2 is true and condition1 is false
} else if (condition3) {
// executes when condition3 is true and previous conditions are false
} else {
// executes when all above conditions are false
}

Flow diagram:-

Prepared by [Link]
Example:-
public class ElseIfExample {
public static void main(String[] args) {

int marks = 72;

if (marks >= 90) {


[Link]("Grade: A");
}
else if (marks >= 75) {
[Link]("Grade: B");
}
else if (marks >= 60) {
[Link]("Grade: C");
}
else if (marks >= 45) {
[Link]("Grade: D");
}
else {
[Link]("Grade: Fail");
}
}
}
Switch statement:-
The switch statement in java is a multi-way branch statement in simple words the java
switch statement executes one statement from multiple conditions
Some Important Rules for Java Switch Statements
 Case values must be constants or literals and of the same type as the switch
expression.
 Duplicate case values are not allowed.

Syntax:-
switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional
......
default: //code to be executed if all cases are not matched;
}

Prepared by [Link]
Flow diagram:-

Example:
int choice=2;
switch(choice)
{
case 1: [Link](“this is case 1”);
break
case 2: [Link](“this is case 2”);
break;
case 3: [Link](“this is case 3”);
break;
default: [Link](“this is default case”);
}
Output: this is case 2

Prepared by [Link]
LOOPING/ITERATION STATEMENT:-
Looping means executing a block of statements repeatedly until a specific condition become false
It allows you to perform repeated tasks without writing the some code multiple times
 For loop
 While
 Do while

1. For loop:-
The for loop is used when we know the number of iterations (we know how many times we
want to repeat a task). The for statement includes the initialization, condition, and
increment/decrement in one line.

 Initialization condition: Here, we initialize the variable in use. It marks the start
of a for loop

Testing Condition: It is used for testing the exit condition for a loop
 Statement execution: Once the condition is evaluated to true, the statements in
the loop body are executed.
 Increment/ Decrement: It is used for updating the variable for next iteration.\

FLOW DIAGRAM:-

Example:-
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++) {
[Link](i + " ");
}
}
}

Prepared by [Link]
While Loop:-
 The Java while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop
 The condition is checked before executing the loop
 If the condition is true, the loop runs
 If the condition is false, the loop stops
Syntax:-
while(condition)
{
//code to be executed
}
Example:-
class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
[Link](i+” “);
i++;
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
do-while Loop:-
 The Java do-while loop is used to iterate a part of the program several times.
 if the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use do-while loop
 The Java do-while loop is executed at least once because condition is checked
after
loop body.
Syntax:-

do
{
//code to be executed
}
while(condition);

Example:-

Prepared by [Link]
class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
[Link](i);
i++;
}
while(i<=10);
}
}
Output:

1 2 3 4 5 6 7 8 9 10

Jumping Statements:-

jump statements are used to alter the normal flow of program execution
when certain conditions are met. They can be used to terminate a loop, skip
an iteration, or exit from a method or block of code.

 Continue Statement
 Break statement

Continue Statement:-
 The continue statement in Java is used inside loops (for, while, do-
while).
 it skips the current iteration of the loop and jumps to the next
iteration immediately.
 This is used for nested loops to skip to a specific outer loop iteration.

Syntax:-
continue;

Example:-

Prepared by [Link]
class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
continue; // skip printing 5
}
[Link](i+” “);
}
}
}
Output:-

1 2 3 4 6 7 8 9 10

5 is skipped because the continue statement is executed

Keywords:-
 keywords are the reserved words that have some predefined meanings and are
used by the Java compiler for some internal process or represent some
predefined actions.
 These words cannot be used as identifiers such as variable names, method
names, class names, or object names.

Important Points:-

 The keywords const and goto are reserved, even though they are not
currently used in Java.
 true, false, and null look like keywords, but in actuality they are literals.
However, they still can't be used as identifiers in a program.
 In Java, keywords are case-sensitive, and writing Java keywords in upper
case (like IF instead of if) will throw an error.
 there are 51 keywords, but 2 of them are not used which are-goto and const.

Prepared by [Link]
 Only 49 keywords are used in Java. All of them have different purposes and
meanings.

Constants:-
constant is a named constant value defined once and used throughout a
program. Symbolic constants are declared using the final keyword.

 Which indicates that the value cannot be changed once it is


initialized.
 The naming convention for symbolic constants is to use all capital
letters with underscores separating words.

Syntax of Symbolic Constants:-


final data_type CONSTANT_NAME = value;

 final: The final keyword indicates that the value of the constant
cannot be changed once it is initialized.
 data_type: The data type of the constant such as int, double, boolean,
or String.
 CONSTANT_NAME: The name of the constant which should be
written in all capital letters with underscores separating words.
 value: The initial value of the constant must be of the same data type
as the constant

Prepared by [Link]
FUNCTIONS:-

 A function is a block of code which only perform certain actions


 Methods are used to perform certain actions, and they are also known
as functions.
Two Types
[Link] defined
[Link] defined

Create a Method
 A method must be declared within a class.
 It is defined with the name of the method, followed by parentheses
().
 Java provides some pre-defined methods, such as
 [Link](), but you can also create your own methods to
perform certain actions
 A method can also be called multiple times

Example

Create a method inside Main:


public class Main {
static void myMethod() {
// code to be executed
}
}

Prepared by [Link]
UNIT–I: JAVA BASICS
Short Questions (2 Marks )
1. What is Java? Mention any two features.
2. Define JVM, JRE, and JDK.
3. What is a variable? Give an example.
4. Define constants in Java.
5. List the primitive data types in Java.
6. What are keywords? Give any four examples.
7. What are operators? Name any two types.
8. What is type casting?
9. Define control statements.
10. Write the syntax of a for loop.
11. What is the difference between break and continue?
12. What is a function/method in Java?
Long Questions (10 Marks / Essay)
1. Explain the different data types in Java with examples.
2. Describe operators in Java. Explain any five operators with examples.
3. Explain control statements in Java with suitable examples.
4. Discuss loop statements with syntax and examples.
5. Define methods in Java. Explain method declaration, calling, and return types with example

Prepared by [Link]
Prepared by [Link]
Prepared by [Link]
Prepared by [Link]
Prepared by [Link]
Prepared by [Link]

You might also like