Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 9 - Java Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Basic Concepts in Java

programming

Lecture 9
1
Outline
• Java input/output
• Variables
• Literals
• Type Casting
• Issues in Casting

2
Hello World!
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Hello World");
}
}

3
public class HelloWorld{
● Every java application begins with a class definition. In the program,
HelloWorld is the name of the class.
public static void main(String[] args) {
● Main method.
● Every application in Java must contain the main method.
● The Java compiler starts executing the code from the main method.
System.out.println("Hello World");
● It prints the text Hello, World! On console screen . The text inside the
quotation marks is called String in Java.
4
Java Output
● Display output to the user. There are 3 ways to display the output in Java.
System.out.println(“Hello World”);
System.out.print(“Hello World”);
System.out.printf(“Hello World”);

System - Java class


out - Field that accept output data
5
print vs println vs printf
print() -
It prints string inside the quotes.
println()
It prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
printf()

It provides string formatting (similar to printf in C/C++ programming).

6
Java Input
● Import Scanner class to get input from the user using Scanner class object.
import java.util.Scanner;
● create an object of the Scanner class.
Scanner in = new Scanner (System.in);
Scanner - Java class
in -User defined name for the scanner class object

● Take input from user to a variable.


int number = input.nextInt(); 7
Example
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
8
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
9
Data types and Default Values

Type Default Value Type Default Value

boolean false float 0.0f

byteint 0 double 0.0d

short 0 long 0L

int 0 object Reference null

char \u0000

10
public class Variables{
public static void main(String[] args) {
boolean flag = true;
int range = -4250000;
double number = -42.3;
float number = -42.3f;
char letter = '\u0051';

System.out.println(flag);
System.out.println(range);
System.out.println(number);
System.out.println(number);
System.out.println(letter);
} 11
String is a data type???

● Strings in Java are not primitive types (like int, char, etc).
● Instead, all strings are objects of a predefined class named String.

12
Variables
● A variable is a location in memory (storage area) to hold data.

Variable Declaration
dataType variableName;

Variable Initialization
dataType variableName = value;

13
Variable Naming Conventions
● Java is case sensitive.
● Start with either a letter or an underscore, _ or a dollar, $ sign.
● Do not start with numbers.
● Do not use whitespace.

14
Types of variables in Java

1. Instance Variables (Non-Static Fields)


• objects store their individual states
• their values are unique to each instance (object) of a class
• fields declared without the static keyword

2. Class Variables (Static Fields)


• fields declared with the static modifier
• there is exactly one copy of this variable

15
Variables contd..

3. Local Variables
• methods store its temporary state
• only visible to the methods
• not accessible from the rest of the class

16
Comments
● Comments are a portion of the program that are completely ignored by
Java compilers.
● They are mainly used to help programmers to understand the code.
● In Java, there are two types of comments:
○ single-line comment - Comment starts and ends in the same line. // symbol is
used.
○ multi-line comment - /* and */ symbols are used.

17
Single line comment
Ex: //This is a single line comment

Multi-line comment
Ex:
/*
This is a multi line comment
in Java
*/

18
Literals
• There are five basic types of literals in Java.
• Integer literals
• Floating point literals
• Character literals
• String literals
• Boolean literals

19
Integral literals
• Literal: Any constant value which can be assigned to the variable is called
literal/constant.

• For byte, short, int and long.

• Can be expressed using decimal, octal, or hexadecimal number systems.


• Decimal: Base 10, digits 0 - 9
• Octal: Base 8, digits 0 – 7 The prefix 0 indicates octal,
• Hexadecimal: Base 16, digits 0 - 9 & A – F whereas 0x indicates
hexadecimal
int decVal = 26; //The number 26,in decimal
int octVal = 032; //The number 26,in octal
int hexVal = 0x1a; //The number 26,in hexadecimal \

20
Floating point literals
• Can be expressed even using E or e (for scientific notation)

double d1 = 123.4;
double d2 = 1.234e2; //same value as d1, but
in scientific notation
float f1 = 123.4f;

• double is the default, not float, therefore, no special character is


appended.
21
Character Literals
• Any Unicode (UTF-16) character
• Use 'single quotes' for char literals
‘A’ ‘x’ ‘3’ ‘?’ ‘ ’

‘H’ is a char constant.


“H” is a String that happens to only contain a single character--
it is not a char.
This is a syntax error! The compiler will complain.

22
String Literals
• Any Unicode (UTF-16) character

• Use "double quotes" for String literals


“green” “Washington, D.C. 2005” “270-32-3456”

“$19.99” “THE CORRECT ANSWER IS” “2*(I+3)/j”

“ ” “”

Notice that the string “” is a null (empty) string.


23
Escape Sequences
Character Escape Sequence

Backspace \b
Tab \t
Nonprinting characters,
Vertical tab \v
New line (line feed) \n
Always begins with a
Form feed \f backward slash
Carriage return \r
Quotation quote (“) \”
Single quote (‘) \’
Backslash (\) \\
24
Example: Quotation quote (“) - \”

public class Test {


public static void main(String[] args)
{
System.out.println("Hi Student, welcome to \“LNBTI\".");
}
}

25
Boolean Literals
• A Boolean type must be assigned the value of the constants true or
false.
[Meaning, these exact lowercase words.]

• In contrast to C/C++, in Java 1 and 0 cannot stand in for true or false.

26
Scope of Variables
• Scope of a variable is the part of the program where the variable
is accessible.

variable n in Block2
is available only in Block2,
it goes out of the scope
at end of Block2

27
Scope of Variables contd….
Scopes of the variables args,
local2,local1 and local 3

Nesting - program blocks


within other program
blocks

28
Scope of Variables contd..
• The place of declaration decides the scope of the variable
• Instance & class variables declared inside a class
• Local variables declared & used inside methods

29
Symbolic Constants
• Named constant value defined once and used throughout a
program.

• Symbolic constants are declared using the final keyword.

• Benefits
• Easy to modify the program
• Easy to understand the program
30
Syntax of Symbolic Constants
final type symbolic-name =value;

• Ex: final int PASS MARK = 50;


final float PI = 3.14159;

31
Symbolic Constants contd..

• Similar to variable names BUT, written in CAPITALS

• After declaration assigning values again is ILLEGAL

• Attributes of a class can be declared as final

• Values must be provided at the time of declaration.

• Local variables cannot be declared as final

32
Mixing Data Types
float value1, value2, average;
value1 = 1.4f;
value2 = 2.6f;
average = (value1 + value2)/2;

• The above expression mixes float variables and is acceptable to the


compiler
• value1 + value2 is carried out as a float operation
• 2 is converted to a float value and the division carried out as a float
operation

33
Mixing Data Types contd..
float value1, value2, average;
value1 = 1.4f;
value2 = 2.6f;
average = (value1 + value2)/2.0;

• By default 2.0 is a double value


• Forces the division to be carried out as a double operation
• Hence the result is also of type double
• This may not be assigned to a float variable!

34
Automatic Type Conversion
• The rule for mixed-type expressions is:
“The type of each value is converted to type of the higher type in the
expression”

• This uses the hierarchy of types:


• double highest type
• float
• long
• int
• short
• byte lowest type

35
Assigning Values
• An assignment is unacceptable if the result of the expression on
the right-hand side is of a higher type to that of the variable on the
left-hand side.

int i=4;
float f = 4.0f;
f = i;
i = f;
f = 10.0;
f = 10;

36
Type Casting
• Occasionally we want to force a calculation to take place against the
implicit type conversion rules
• we use a cast operator to achieve this:

• Casting - process of explicitly converting one data type to another

Type variable1=(type) variable2;

Eg: int i = (int) f; //float cast to int


37
Issues in Type Casting
• Allows conversion from any higher type to a lower type

• Note that the casting does have some issues:


- When a floating-point number is converted to an integer the fractional
part is lost by truncating(shortening) it.

- The value of the cast number must not be too large for the new type

38

You might also like