core java day1

19
[email protected] Origin of Java World War-2 need of a platform independent language Green by Sun Micro Systems comes up Fails due to marketing issues et al Analog-to-Digital Transit, Computer H/W advancement, Concept of World Wide Web and Internet, Need of security Green transformed to Oak 1994 Java makes official release

Upload: soham-sengupta

Post on 13-Jul-2015

100 views

Category:

Software


2 download

TRANSCRIPT

[email protected]

Origin of Java

• World War-2 need of a platform independent language

• Green by Sun Micro Systems comes up• Fails due to marketing issues et al• Analog-to-Digital Transit, Computer H/W

advancement, Concept of World Wide Web and Internet, Need of security

• Green transformed to Oak • 1994 Java makes official release

[email protected]

Three Editions of Java

• J2SE (Java 2 Standard Edititon)

• J2EE (Java 2 Enterprise Edition)

• J2ME (Java 2 Micro Edition)

[email protected]

Java Data Types

Numeric: 1. Whole Numbers 2. FractionsWhole Numbers: byte 1 byte default value 0

short2 bytes default value 0 int 4 bytes default value 0 long 8 bytes default value 0

Fractions: float 4 bytes default value 0.0f double 8 bytes default value 0 .0

Symbolic: char 2 bytes (Sun Unicode Character) default value‘\u0000’

Logical : boolean 1 byte default value falseUser Defined: class and interface (to be described later on)

[email protected]

Your First Java Program

• In C consider the code snippet…#include<stdio.h> void main(){ printf(“Hello From Soham”);}• The corresponding Java Code would be…class A{public static void main(String[] args){ System.out.print(“Hello from Soham”);}}

[email protected]

Before I say more on Java some Do’s Soham was writing a program as on LHS. After typing out 1000 lines he felt he needed an extra statement in if branch, but poor Soham! What he

did was

• if(condition)

statement-1;

statement-2;

.

.

.

Statement-1000;

• if(condition)

statement-1;

statement-1A;statement-1A;

statement-2;

.

.

.

Statement-1000

[email protected]

Poor Me! I intended something else

I was supposed to type…• if(condition){

statement-1;

statement-1A;statement-1A;

}}

statement-2;

.

.

.

statement-1000

• Moral:1. When you come across some

if-else branch, or for, while, switch, or any method or block, at once type out the braces and then carry on with your code

2. It’ll not only save you from my condition, but also it’ll save you quite a lot of time of compilation errors saying…

“ } required”

[email protected]

More on Java

Answers to some FAQ about Java 2• A java file is saved in .java extension• A java file, if successfully compiled, produces x+y number of .class

files where x and y are the number of classes and interfaces in that file

• In java, you can’t put anything except comments outside a class or interface block

• To run java program you need Java Virtual Machine(JVM) which comes as a part of JDK.

• Successful compilation generates .class files which contain byte codes that is interpreted by JVM. So, java development generally uses both compiler and interpreter.

• Java Byte codes are platform independent but JVM is different for different Operating Systems.

[email protected]

Features of Java 2 (J2SE 1.4)

1. Platform independent…means runs on any HW+OS environment2. Java was developed using C++ but excludes the features like

pointers. 3. Java is a purely typed language as it does not allow automatic type

demotion (More on this later on)4. Java is object oriented, secure due to its various security features,

reusable and portable,form-free and case sensitive and supports general logical statements like C/C++

5. Java is not only platform friendly but also is very much developer friendly. As support of this statement, Java does not have concept of garbage value. It will never let the program perform read operation on a non initialized local variable .Also, it saves you from getting tampered data due to overflow and/or underflow since it doesn’t allow automatic type demotion

[email protected]

Java Source File Name & Class Name

1. A java source file may contain any number of classes and interfaces and there is no such hard-and-first rule that file name and class/ interface name should have relation…. But wait friends, this is applicable as long as the file contains no public class/interface. More concisely, a java source file must have the same name as that of the public class/interface in it. It’s thus implied that a java source file can contain one and only one public class/interface

2. To compile a Java file, say, A.java you have to give the command …>javac A.java

3. If successful compilation occurs, you will surely want to run it. And your command is going to be …> java MyClass where MyClass is the class inside A.java that has then main method.

4. Remember, MyClass need not always have the main method.

[email protected]

My Second Java Program

#include<stdio.h>

void main()

{

int x=940;

printf(“U scored good marks\n”);

printf(“Your marks is %d”,x);

}

class A{ public static void main(String[] ar){ int x=940; System.out.println(“U scored good

marks”);System.out.print(“Your marks is ”+x);}

}

[email protected]

Printing an output on the console

• We generally use the syntax System.out.print() or System.out.println() to output text on the console. Difference between them is that println() can be used with no arguments where as print() can’t be used without an argument. Also, println() automatically appends a trailing new line character (‘\n’)

• Don’t ask me more about System.out because my plan is to climb up the Java tree step by step and I don’t want to stumble down the stairs.

Yet, FYI, System is class under java.lang package and out is an static object belonging to System class and of type java.io.PrintStream.

• Note the syntax: System.out.print(“Your marks is ”+x);

• Here + is concatenation operator instead and apart from being the traditional addition operator.

[email protected]

Dual Nature of + operatorLook at the code snippet below and see the outputs int x=9; int y=6; System.out.println(x+y);

15

int x=9; int y=6; System.out.println(“Sum is ”+x+y);

