Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

3 Java Fundamentals

The document provides an overview of basic Java concepts, including primitive data types, operators, control structures, and user input handling. It covers the eight primitive data types in Java, their ranges, and how type conversion and casting work. Additionally, it explains how to use the Scanner class for user input and introduces various operators and control statements in Java.

Uploaded by

gohilsrushti64
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

3 Java Fundamentals

The document provides an overview of basic Java concepts, including primitive data types, operators, control structures, and user input handling. It covers the eight primitive data types in Java, their ranges, and how type conversion and casting work. Additionally, it explains how to use the Scanner class for user input and introduces various operators and control statements in Java.

Uploaded by

gohilsrushti64
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Java Basic Concepts

Mr. M.R.
Solanki
Sr. Lecturer, Information Technology,
manish_ratilal2002@yahoo.com
SBMP
Learning Outcomes

Students will be able to:


• Examine the basic syntax and
semantics of Java language i.e. data
types, literals, variables, keywords,
etc.
• Explore various operators supported in
Java.
• Appraise themselves about conditional
and looping statements existing in
Java.
• Take user inputs through key board.
Primitive Data Types
Primitive Data Types
 Java defines eight primitive types of data:
byte, short, int, long, char, float, double, and
boolean

 These primitive types(simple types) can be


put in four groups:

1. Integers :includes byte, short, int, and


long, which are for whole-valued signed
numbers

2. Floating-point numbers: includes float and


double, which represent numbers with
fractional precision
Primitive Data Types
3. Characters :includes char, which
represents symbols in the character set i.e.
letters, numbers and special characters.

4. Boolean: includes boolean, which is a


special type for representing true/false
values
Primitive Data Types Range

In Java only signed types are available. ( No
unsigned types like C and C++)
Primitive Data Types: Character
 In Java, the data type used to store
characters is char
 In C/C++, char is 8 bits wide. Instead, Java
uses 16-bits Unicode to represent char.
 Unicode defines a fully international
character set that can represent all of the
characters found in all human languages.
 It is a unification of dozens of character sets,
such as Latin, Greek, Arabic, Cyrillic, Hebrew,
Katakana, Hangul, and many more.
 Unicode is of 16-bits so the range of a char is
0 to 65,535
 There are no negative chars (like C/C++)
Primitive Data Types: Character
 The standard set of characters known as
ASCII still ranges from 0 to 127 and the
extended 8-bit character set, ISO-Latin-1,
ranges from 0 to 255.
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.print(ch1 + " " + ch2);
}}
 This program displays the following
output:
ch1 and ch2: X Y
++/-- operator with char


 We can not write the following statement for
characters:
char ch=‘A’;
ch=ch+1; //Error
 Whereas, ch++ or ch+=1 is allowed
Primitive Data Types: boolean
 Java has a primitive type boolean for logical
values.

 It can have only one of two possible values,


true or false.

 This is the type returned by all relational


operators.

int a=5,b=7;
System.out.print(a>b); // false # in
C/C++ =>0
System.out.print(a<b); // true # in C/C+
+ =>1
System.out.print(a!=b); // true

The result of the condition used
conditional and looping statements
in
is
boolean only .
 If(num%2==0)
 while(i<=n)
{
// stetements
}
Primitive Data Types: boolean
Primitive Data Types: boolean

Applications :
 Used by Java internally as a result of all relational
operators

 Can be used for flag variables having 2 possibilities


i.e. 1 (true) or 0 (false)

Examples: To decide a number is prime or not,


searching a number from an array.
Basic Building Blocks

 Literals ( Constants)
 integer i.e. 123, -23, 10101, etc.
 floating point: 2.546, 0.00023, etc.
Character : ‘A’, ‘#’, etc.
String: “Hello” , “Java” ,etc.
 Variables : Rules are same as C/C++
(except $ sign is allowed in Java)
 Keywords : Reserved words i.e. class,
float, if, for, etc.
Java Keywords

abstract else interface switch


assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
Type Conversion
Type Conversion and Casting
Java’s Automatic Conversions: (Implicit Type
Casting)

 When one type of data is assigned to another


