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

18CS45 - 2020 - 21 - Module2 - Ooc

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

Module-2

Introduction to Java

Mr. Pradeep N. Surasura


Dept. of C.S.E.,
K.L.E.I.T., Hubballi.
Java Magic - The Bytecode
• Instruction set for the Java Virtual Machine

• Similar to an assembler same as representation


of a C++ code

• As java program is compiled, java bytecode is


generated

• Java bytecode is the machine code in the form


of a .class file.

• Java bytecode helps to achieve platform


independence
Java Bytecode Working and
Advantages
Java Buzzwords or Features
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Java Development Kit (JDK)
The Java Development Kit (JDK) is a software
development environment used for developing Java
applications and applets.

It includes the Java Runtime Environment (JRE), an


interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator (javadoc)
and other tools needed in Java development
Object-Oriented Programming
Two Paradigms
• Abstraction
• The Three OOP Principles
• Encapsulation
• Inheritance
• Polymorphism
Note
• Java is CASE SENSITIVE!!
• Whitespace is ignored by compiler
• Whitespace makes things easier to read
• File name has to be the same as class name
in file
• Need to import necessary class definitions
Structure of Java Programs
class class-name {
public static void main(String args[]) {
statement1;
statement2;


}
}
Example Program
“First.java”
Compiling & Running the Program

Compiling: is the process of translating source code written in


a particular programming language into computer-readable
machine code that can be executed.
$ javac First.java
This command will produce a file ‘First.class’, which is used
for running the program with the command ‘java’.

Running: is the process of executing program on a computer.


$ java First
About Printing on the Screen

1. System.out.println(“Hello World”); – outputs the string


“Hello World” followed by a new line on the screen.
2. System.out.print(“Hello World”); - outputs the string “Hello
World” on the screen. This string is not followed by a new
line.
3. Some Escape Sequence –
• \n – stands for new line character
• \t – stands for tab character
A Closer Look at the First Sample Program
A Second Short Program
System.out.println
• println is a method in the Printstream class.
• Defined:
– public void println(String x)

can be any type of string or combination string


using addition to join parts.
Example:
println(“hello “ + “world “ + x);
System.exit()
• One method in java.lang.System
• Defined:
public static void exit ( int status)
• Terminates currently running Java VM
• Status is status code, non zero will usually
mean something abnormal.
• Used at end to indicate success, or in middle
to signal problems.
Storing data
In Java, Data can be stored as
– Numbers
2, 6.67, 0.009
– Characters
‘c’, ‘p’, ‘?’, ‘2’
– Strings
“data”, “Hindi language”, “$99”,
“www.rediff.com”
Variables
• A variables can be considered as a name given to
the location in memory where values are stored.
• One syntax of variable declaration
dataType variableName;
• Do you imagine that the variable can change its
value – yes, that is why it is called as variable.
• Is the following variable name is legal:
GrandTotal ? Suggest good name for it?
Variables
• Variables:
– Name
– Type
– Value
• Naming:
– May contain numbers,underscore,dollar sign, or
letters
– Can not start with number
– Can be any length
– Reserved keywords
– Case sensitive
Variable declaration
• Before using any name, it must be declared
(with its type i.e int or double).

• Needed only once in one program


• Generally, done initially
• Syntax
datatype name;
double total; // stores the total value
int index;
int a,b , c, sum, interest;
Variable Names and Keywords
• Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character
'_', and character '$'. A name can’t contain space character.
• Do not start with a digit. A name can be of any length.
• Upper and lower case count as different characters. So SUM and Sum are
different names.
• A name can not be a reserved word.
• A name must not already be in use in this part of the program.
• A reserved word is a word which has a predefined meaning in Java. For
example int, double, true, and import are reserved words.
Primitive data types
Byte 8 -27 27-1
Short 16 -215 215-1
Int 32 -231 231-1
Long 64
Float 32
Double 64
Boolean 1 0 1
Char 16
Types of numbers
• int
Whole numbers like 0, 575, -345 etc.

• double
Numbers with decimal point
like 12.453, 3.432, 0.0000002
Math
• Unary
int x = -9;
• Regular math (+,-,*,/)
int y = 3+x;

• % modulo operator
Incrementing
• Increment and Decrement
• i++ equivalent to i = i + 1;
• Can also do ++i, which uses i before
incrementing it.
• Decrementing: i--;
Assignment
int a; //declaration – needed once
a = 10 ; // assignment … declared above

int a = 10; // assignment and declaration together


