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

Ss Java Basics

Uploaded by

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

Ss Java Basics

Uploaded by

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

JAVA

PROGRAMMING
Birth of Java

•Assembly level language created by the assembler can be executed only the same
computer which has same OS and CPU in which program was developed and this
makes all S/W developed using this language dependent on the platform.

•SunMicroSystems software development company had the vision of developing a


programming language which was completely platform independent.

•In 1990 a team of Researchers led by James Gosling starts research to develop a
platform independent programming language.

•In the year 1995 official version of JAVA was first released to the market
Birth of Java
JDK(Java Development Kit)

-------
----
-----
Javac Bytecode JVM
Java compiler Java Virtual
----- Machine
---

Check the syntax of the Demo.class •Read a line of code.


Demo.java program. •Understand a line of code
Create java program using ifsyntax mistake •Execute a line of code
Code Editors : Sublime throw Compile Time Error If code is not
text, Notepad++, Editplus else
create convert java code to
understandable
etc.. throw Run Time Error
IDE: NetBeans, Eclipse , bytecode and save it .class
file. or Exception
IntelliJ , Jcreator else
execute the code
Installation of JDK and Sublime Text
Learning Objectives

•How to set-up JDK for java development.


•Learn how to compile and execute java
programs
•Understanding structure of java program.
Keywords, Identifiers and Variables
Keywords

•Keywords are those reserved words which will have a pre-


defined
meaning defined in the programming language.

•Keyword should be written only in lowercase.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/
_keywords.html
Identifiers
•Identifiers are the names given for an entity in a program
•In java identifiers are used to identify Class, Methods and Variables.

RULES OF IDENTIFIERS.

✓ Identifiers can be alpha-numeric.


✓ Identifiers should not start with numeric.
✓ $ and _ are the only 2 special characters that can be used with Identifiers.
✓ Identifiers can start with $ or _
✓ Single _ is an invalid identifier in java.
✓ Keywords can not be used as identifiers.
Variables

•A named memory location which is used to store values for the program is
called as variable.

To use a variable we have to follow 3 steps

✓ Declaration

✓ Initialization

✓ Utilization
•Declaration is a statement which written to specify
the type of data to be stored in the given variable.
syntax : datatype varName; D
DataType Capacity Default value
byte 8-bits or 1-byte 0
short 16-bits or 2-bytes 0
int 32-bits or 4-bytes 0
long 64-bits or 8-bytes 0l
float 32-bits or 4-bytes 0.0f
double 64-bits or 8-bytes 0.0
char 16-bits or 2-bytes Space
Boolean 8-bits or 1-byte false
Initialization
• Initialization : It is a statement which is written to store the data
within a variable using assignment operator(=).
syntax : varName= value;

Utilization
• Utilization : It is one or group of statements which is written to use
the value in the variable to perform the operation.
Initialization
• Initialization : It is a statement which is written to store the data
within a variable using assignment operator(=).
syntax : varName= value;

Utilization
• Utilization : It is one or group of statements which is written to use
the value in the variable to perform the operation.
DATA TYPES
DATA TYPES

There are two data types available in Java:

Primitive Data Types

Non-Primitive Data Types (Reference Types)


DATA TYPES

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a key word. Let us now look into
detail about the eight primitive data types.

Primitive Data Types:


Non-primitive data types are created by the programmer and are not defined by
the programming language, except for String.
Ex. of non-primitive types are Strings, Arrays, Classes, Interface, etc.
byte: Byte data type is a 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in
place of integers, since a byte is four times smaller than an int.
Example : byte a = 100 , byte b = -50

public class IntExample1


{
public static void main(String[] args)
{
byte age = 100;
System.out.println("num1: "+
age);
}
}
short: Short data type is a 16-bit signed two's complement
integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767(inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data
type. A short is 2 times smaller than an int.
Default value is 0.
Example : short s= 10000 , short r = -20000

public class IntExample1


{
public static void main(String[] args)
{
short salary = 30000;
System.out.println("num1: "+ salary);
}
}
int: Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless
there is a concern about memory.
The default value is 0.
Example : int a = 100000, int b = -200000

public class IntExample1


{
public static void main(String[] args)
{
int num1=10;
System.out.println("num1: "+num1);
}
}
long: Long data type is a 64-bit signed two's complement
integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example : int a = 100000L, int b = -200000L

public class IntExample1


{
public static void main(String[] args)
{
long num1=10002250;
System.out.println("num1: "+num1);
}
}
float: Float data type is a single-precision 32-bit IEEE 754
floating point.
Float is mainly used to save memory in large arrays of floating
point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example : float f1 = 234.5f

public class IntExample1


{
public static void main(String[] args)
{
float num1=10525.2515;
System.out.println("num1: "+num1);
}
}
double: double data type is a double-precision 64-bit IEEE
754 floating point.
This data type is generally used as the default data type for decimal
values. generally the default choice.
Double data type should never be used for precise values such as
currency.
Default value is 0.0d.
Example : double d1 = 123.4

public class IntExample1


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

double num1=10250250.115511254515;
System.out.println("num1: "+num1);
}
}
boolean: boolean data type represents one bit of information.
There are only two possible values : true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example : boolean one = true

