KCS-602 Lecture02 Cse

You might also like

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

Core Java

HISTORY OF JAVA
• Java is developed by SUN Microsystems in 1991.
• Created by James Gosling, Patrick Naughton,,
Chris worth, Ed Frank Mike Sheridan.
• Initially it is called as “OAK” and renamed as
“JAVA” in 1995
• Java is an object oriented and multi threaded
programming language.

PRIMARY MOTIVATION
 General purpose Language, language used for embedded
systems.
 Initially used for Consumer Devices like microwave ovens,
televisions, hand-held remote control named Star 7.
FEATURES OF JAVA
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
• Simple:
– Java was designed to be easy for the professional
programmer to learn and use effectively.
– If you already understand the basic concepts of object-
oriented programming, learning Java will be even easier.
– In Java, there are a small number of clearly defined ways
to accomplish a given task.
• Secure
– Java does not use memory pointers explicitly. All the
programs in java are run under an area known as the
sand box.
– Security manager determines the accessibility options of
a class like reading and writing a file to the local disk.
– Java uses the public key encryption system to allow the
java applications to transmit over the internet in the
secure encrypted form.
– The bytecode Verifier checks the classes after loading.
• Portable
– The feature Write-once-run-anywhere makes the java
language portable provided that the system must have
interpreter for the JVM.
– Java also have the standard data size irrespective of
operating system or the processor. These features makes
the java as a portable language.
• Object Oriented
– Java supports object oriented approach whose important
feature is reusability of code
• Robust
– Java has the strong memory allocation and automatic
garbage collection mechanism.
– It provides the powerful exception handling and type
checking mechanism as compare to other programming
languages.
– Compiler checks the program whether there any error and
interpreter checks any run time error and makes the system
secure from crash.
• Multithreading
– Java was designed to meet the real-world requirement of creating
interactive, networked programs.

– To accomplish this, Java supports multithreaded programming,


which allows you to write programs that do many things
simultaneously.

– Multithreading means a single program having different threads


executing independently at the same time.

– Multiple threads execute instructions according to the program


code in a process or a program.

– Multithreading works the similar way as multiple processes run


on one computer.

– In multithreaded programs not even a single thread disturbs the


execution of other thread. Threads are obtained from the pool of
available ready to run threads and they run on the system CPUs.

– This is how Multithreading works in Java.


• Platform Independent
– The concept of Write-once-run-anywhere (known as the
Platform independent) is one of the important key feature of
java language that makes java as the most powerful language.
Not even a single language is idle to this feature but java is
more closer to this feature. The programs written on one
platform can run on any platform provided the platform must
have the JVM.

• Architecture Neutral
– The feature “write once; run anywhere, any time, forever.”
makes the java language portable provided that the system
must have interpreter for the JVM.
– Java also have the standard data size irrespective of operating
system or the processor.
• Interpreted
– Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java
bytecode.
– This code can be interpreted on any system that provides a
Java Virtual Machine.

• Performance
– Java uses native code usage, and lightweight process
called threads. In the beginning interpretation of bytecode
resulted the performance slow but the advance version of JVM
uses the adaptive and just in time compilation technique that
improves the performance.
• Distributed

– The widely used protocols like HTTP and FTP are


developed in java. Internet programmers can call
functions on these protocols and can get access the files
from any remote machine on the internet rather than
writing codes on their local system.

• Dynamic

– While executing the java program the user can get the
required files dynamically from a local drive or from a
computer thousands of miles away from the user just by
connecting with the Internet.
A Simple Java Program – The Set Up

 Before we learn about writing a simple java program, let us


understand what preparations are needed for running a java
program from console.

 We have to define PATH and CLASSPATH parameters and


create necessary directories (folders) where we will be
storing all our program files.
PATH

 PATH is an environmental variable in DOS(Disk Operating System),


Windows and other operating systems like Unix.

 PATH tells the operatingsystem which directories(folders) to


searchfor executable files, in response to commands issued by a user

 It is a convenient way of executing files without bothering about


providing the absolute path to the folder, where the file is located.
How to set PATH ?

1.Right Click My Computer


2.Select Properties
3. Youwillget to see the Properties
Page of My Computer
4.Select Advanced Tab
5.Select Environment Variables
6. You will see Environment
Variables Page as displayed here.
How to set PATH ? (Contd.).

3. Insert the path to your jdk/bin folder