10 = a ; // not possible – compilation error
Left hand side is always a variable for assignment

Storage area
a 10
Assignment
• =
• Example:
int n;
n = 10;
or
int n = 10; //same
Assignment
• +=
• -=
• *=
• /=
• %=
Assignment…
int a , b ; // a =? b = ?
a = 4; // a = 4 b = ?
b = 7; // a = 4 b = 7
a = b; // a = 7 b = 7
b = a; // a = 7 b = 7
a = 5; // a = 5 b = 7
Arithmetic Operators
• What is the value of –12 + 3
• An arithmetic operator is a symbol that asks for
doing some arithmetic.

Operator Meaning Precedence


- Unary minus highest
+ Unary Plus highest
* Multiplication middle
/ Division middle
% Modulus middle
+ addition low
- Subtraction low
Expressions
• An expression is a combination of constants (like
100), operators ( like +), variables(section of
memory) and parentheses ( like “(” and “)” )
used to calculate a value.
• x = 1; y = 100 + x;
• This is the stuff that you know from algebra, like:
(32 - y) / (x + 5)
• There are rules for this, but best rule is that
an expression must look OK as algebra.
• Based on what you know about algebra, what is
the value of 12 - 4/2 + 2 ?
• Spaces don’t much matter.
basicOperation.java
class basicOperation {
//arithmetic using variables
public static void main() {
int a = 1+ 1;
int b = 3 * 3;
int c = 1 + 8/ 4;
int d = -2;
System.out.println( “a = ” + a);
System.out.println(“b = ” + b);
System.out.println(“c = ” + c);
System.out.println(“d = ” + d);
}
}
basicMath.java
class basicMath {
//arithmetic using variables
public static void main() {
int a = 1+ 3;
int b = a * 3;
int c = b / 4;
int d = c – a;
int e = -d;
System.out.println( “a = ” + a);
System.out.println(“b = ” + b);
System.out.println(“c = ” + c);
System.out.println(“d = ” + d);
System.out.println(“e = ” + e);
}
}
Parenthesis
• Difference between -1 * ( 9 - 2 ) * 3 and -1 * 9 - 2 * 3
• To say exactly what numbers go with each operator, use
parentheses.
• Nested Parentheses: The expression is evaluated starting at the
most deeply nested set of parentheses (the "innermost set"), and
then working outward until there are no parentheses left. If there
are several sets of parentheses at the same level, they are
evaluated left to right.
• ( ( ( 32 - 16 ) / ( 2 * 2 ) ) - ( 4 - 8 ) ) + 7
• Are arithmetic expressions the only kind of expression?
intergerDivision.java
class integerDivision {
public static void main ( String[] args ) {
System.out.println("The result is: " + (1/2 + 1/2)
);
}
}

• What is the value of 99/100 ?


• Change print statement to “print” (1.0/2 + 1/ 2 .0)
Increment Operators

• i + + first use the value of i and then increment it by 1.


‘i + +’ equivalent to ‘i = (i)+1’. // postfix increment
• + + i first increment the value of i by 1 and then use it.
‘+ + i’ equivalent to ‘i = (i+1)’. // prefix increment
int i=2;
•System.out.print(“ i = ”+ i++);//print 2, then i becomes 3
•System.out.print(“ i = ”+ ++i);//add 1 to i, then print 4
•Refer to incre.java
Decrement Operators

• i - - first use the i ’s value and then decrement it by one


i - - equivalent to (i)-1. // postfix decrement
• - - i first decrement i ’s value by one and then use it.
- - i equivalent to (i-1). // prefix decrement

int i=5;
System.out.print(“i = ” + i--);//print 5, then i becomes 4
System.out.print(“i = ” + --i);//subtract 1 from i, then print
3
Refer to decre.java
Boolean Data Type

This data type can store only two values; true and false.
Declaring a boolean variable is the same as declaring any other
primitive data type like int, float, char.
boolean response = false; //Valid
boolean answer = true; //Valid
boolean answer = 9943; //Invalid,
boolean response = “false”; // Invalid,

This is return type for relational & conditional operators.

Refer to bool_op.java
Boolean Expressions
• boolean b
b will be either true (1) or false (0)
• Logical operations: !(not), && (and) || (or)
• boolean a,b;
a = true;
b = false;
System.out.println (“a && b is “ + (a && b));
Strings
• Not a primitive class, its actually something called a wrapper
class
• To find a built in class’s method use API documentation.
• String is a group of char’s
• A character has single quotes
– char c = ‘h’;
• A String has double quotes
– String s = “Hello World”;
• Method length
– int n = s.length;
Using Strings
public class hello{
public static void main (String [] args) {
String s = “Hello World\n”;
System.out.println(s); //output simple
string
} //end main
}//end class hello
Character data
• Characters
‘a’, ‘A’, ‘c’ , ‘?’ , ‘3’ , ‘ ’
(last is the single space)