type of variable, an automatic type conversion
will take place if the following two conditions are
met:

1. The two types are compatible.


2. The destination type is larger than the source
type.
Type Conversion and Casting
Type Compatibility:
 The numeric types, including integer and
floating-point types, are compatible with each
other
Examples:
I. byte type data can be assigned to int, short and
long
II. short type data can be assigned to int and long
III. int type data can be assigned to long and float
IV. float type data can be assigned to double

 No automatic conversions from the numeric types


to char or boolean.

 char and boolean are not compatible with each


other.
Type Conversion and Casting
Type Conversion and Casting
Type Conversion and Casting
Casting Incompatible Types:(Explicit Type Casting)

 What if you want to assign an int value to a byte


variable?
 This conversion will not be performed
automatically, because a byte is smaller than an int
(violation of rule 2)

 This kind of conversion is sometimes called a


narrowing conversion, since you are explicitly
making the value narrower so that it can fit into
the target type.
Type Conversion and Casting
Casting Incompatible Types:(Explicit Type Casting)
 To create a conversion between two
incompatible types, you must use a cast.

 A cast is simply an explicit type conversion.


(target-type) value

Here, target-type = type to which value will be


converted

Example: int a=23;


byte b;
b= (byte) a;
Type Conversion and Casting
Casting Incompatible Types:
Type Conversion and Casting
Casting Incompatible Types:
How int to byte conversion would take place?
Answer#1:
 byte requires 8-bits (1 byte) storage.
 byte can store : -128 to +127 values only.

While assigning int value beyond the range of target


type i.e. byte:
result =value%2n

n= no. of bits required for destination data type

result=257%256 (28 = 256)


=1
Type Conversion and Casting
Casting Incompatible Types:
How int to byte conversion would take place?
Answer#2:
byte requires 8-bits (1 byte) storage.
byte can store : -128 to +127 values only.

Represent 257 into binary form:

256 128 64 32 16 8 4 2 1
1 0 0 0 0 0 0 0 1

As byte can store only 8-bits the result will


be 1
Type Conversion and Casting
Casting Incompatible Types:
Expressions

Java performs an automatic type conversion


when storing a literal integer constant into
variables of type byte, short, long, or char
i.e. byte b = 125;
int i= 25678;
char ch=65535;
Expressions
 In an expression, an intermediate value will
sometimes exceed the range of either operands
For example(1), examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
 The result of the intermediate term a * b
(=2000) easily exceeds the range of either of its
byte operands.
 To handle this kind of problem, Java
automatically promotes each byte, short, or char
operand to int when evaluating an expression.
Type Conversion and Casting
Automatic Type Promotion in Expressions
Example2:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to
a byte!

Solution:
byte b = 50;
b = (byte)(b * 2);
In Java


 Integral literals are always treated as int while
evaluating expressions.
 Floating point literals are always treated as
double.
Floating point literal Error
casting
Operators
Operators
Arithmetic Operators:

Note: Modulus operator can be applied to floating-point


types as well as integer types.
Operators

Increment/Decrement Operator:

 The ++ and the – – are Java’s increment


and decrement operators
 They are of two types prefix and postfix
(same as C/C++)
Operators
Relational Operators:
Operators
Logical(boolean) Operators:
Operators
Short Circuit Logical(boolean) Operators:

The OR operator results in true when A is true, no matter


what B is.

The AND operator results in false when A is false, no


matter what B is.
Operators
Short Circuit Logical(boolean) Operators:

If you use the || and && forms, rather than the | and &
forms of these operators:

Java will not bother to evaluate the right hand operand when
the outcome of the expression can be determined by the left
operand alone.
Operators
Short Circuit Logical(boolean) Operators:
Example1: if(a>b && a<c)
Example2: if (denom != 0 && num / denom > 10)

Since the short-circuit form of && is used, there is no risk of


causing a run-time exception when denom is zero.

 If we use conventional logical and operator, both the


conditions will be evaluated.

if(a>b & a<c)


In Java


 Logical operator = &, |
 Short circuit logical operator = &&, ||