public class IntExample1


{
public static void main(String[] args)
{
boolean num1;
System.out.println("num1: "+num1);
}
}
char: char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example . char letterA ='A'

public class IntExample1


{
public static void main(String[] args)
{
char num1 = ‘A’;
System.out.println("num1: "+num1);
}
}
Operators
•Operator performs operations on operands and produce results.

Types of operators

✓ Logical Operators
&& || ^
✓ Increment and Decrement Operators
++ --
✓ Arithmetic Operators
+ -* / %
✓ Comparison Operators or Relational Operators
< > == != <= >=
✓ Logical Operators
&& || ^
✓ Bitwise Operators
&|^
Priority Operator Operation
1 () [] -> . :: Function call, scope, array/member access
2 ! ~ -+ * & (most) unary operators, sizeof and type casts(right to left)
sizeof type cast++ --
3 * / % MOD Multiplication, division, modulo
4 +- Addition and subtraction
5 << >> Bitwise shift left and right
6 < <= > >= Comparisons: less-than and greater-than
7 == != Comparisons: equal and not equal
8 & Bitwise AND
9 ^ Bitwise exclusive OR (XOR)
10 | Bitwise inclusive (normal) OR
11 && Logical AND
12 || Logical OR
13 ?: Conditional expression (ternary)
14 =, +=, -=, *=, /=, %=, Assignment operators (right to left)
&=, |=, ^=, <<=, >>=
15 , Comma operator
Arithmetic Operators

Arithmetic operators are used to perform common mathematical


operations.

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable ++x
by 1
-- Decrement Decreases the value of a variable --x
by 1
Arithmetic Operators Example
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x + y);
System.out.println(x - y);
System.out.println(x * y);
System.out.println(x / y);
System.out.println(x % y);
++x;
System.out.println(x);
--x;
System.out.println(x);
}
}
Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10; x += 5;
public class Main {
public static void main(String[] args) {
int x = 5;
A list of all assignment operators: System.out.println(x);
x += 3;
System.out.println(x);
Operator Example Same As x -= 3;
= x=5 x=5 System.out.println(x);
+= x += 3 x=x+3 x *= 3;
System.out.println(x);
-= x -= 3 x=x-3
x /= 3;
*= x *= 3 x=x*3
System.out.println(x);
/= x /= 3 x=x/3 x %= 3;
%= x %= 3 x=x%3 System.out.println(x);
}
}
Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

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

These values are known as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than
3:

Example
int x = 5; int y = 3; System.out.println(x > y); // returns true, because
5 is higher than 3
A list of all Comparison operators:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // returns false because 5 is not equal to 3

System.out.println(x != y); // returns true because 5 is not equal to 3

System.out.println(x > y); // returns true because 5 is greater than 3

System.out.println(x < y); // returns false because 5 is not less than 3

System.out.println(x >= y); // returns true because 5 is greater, or equal, to 3

System.out.println(x <= y); // returns false because 5 is neither less than or equal
to 3
}
}
Logical Operators
You can also test for true or false values with logical operators.

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

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is x < 5 || x < 4
true
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true
^ Logical XOR operator will return FALSE if and only if x<5^x<4
the result of both the Boolean
condition’s result is FALSE or TRUE and in
all other cases it returns TRUE
Logical AND &&

 Logical AND &&operators will return TRUE if and only if


the result of both the Boolean condition’s result is TRUE
and in all other cases it returns FALSE

 TRUTH table for LOGICAL AND (&&)

CONDITION1 CONDITION2 RESULT


TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Logical OR ||

 Logical OR ||operator will return FALSE if and only if the result of both the
Boolean condition’s result is FALSE and in all other cases it returns TRUE

 TRUTH table for LOGICAL OR (||)

CONDITION1 CONDITION2 RESULT


TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Logical XOR ^

 Logical XOR ^operator will return FALSE if and only if the result of both the
Boolean condition’s result is FALSE or TRUE and in all other cases it returns TRUE

 TRUTH table for Logical XOR ^

CONDITION1 CONDITION2 RESULT


TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
public class Main {
public static void main(String[] args) {
int x = 5;

System.out.println(x > 3 && x < 10);


// returns true because 5 is greater than 3 AND 5 is less than 10

System.out.println(x > 3 || x < 4);


// returns true because one of the conditions are true (5 is greater than
3, but 5 is not less than 4)

System.out.println(!(x > 3 && x < 10));


// returns false because ! (not) is used to reverse the result

System.out.println(x > 2 ^ x < 4);


// returns false because ^ (XOR) both the condition are true.
}
}
Bitwise Operator

 Bitwise operator will perform bitwise operations on every bit of given value and
produce results as 0 or 1