• Enclosed in single quotes


• Character variable declaration
char ch;
• Character assignment
ch = ‘k’;
String data
• Strings are sequence of characters enclosed in double quotes
• Declaration
String name;
String address;
String line;
• Assignment
name = “ram”;
line = “this is a line with spaces”;
name = “a”; // single character can be stored
name = “”; // empty string
• The sequence of characters enclosed in double quotes, printed in
println() are also strings.
• E.g. System.out.println( “Welcome ! “ );
try….catch blocks.
• Try {
…….
}
catch ( IOException v) {
……….
}
Exceptions
• Java exception object.
• java.io.Exception
most general one.
Some exception like in Throwable class
define methods to get the message.
Relational Operators

a < b a less than b. (true/false)


a <= b a less than or equal b. (true/false)
a > b a greater than b. (true/false)
a >= b a greater than or equal to b. (true/false)
These operations always return a boolean value.
System.out.println(“23 is less than 65 ” +23<65); // true
System.out.println(“5 is greater than or equal to 25.00?” +
5>=25.00); // false
Refer to relate.java
Relational Operators
• == equality
• != inequality
• > greater than
• < less than
• >= greater than or equal to
• <= less than or equal to
Equality Operators

a==b a equal to b. (true/false)


a!=b a not equal to b. (true/false)

boolean equal = 12 = = 150; // false


boolean again_equal = ‘r’= = ‘r’); // true
boolean not_equal = 53!=90); // true

Refer: equa.java
Conditional Operators

•A conditional operator is used to handle only two boolean


expressions.
Boolean expression always returns ‘true’ or ‘false’.
•Conditional AND ‘&&’
Return value is ‘true’ if both, x and y are true, else it is ‘false’.
System.out.println(“x&&y ” + x&&y); // Refer cond_and.java

•Conditional OR ‘||’
return value is true if any one of x or y, is true else it is false.
System.out.println(“x||y ” + x||y); // Refer cond_or.java
The if - branching statement
• if ( x < y) { • if ( x < y ) {
x = y; x = y;
} }
else {
x = 88;
}
The ‘ if ’ construct

It is used to select a certain set of instructions. It is used to decide


whether this set is to be carried out, based on the condition in the
parenthesis. Its syntax is:
if (<boolean expression>){
//body starts
<statement(s)>
//body ends
}
The <boolean expression> is evaluated first. If its value is true, then
the statement(s) are executed. And then the rest of the program. Refer
if_cond.java, if_cond1.java
The ‘if else’ construct

It is used to provide an alternative when the expression in if is


false. Its syntax is:
if(<boolean expression>){
<statement(s)>
}
else{
<statement(s)>
}
The if construct is the same. But when the expression inside if
is false then else part is executed.
Refer ifelse_cond.java
If/Else
• if (logic condition) {
something
}
else if (logic condition) {
something
}
else {
something else
}
Sample Program for if statement
‘if-else’ Program
class print_num {
public static void main(String args[]) {
int a_number;
a_number = 0;
if(a_number = = 1)
System.out.println("One");
else
{
if(a_number = = 2)
System.out.println("Two");
else
{
if(a_number = = 3)
System.out.println("Three");
else
System.out.println("No. is out of the range");
}
}
}
}
Nested IF
if ( x < 0 ) {
System.out.println( “ x is negative “ );
}
else {
if ( x > 0 ) {
System.out.println ( “x is positive” );
}
//end if x > 0
else {
System.out.println ( “x is zero “ );
}
} //end else x >=0
Syntax
switch(expression){
case value1:
statements;
break;
case value2:
statements;
break;
.
.
case valueN:
statements;
break;
default:
statements;
}
Switch/Case
• Switch(variable){
case(1): something;
break;
case(23): something;
break;
default: something;
}
‘switch’ Program
class print_num_switch {
public static void main(String args[]) {
int a_number;
a_number = 3;
switch(a_number){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("No. is out of the range");
}
}
}
Note

• The case values can be compared only for equality with the
switch expression
• The expression must be of type int, char, short, byte
• Each case value must be a constant, not a variable
• Duplicate case values are not allowed
• The default part is optional
Iteration Statements