(e.g. C:\Program Files\Java\JDK
1.6.0_05\bin;

4.
1. Select Click on
Path OK

2. Click on
Edit 5.
Click
on OK
CLASSPATH

• CLASSPATH is a parameter which tells the JVM or the Compiler,


where to locate classes that are not part of Java Development
ToolKit(JDK).

• CLASSPATH is set either on command-line or through environment


variable.

• CLASSPATH set on command-line is temporary in nature, while the


environment variable is permanent.
How to set CLASSPATH ?

1.Right Click My Computer


2.Select Properties
3. You will get to see the
Properties Page of My
Computer
4.Select Advanced Tab
5.Select Environment Variables
6. You will see Environment
Variables Page as displayed
here
How to set CLASSPATH ? (Contd.).
2. Enter “CLASSPATH” as
the variable Name

3. Enter “.” as the Variable


1. Click on New
value
A Simple Java Program
Our first Java Program:

public class Welcome {


public static void main(String args[]) {
System.out.println(“Welcome..!”);
}
} This program displays the output
“Welcome..!”
on the console

Create Source File: Welcome.java


Compile : javac Welcome.java
Execute : java Welcome
Executing your first Java Program
 Before executing the program, just check whether the PATH and the CLASSPATH
parameters are properly set, by typing in the commands as shown in the screen below:
Executing your first Java Program (Contd.).
 Now compile and execute your program as given below :
Public static void main(String args[]) - Means
Public- it is access specifiers from anywhere we can access it
Static- it is access modifier we can call the methods directly by class name without
creating its objects
Void- it is the return type
Main- it is a method name
String[]args- in java we accept only the string type of argument and store it.
Access Specifier:- This can be understood as the access you provide to your code in Java
whether other classes can access your code or not.
E.g. public, private, protected and default.
Access Modifier:- Java provides both Access Specifier and Access Modifiers for creating
access to your Java code for other classes. Here modifier is also used to do the same task
but there are limitations.
Class Modifier:
abstract :- This defines the restriction such that objects cannot be created.
final:- This restricts a class from being inherited.
strictfp:- it is related to the checking of floating point values irrespective of OS.
Variable Modifier:
static:no object creation required
final: cannot be reassigned
transient: it is not serialized
volatile: the values are liable for change
JAVA ARCHITECHTURE
COMPILE TIME RUN TIME ENVIRONMENT
ENVIRONMENT
Step 3 JAVA
CLASS
Step 1 CLASS
LOADER
JAVA LIBRARIES
SOURCE
CODE Step 4 BYTE
CODE
Java Bytecodes
VERIFIER
Step 2 move locally or Step 5
through
JAVA COMPILER network JUST IN
JAVA TIME
INTERPRETER
COMPILER

JVM
JAVA
RUN TIME SYSTEM
BYTE
CODE
(.class)
OPERATING SYSTEM

HARDWARE
Java Architecture (Contd.).

Step1:
Create a java source code with .java extension

Step2:
Compile the source code using java compiler, which will
create bytecode file with .class extension

Step3:
Class loader reads both the user defined and library classes
into the memory for execution
Java Architecture (Contd.).

Step4:
Bytecode verifier validates all the bytecodes are valid and
do not violate Java’s security restrictions

Step5:
JVM reads bytecodes and translates into machine code for
execution. While execution of the program the code will
interact to the operating system and hardware
The 5 phases of Java Programs
Java programs can typically be developed in five stages:
1. Edit
Use an editor to type Java program (Welcome.java)
2. Compile
• Usea compiler to translate Java program into an
intermediate language called bytecodes, understood by Java
interpreter (javac Welcome.java)

• Use a compiler to create .class file, containing bytecodes


(Welcome.class)
3. Loading
Use a class loader to read bytecodes from .class file into memory
The 5 phases of Java Programs (Contd.).

4. Verify
Use a Bytecode verifier to make sure bytecodes are valid and do not
violate security restrictions
5. Execute
• Java Virtual Machine (JVM) uses a combination of interpretation
and just-in-time compilation to translate bytecodes into machine
language

• Applications are run on user's machine, i.e. executed by


interpreter with java command (java Welcome)
Java Virtual Machine

• The output of the compiler is


bytecode
• The bytecodes are executed by
JVM
• It is an interpreter which converts
the specific byte code to machine
instructions and executes
• JVM is platform specific
Keywords
Java reserves some words, which cannot be used as class, method or
variable names.
Good Programming Practices
Naming Conventions
Class Names
 Class names should be nouns, in mixed case with the first
letter of each internal word capitalized
 Class names should be simple and descriptive
 Eg: class Student, class TestStudent

Variable Names
 The variables are in mixed case with a lowercase first letter
 Variable names should not start with underscore _ or dollar sign $
characters, even though both are allowed
 Variable names should be small yet meaningful
 One-character variable names should be avoided except for
temporary “throwaway” variables
 Eg: int y,myWidth;
Good Programming Practices(Contd.).
Naming Conventions
Method Names
 Methods should be verbs, in mixed case with the first letter lowercase, with the
first letter of each internal word capitalized
 Eg: void run(), void getColor()
Comments

Block Comments
(optional)
 Block comments are used to provide descriptions of files, methods, data
structures and algorithms
 Block comments may be used at the beginning of each file and before each
method
/*
Here is a block comment
*/
Good Programming Practices(Contd.).

Comments
Single line Comment
Single line comments can be written using
// Single line
Number per Line
One declaration per line is recommended
int height;
int width;
is preferred over
int height,width;
Do not put different types on the same line
int height,width[]; // Not recommended
Error Types
Syntax error / Compile errors
– caught at compile time.
– compiler did not understand or compiler does not
allow
Runtime error
– something “Bad” happens at runtime. Java
breaks these into Errors and Exceptions
Logic Error
– program compiles and runs, but does not do
what you intended or want
Operators

Java provides a rich set of operators that can be


categorized under 6 groups of operators
• Arithmetic Operator
• Relational Operator
• Logical Operator
• Unary Operator
• Bitwise Operator
• Assignment Operator
Arithmetic operator

Operator Name of the Operator Example


+ Addition n = n + 1;
- Subtraction n = n-1;
* Multiplication n = n * 1;
/ Division n = n / 1;
% Modulus [Reminder] n = n % 1;
Arithmetic Operators - QUIZ

class Sample{ Output:


a + b = 13
public static void main(String[ ] args){
a-b=7
int a = 10; a * b = 30
int b = 3; a/b=3
System.out.println("a + b = " + (a + b) ); a%b=1
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("a / b = " + (a / b) );
System.out.println("a % b = " + (a % b) );
}
}
Relational operator

Operator Name of the Operator Example


== Equal to a == b
!= Not Equal to a != b
> Greater Than a>b
>= Greater Than or equal to a >= b
< Lesser Than a<b
<= Lesser than or equal to a <=b
Relational Operators - QUIZ

class Sample{
public static void main(String[] args){
int a = 10;
int b = 20; Output:
System.out.println("a == b = " + (a == b) );
a == b = false
System.out.println("a != b = " + (a != b) );
a != b = true
System.out.println("a > b = " + (a > b) ); a > b = false
System.out.println("a < b = " + (a < b) ); a < b = true
System.out.println("b >= a = " + (b >= a) ); b >= a = true
System.out.println("b <= a = " + (b <= a) ); b <= a = false
}
}
Logical operator & Unary operator
Operator Name of the Operator Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !(a &&b)

Operator Name of the Operator Example


+ Unary plus operator int number = +1;
- Unary minus operator number = - number;
++ Increment operator ++ number;
-- decrement operator -- number;
Logical Operators - QUIZ

class Sample{
public static void main(String[] args){
boolean a = true;
boolean b = false;
System.out.println("a && b= " + (a&&b));
System.out.println("a || b= " + (a||b));
System.out.println("!(a && b)= "+!a&&b));
}
} Output:
a && b = false
a || b = true
!(a && b) = true
Unary Operator - QUIZ