25
2|12-1
2|6-0 0011001 0011001 0011001
2|3-0 1100100(&) 1100100(|) 1100100(^)
2|1-1
Result : 11001 -------------- -------------- --------------
100 0000000 1111101 1111101
2|50-0 0*2^6+ 0*2^5+
2|25-0 0*2^4+ 0*2^3+
2|12-1 0*2^2+ 0*2^1+
2|6-0 0*2^0 =
2|3-0 RESULT : 0
2|1-1
Result : 1100100
Concatenation Operator

• concatenation oprt(+) : Is used to join a String value with any other


data.
• Between a string and any other type if you use + oprt it will join the
string and given
value creating a new String.
• Ex : "hello"+"world“
• “hello"+10
Method
s
Methods

• Methods are named blocks of codes which will perform a specific task.

Syntax : access specifier access modifiers return type name(argument list)


{
stmt..
stmt..
return;
}

•Methods are used to eliminate duplicate lines of code in the program.

•Access modifier : static.

•Access specifier : public, protected, pkg-level, private.

•Return type : depends on the data type of the value returned from the method
• A method which is called by another method is known as called method.
• A method which is calling another method is known as calling method.
• If methods returns any value then the returned value should be
stored in a variable matching the return type of the method.
• return statement is used to transfer the control and the values from
called method to calling method.
• If methods do not return any value then its return type should be
declared as void.
• If return type of method is void then, programmer can skip writing the
return statement.
FLOW CONTROL STATEMENTS
Flow control statements

•Flow control statements are used to control the execution flow


of the program at the runtime.

•Flow control statements are of 2 types


•Decision Making Statements
•Looping Statements
Decision Making Statements

•Decision Making Statements are used to execute one or group of


statements based on a Boolean condition.

•Boolean cond / Boolean exp : a Comparison statement written using


Comparison
opts and logical opts is called Boolean exp/cond.
•Types of Decision making statements are

•IF
•If-else
•if-else-if
•Switch-case

Decision Making Statements


Statement

•it is a type of decision making where one or group of statements


written within the if body will be executed if and only if result of
Boolean condition
is true .
if -statement
Syntax : if(Boolean cond)
{
stmt..
stmt.
}
if -else statement
• It is a type of decision making statements where statements of if
body are executed if result of boolean condition is TRUE else the
statements of else body are executed .
if -else statement
Syntax : if(Boolean cond)
{
stmt..
stmt.
}
else
{
stmt
stmt
}
In this example, we have a variable number set to 10. The if-else statement checks the value of
number against three conditions:
If number is greater than 0, it prints "The number is positive."
If number is less than 0, it prints "The number is negative."
If neither of the above conditions is true (i.e., number is equal to 0), it prints "The number is zero."

public class IfElseExample {


public static void main(String[] args) {
int number = 10;

if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) { Since the value of number is 10, it
System.out.println("The number is negative."); satisfies the first condition, and
} else { the output will be:
System.out.println("The number is zero.");
The number is positive.
}
}
}
if –else -if statement

•It is a type of decision making statements which is used to whenever there are
multiple Boolean conditions to be evaluated to execute different set of
statements.
Syntax : if(Boolean cond1)
{
stmt..
}
else if(Boolean cond2)
{
stmt
}
else
{
stmt
}
switch case -statement

• It is a type of decision making statements which is used whenever there are


only equals conditions to be evaluated to execute different set of statements.
switch case -statement
Syntax : switch(choice)
{
case choice 1 : stmts
break;
case choice 2 : stmts
break
default : stmts
}
Looping Statements

•Looping Statements are used to execute one or


multiple Statements repeatedly.

•In java there are 4 looping statements


•For loop
•While loop
•do-while loop
•for-each loop
For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:

for (statement 1; statement 2; statement 3) { // code block to


be executed }

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

for (int i = 0; i < 5; i++)


{
System.out.println(i);
}
Nested for Loops
It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

// Outer loop OUTPUT


for (int i = 1; i <= 2; i++)
{ Outer: 1
System.out.println("Outer: " + i); // Executes 2 times Inner: 1
// Inner loop Inner: 2
for (int j = 1; j <= 3; j++) Inner: 3
{ Outer: 2
System.out.println(" Inner: " + j); // Executes 6 times Inner: 1
(2 * 3) Inner: 2
} Inner: 3
}
While Loop

The while loop loops through a block of code as long as a specified


condition is true:
Syntax
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again,
as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5)
{
System.out.println(i); i++;
}
Do/While Loop

The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
// code block to be executed
} while (condition);
for-each loop

The "for-each" loop is also known as the enhanced for loop or the "for-
each" loop. It allows you to iterate over elements in an array or any
object that implements the Iterable interface (e.g., List, Set, etc.).
The loop simplifies the process of iterating through a collection and
accessing its elements without dealing with indices explicitly.

The basic syntax of a "for-each" loop in Java is as


follows:

for (dataType variable : collection) {


// code block to be executed for each element
}
Here's an example of a "for-each" loop in Java:

Output
public class ForEachExample {
public static void main(String[] args) { 1
int[] numbers = {1, 2, 3, 4, 5}; 2
3
for (int number : numbers) {
System.out.println(number); 4
} 5
}
}

You might also like