Operators
Bitwise Operators:
Operators
Bitwise Operators(~) : Complements every bit of
the value i.e. 0 to 1 and 1 to 0 (NOT gate in Digital
Electronics)

Example: byte a=5;


System.out.println(~a);
Explanation:
Note: As a is of type byte, we have to
consider 1 byte data
Represent 5 into binary = 0000 0101
Bitwise NOT (~) = 1111 1010
The msb (most significant bit =1 , the number
is -Ve)
Now take 2’s complement of the number= 1’s
Comp. +1
= 0000 0101
+ 1
Operators
Bitwise Operators (&) : Bitwise AND operation (AND
gate in Digital Electronics)

Example: byte a=5,b=4;


System.out.println(a&b);

Explanation:
Note: As a is of type byte, we have to
consider 1 byte data
Represent 5 into binary = 0000 0101
Represent 4 into binary = 0000 0100

(Result of & )= 0000 0100


Operators
Bitwise Operators: << (shift left)
Syntax: var/val << n;
Here, n= number of times rotations
Example: byte a=5;
System.out.println(a<<1);
Explanation:
Note: As a is of type byte, we have to
consider 1 byte data
Represent 5 into binary
0
= 0 0 0 1 0 1
0
a<<1 =

0 0 0 0 0 1 0 1 0

Most significant bit is discarded and empty space created at Least


significant bit is filled with 0
Operators
Bitwise Operators: >>> (shift right zero fill)
Syntax: var/val << n;
Here, n= number of times rotations
Example: byte a=5;
System.out.println(a>>>1);
Explanation:
Note: As a is of type byte, we have to
consider 1 byte data
Represent 5 into binary
0
=0 0 0 0 1 0 1
a>>>1 =

0 0 0 0 0 0 1 0 1

Least significant bit will be discarded and empty space is filled with 0
Operators
Bitwise Operators: >> (shift right)
Most Significant bit of previous value is copied to
the vacant place. Used to preserve the sign of
previous value.
Example: byte a=-14;
System.out.println(a>>1);
Explanation:
Note: As a is of type byte, we have to
consider 1 byte data 1 1 1 1 0 0 1 0
Represent 5 into binary =
a>>1 =

1 1 1 1 1 0 0 1 0

Least significant bit will be discarded and empty space is filled with
the msb of the previous value.

 While performing <<, value becomes double.
 While performing >>, the value becomes
half.
Operators
Operators
Operators
Operator Precedence:
Control Structures
Control Statements
Conditional Statements:
Simple if
If …..else
nested if
else if ladder
 switch…… case

Note: We can use String in switch…..case as


opposed to C/C++

Iterative Statements:
 while loop
do.....while loop
for loop
Taking user input using
Scanner class
Scanner class
 In Java, there is no function i.e. scanf() or cin as
available in C and C++ respectively.
 One of the ways to take user input in Java is
using Scanner class.

Steps to use Scanner class:


1. Import package java.util.Scanner or java.util.*

2. Create the object of Scanner class:

Scanner sc = new Scanner(System.in);

3. Invoke the appropriate method(function):

type a = sc.nextType();
Scanner class Methods

Method Purpose
nextByte(), nextShort(), nextInt() To read byte, short, int and long
and nextLong() data respectively
nextFloat() and nextDouble() To read float and double data
respectively

nextBoolean() To read boolean value


next() To read string without space
nextLine() To read string with space

Note: There is no method available to read char data



 Use sc.next().charAt(0) method to read
character data from the keyboard.
user input
user input
Working with Strings
 String is a class in Java.

Syntax: String str_var;


Example: String str;

 Initializing a string:

String str=“Hello”;
System.out.println(str);

 Taking string as a user input from keyboard :

String str;
System.out.println(“Enter the String”);
str = sc.nextLine();
board
Keyboard

 If we read a string after reading integer type
data then provide one dummy statement i.e.
sc.nextLine()
Thanks!
Any questions?
You can find me at:
manish_ratilal2002@yahoo.com
Credits
 Java, The Complete Reference, TMH
 Tutorials and Forums available on Inte
rnet

You might also like