class Sample{
public static void main(String args[]) { Output:
int a = 10;
int b = 20; ++a = 11
System.out.println(“++a=”+ (++a));
--b = 19
System.out.println(“--b=”+ (--b));
}
}
Quiz-2

What will be the result, if we try to compile and execute the following code?

class Test {
public static void main(String [ ] args) {
int x=10;
int y=5;
System.out.println(++x+(++y));
}
}

OUTPUT: 17
bitwise operator

Operator Description Example


~ Unary bitwise complement ~op2
& Bitwise AND Op1 & Op2
| Bitwise inclusive OR Op1 | Op2
^ Bitwise exclusive OR Op1 ^ Op2
<< Signed left shift Op1 << Op2
>> Signed right shift Op1 >> Op2
Bitwise operator
~  Compliment &  AND
^  XOR |  OR

0 0 1 0 1 1 0 1

~ 0 1 0 0 1 1 1 1 & 0 1 0 0 1 1 1 1

1 0 1 1 0 0 0 0 0 0 0 0 1 1 0 1

0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1

^ 0 1 0 0 1 1 1 1 | 0 1 0 0 1 1 1 1

0 1 1 0 0 0 1 0 0 1 1 0 1 1 1 1
Right-Shift and left-shift Operators
• Arithmetic or signed right shift (>>)
operator:
– Examples are:
• 128 >> 1 returns 128/21 = 64
• 256 >> 4 returns 256/24 = 16
• -256 >> 4 returns -256/24 = -16
– The sign bit is copied during the shift.