Sum is 96

int x=9; int y=6; System.out.println(“Sum is ”+(x+y));

Sum is 15

int x=9; int y=6;System.out.println(“Product is ”+x*y);

Product is 54

int x=9; int y=6; System.out.println(x+y+ “ is the sum”);

15 is the sum

int x=9; int y=6; System.out.println(x-y+ “ is difference”);

3 is difference

int x=9; int y=6; System.out.println(“Difference is”+x-y);

Compilation error:Operator – cannot be applied to java.lang.String,int

[email protected]

From the Experts’ Desk

1. Since you can’t always afford to remember all the precedence rules and this sort of things, the Java Guru recommends that you should always use parentheses while using arithmetic expressions in the simplest way

2. As you are mostly accustomed to C/C++, first you’ll ask for a counterpart of scanf() and cin>>. Yes. You can take input from console through keyboard. But as I’ve told you, wait till I make you climb to that level! Java, unlike C/C++ is not meant to be used as a mere programming language with console as you did with Turbo C++, generating Pascal triangles or Fibonacci Series et al.

3. Today java is more of a technology than of a language itself. Java can carry out robust networking, enterprise web development to small mobile device programming.

4. Note that Java handles all inputs as String, unlike C then tries to convert to the intended type.

[email protected]

Java As a Typed language: code snippet

byte x=9;System.out.println(x);

Here output will be 9 It’s OK to assign a value to a type within range

byte x=129;System.out.println(x);

Error: Possible loss of precision: found int , required byte

Value beyond range. Range of byte –128 to +127

byte x=(byte)129;System.out.println(x);

Output: -127 (data tampered due to overflow)

Explicit type casting may cost you to worry later

int y=5; byte x=y;System.out.println(x);

Error: Possible loss of precision: found int , required byte

Though value is in range, type int can’t be automatically demoted.

int y=5; byte x=(byte)y;System.out.println(x);

OK. Output: 5 Explicit type demotion ok here but can cause OF/UF

long y=8; int x=y;System.out.println(x);

Guess yourself Automatica type demotion not allowed so error.

float x=9.8; // ErrorShould be float x=9.8f;

Error: possible loss of precision: found double required float

9.8 is double and 9.8f/9.8F is float. This is because java is memory efficient

[email protected]

Java A Typed Language: Contd.

1. boolean is the only data type that can’t be converted to any type nor any other type be converted to boolean.

2. Implicit type demotion is not allowed in java. You have to do it explicitly. But before that make sure that it causes no overflow and/or underflow or both.

3. Although char is 2 bytes and so is short, yet they are not compatible. char is automatically converted to int or higher. For hierarchy consult any standard book.

4. char is unsigned strictly in java and note the following. char ch=-90; // Error

char ch=90; System.out.println(ch); // output : Z

char ch=90; System.out.println((int)ch);// output 90

[email protected]

Operators: Unary & Binary

1. Rule for Unary Operator:

“If the operand is of a type which is below int in the hierarchy, the output is converted to int, else the type of the output is the type of the operand.”

2. Rule for Binary Operator:“ If the Binary operator takes 2 operators one of type T1 and the other of type T2, and max(T1,T2) is less than or equal to int, the output is converted to int itself, else the output is of type max(T1,T2)”

This rule is not applicable to increment and decrement operators

Hold your breath dears! Lots of surprises await you in the next slide.

[email protected]

Look at the code snippets belowbyte x=9; x=-x;System.out.println(x);

Error: Possible loss of precision found: int required: byte

Rule-1: inputbyteOutput int

byte x=9; byte y=x+1;System.out.println(x);

Same Error Rule:2 i/p byte, intO/p int

byte x=7; byte y=2;short z=x+y;

Same Error! Apply Rule-2

long x=89; byte y=8;int z=x+y;

Error! Apply Rule-2. Output is of type long

byte x=9; x=x+8; Error Apply Rule-2: Output is of type int

byte x=9; x+=8; x++; OK Rule-2 Not applicable for += and ++ operator

char ch=‘%’; int x=100System.out.println(x+ch+ “ pure am I”);

Output 137 pure am I Be careful. To avoid this, use parentheses or String ch=“%”;

[email protected]

Note the Following• byte x=‘c’; // is OK• int x=12; byte y=x; // Error

• final int x=12; byte y=x; // IS OK• final int x=134; byte y=x; // Error out of range• This holds only when source data is less than or

equal to int.• Adding the keyword “final” before a variable

makes it constant. It can’t be changed and any code to change this will result in compilation error

[email protected]

Note the following code snippets

public static void main(String[] args){ int x; x++; System.out.println(x);}

Error: variablex might not have been initialized.

In Java there is no concept of garbage value. Withoutinitializing a local variable u can’t perform read operation on it.

int x;if(6>4){x=8; }System.out.println(x);

OK. Output will be 8

6>4 is evaluated at compile time. So, since it’s true always, x must be initialized.

int x;if(6<4){ x=8;}System.out.println(x);

Error:variablex might not have been initialized.

6<4 is evaluated at compile time. So, since it’s false always, x must not be initialized.

Replace numerics by variables say, a & b. Observe the result, it’s errorif(a>b){ x=8;} System.out.print(x);But making them final will be ok if a>b is true

Error:variablex might not have been initialized.

a>b or a<b is not evaluated during compilation time. So, it’s not sure if x is initialized or not. Hence Error