• while
• The while loop is Java’s most fundamental loop statement. It repeats a
statement or block
• while its controlling expression is true. Here is its general form:
• while(condition) {
• // body of loop
• }
• The condition can be any Boolean expression. The body of the loop will be
executed as long
• as the conditional expression is true. When condition becomes false, control
passes to the
• next line of code immediately following the loop. The curly braces are
unnecessary if only
• a single statement is being repeated.
• do-while
do {
// body of loop
} while (condition);

• for
• a powerful and versatile construct.
for(initialization; condition; iteration) {
// body
}
• Using the Comma
Type Conversion and Casting

• Java’s Automatic Conversions


• 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:
• • The two types are compatible.
• • The destination type is larger than the source type.

• Casting Incompatible Types


• To create a conversion between two incompatible types, you must use
a cast. A cast is
• simply an explicit type conversion. It has this general form:
• (target-type) value
• int a;
• byte b;
• // ...
• b = (byte) a;
Automatic Type Promotion in Expressions

• byte a = 40;
• byte b = 50;
• byte c = 100;
• int d = a * b / c;

• As useful as the automatic promotions are, they can cause confusing


compile-time errors.
• For example, this seemingly correct code causes a problem:
• byte b = 50;
• b = b * 2; // Error! Cannot assign an int to a byte!
• In cases where you understand the consequences of overflow, you
should use an explicit
• cast, such as
• byte b = 50;
• b = (byte)(b * 2);
• which yields the correct value of 100.
Casting
int n = 40;
Wrong : byte b = n;
why??
Right: byte b = (byte) n;

Type casting converts to target type


Casting II
• Type char is stored as a number. The ASCII
value of the character.
• A declaration of :
– char c = ‘B’;
stores the value 66 in location c
can use its value by casting to int
how??
Arrays

Definition:
An array is a group/collection of variables of the same type
that are referred to by a common name and an index

Examples:
• Collection of numbers
• Collection of names
• Collection of suffixes
Examples

Array of numbers:

10 23 863 8 229

Array of names:

Sholay Shaan Shakti

Array of suffixes:

ment tion ness ves


Syntax
Declaration of array variable:
data-type variable-name[];
eg. int marks[];
This will declare an array named ‘marks’ of type ‘int’. But no
memory is allocated to the array.

Allocation of memory:
variable-name = new data-type[size];
eg. marks = new int[5];
This will allocate memory of 5 integers to the array ‘marks’
and it can store upto 5 integers in it. ‘new’ is a special
operator that allocates memory.
Syntax…

Accessing elements in the array:


Specific element in the array is accessed by specifying name
of the array followed the index of the element. All array
indexes in Java start at zero.
variable-name[index] = value;
eg. marks[0] = 10;
This will assign the value 10 to the 1st element in the array.
And
marks[2] = 863;
This will assign the value 863 to the 3rd element in the array.
Example
STEP 1 : (Declaration)
int marks[];
marks  null
STEP 2: (Memory Allocation)
marks = new int[5];
marks  0 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]

STEP 3: (Accessing Elements)


marks[0] = 10;
marks  10 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]
Program
class try_array {
public static void main(String args[]) {
int marks[];
marks = new int[3];
marks[0] = 10;
marks[1] = 35;
marks[2] = 84;
System.out.println(“Marks obtained by 2nd student=” + marks[1]);
}
}
Note

• Arrays can store elements of the same data type. Hence an


int array CAN NOT store an element which is not an int.
Though an element of a compatible type can be converted to
int and stored into the int array.
eg. marks[2] = (int) 22.5;
This will convert ‘22.5’ into the int part ‘22’ and store it into
the 3rd place in the int array ‘marks’.
• Array indexes start from zero. Hence ‘marks[index]’ refers
to the (index+1)th element in the array and ‘marks[size-1]
refers to last element in the array.
eg. marks[0] refers to 1st element, marks[1] refers to 2nd
element… etc. etc.
Alternative Syntax
Combined declaration & memory allocation:
data-type variable-name[] = new data-type[size];
eg. int marks[] = new int[5];
This will declare an int array ‘marks’ and will also allocate
memory of 5 integers to it.
Combined declaration, allocation & assignment:
data-type variable-name[] = {comma-separated values};
eg. int marks[] = {10, 35, 84, 23, 5};
This will declare an int array ‘marks’, will allocate memory
of 5 integers to it and will also assign the values as-
marks  10 35 84 23 5
marks[0] marks[1] marks[2] marks[3] marks[4]
End of Module 2

You might also like