• Left-shift (<<) operator works as follows:


– 128 << 1 returns 128 * 21 = 256
– 16 << 2 returns 16 * 22 = 64
Example
class BitwiseOper {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
}
}
Right Shift Operator >> QUIZ
class ShiftExample1 {
public static void main(String[] args) {
int x = 16;
System.out.println("The original value of x:"+x);
x = x >> 3;
System.out.println("After >> 3,new value:"+x);
}
}

The original value of x: 16


After >> 3, new value: 2
Left Shift Operator << QUIZ
class ShiftExample2 {
public static void main(String[] args) {
int x =8;
System.out.println("The original value:"+x);
x = x << 4;
System.out.println("After << 4,new value:"+x);
}
}

The original value: 8


After << 4, new value: 128
Assignment operator
Operator Description Equivalent Expression
= x = y;
+= x += y; x = (x + y);
-= x -= y; x = (x - y);
*= x *= y; x = (x * y);
/= x /= y; x = (x / y);
%= x %= y; x = (x % y);
&= x &= y; x = (x & y);
|= x != y; x = (x ! y);
^= x ^= y; x = (x ^ y);
<<= x <<= y; x = (x << y);
>>= x >>= y; x = (x >> y);
Example
class CompAssignDemo{
public static void main(String[] args) {
int x=5;
int y=10; x += y;
System.out.println("The addition is:"+ x);
x -= y;
System.out.println("The subtraction is:"+ x);
x *= y;
System.out.println("The multiplication is:"+ x);
x /= y;
System.out.println("The division is"+ x);
x %= y;
System.out.println("The remainder is:"+x);
x &= y;
System.out.println("The result of AND operation :"+ x);
x |= y;
System.out.println("The result of Bitwise inclusive OR operation :"+ x);
x <<= y;
System.out.println("The result of Signed left shift operation :"+ x);
}
}
DATATYPES
There are eight primitive data types supported by Java
1. byte:
Byte data type is an 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

2. 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
3. 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

4. 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: long a = 100000L, int b = -200000L
5. float:
Float data type is a single-precision 32-bit floating point.
Float is mainly used to save memory in large arrays of floating
point numbers. Default value is 0.0f.
Example: float f1 = 234.5f

6. double:
double data type is a double-precision 64-bit floating point.
This data type is generally used as the default data type for
decimal values, generally the default choice.
Default value is 0.0d.
Example: double d1 = 123.4d
7. 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

8. char:
char data type is a single Unicode character (instead of ASCII).
Minimum value is '\u0000' (or 0). 16-bit
Maximum value is '\uffff' (or 65,535 inclusive). Char data type is
used to store any character.
Example: char letterA ='A'
Quiz

What will be the result, if we try to compile and execute the following code?

class Test
{
public static void main(String [ ] ar)
{
int for=2;
System.out.println(for);
}
}
Quiz

class Test {
public static void main(String [ ]arg)
{
byte b=128;
System.out.println(b);
}
}
Quiz
class Test {
public static void main(String ar[])
{ float f=1.2;
boolean b=1;
System.out.println(f);
System.out.println(b);
}
}
Quiz(Contd.).
class Test {
public static void
main(String ar[]) {
double d=1.2d;
System.out.println(d);
}
}

OUTPUT: 1.2
Quiz(Contd.).

class Test {
public static void main(String [ ] args)
{
int 9A=10;
System.out.println(9A);
}
}
Types of Variables
The Java programming language defines the following kinds of Variables:

 Local Variables

 Tied to a method

 Scope of a local variable is within the method

 Instance Variables (Non-static)

 Tied to an object

 Scope of an instance variable is the whole class

 Static Variables

 Tied to a class

 Shared by all instances of a class


Local Variables
Instance Variables
public class StaticVariable
{ Static Variables
private static String color;
public static String car=“Benz”;

public static void main(String args[])


{
color=“red”;
System.out.println(car+ “ Color: “+color);
}
}

You might also like