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

Unit - 1 Basic Syntactical Constructs in Java.: Mundhe Shankar.G. Lecturer in IT Government Polytechnic Nanded

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 72

Unit -1

Basic Syntactical Constructs in Java.

Mundhe Shankar.G.
Lecturer In IT
Government polytechnic Nanded .

(As per MSBTE syllabus )


Basic Syntactical Constructs in Java.

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991.

This language was initially called “Oak,” but was renamed “Java” in 1995.

primary motivation was the need for a platform-independent (that is, architecture-neutral)
language.

second motivation was the World Wide Web.

Applet:
An applet is a special kind of Java program that is designed to be transmitted over the
Internet and automatically executed by a Java-compatible web browser.
Secure :
Java achieved this protection by confining an applet to the Java execution environment
and not allowing it access to other parts of the computer.
Portability:
Portability is a major aspect of the Internet.

Java’s Magic: The Bytecode


output of a Java compiler is not executable code. Rather, it is bytecode.
Bytecode is a highly optimized set of instructions designed to be executed by
the Java run-time system, which is called the Java Virtual Machine (JVM).

Servlets: Java on the Server Side


A servlet is a small program that executes on the server.
Extends the features of web server.
Servlets are used to create dynamically generated content that is then served
to the client.
Java Features
• Simple
• Secure
• Portable
• Object-oriented
• Robust – Exception Handling , Memory Management (Garbage Collector)
• Multithreaded
• Architecture-neutral- write once; run anywhere, any time, forever.
• Interpreted and High performance-
bytecode was carefully designed to translate directly into native machine
code for very high performance by using a just-in-time compiler
• Distributed- RMI(Remote Method Invocation)
• Dynamic
A First Simple Program
class Example {
public static void main(String args[]) {
System.out.println ("This is a simple Java program.");
}
}

1. name of the source file should be Example.java


2. If more than one class definitions are there –The name of file will be the Class
in which main method is present
3. The Java compiler requires that a source file use the .java
1. C:\>javac Example.java
2. C:\>java Example
4. Public access specifier- main( ) must be declared as public
5. Static -allows main( ) to be called without having to instantiate a particular
instance of the class. main( ) is called by the JVM before any objects are made
6. Java is case-sensitive. Thus, Main is different from main
7. args receives any command-line arguments present
System.out.println ("This is a simple Java program.");

System
System is a predefined class that provides access to the system.

out
out is the output stream that is connected to the console.

println()
Output is actually accomplished by the built-in println( ) method.
class Example2 {
public static void main(String args []) {
int num;
num = 100;
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.print(num);
}
}
Output
This is num: 100
The value of num * 2 is 200

print() & println()


// Program - for loop
Class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
}
• Identifiers
• Identifiers are used to name things, such as classes, variables, and
methods.
• Java is case-sensitive, so VALUE is a different identifier than
Value.

• Literals
• A constant value in Java is created by using a literal
representation of it. For example, here are some literals:
• E.g Integer literal - 100,
float literal 12.43,
char literal ‘c’ ,
String literal “This is a test”
Comments
// Single line comment

/* Multi line
comment
*/
Java Keywords
Java Spacers
Data types
• Java defines eight primitive types of data:
byte, short, int, long, char, float, double, and boolean.

These can be put in four groups:


1. Integers This group includes byte, short, int, and long, which are for whole-valued signed
numbers.

2. Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.

3. Characters –char (16 bit)

4. Boolean - true/false values.


• // Compute the area of a circle.( Demonstration for Double )

class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
// 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: “ + ch1 + “ " + ch2);
}
}

Output

ch1 and ch2: X Y


// char variables behave like integers.
class CharDemo2 {

public static void main(String args[]) {


char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++;
System.out.println("ch1 is now " + ch1);
}
}

The output :
ch1 contains X
ch1 is now Y
// Demonstrate boolean values.

class BoolTest {
public static void main(String args[]) {
boolean b;
//b = false;
System.out.println("b is " + b);
//b = true;
//System.out.println("b is " + b);
}
}
Output:
B is false
B is true
Variables
The variable is the basic unit of storage in a Java program.

Declaring a Variable

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing // d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.


Dynamic Initialization
• Java allows variables to be initialized dynamically, using any expression valid
at the time the variable is declared.

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Scope of variables
• // Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) {
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
y = 100; // Error! y not known here
System.out.println("x is " + x);
}
}
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
// This program will not compile

class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{
// creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
Type Conversion and Casting
• There are two types of conversion 1)Automatic 2) Casting
• If the two types are compatible, then Java will perform the conversion
automatically.
– E.g. assign an int value to a long variable.
• is no automatic conversion defined from double to byte

• Casting -

it is still possible to obtain a conversion between incompatible types. To do


so, you must use a cast.

It performs an explicit conversion between incompatible types.


1 Java’s Automatic Conversions
• Automatic Conversions will take place in following two conditions:
 The two types are compatible.
 The destination type is larger than the source type.

 When these two conditions are met, a widening conversion takes place.

 E.g. int type is always large enough to hold byte values, so no explicit cast
statement is required.

 Java also performs an automatic type conversion when storing a literal


integer constant into variables of type byte, short, long, or char.

 there are no automatic conversions from the numeric types to char or


boolean & vice versa.
Casting Incompatible Types
• what if you want to assign an int value to a byte variable?
• conversion will not be performed automatically, because a byte is smaller
than an int.
• This kind of conversion is sometimes called a narrowing conversion,
• A cast is simply an explicit type conversion.

– It has this general form:


– Variable_name = (target-type) value

– int a;
– byte b;
– b = (byte) a; // Casting done

• truncation: (Float -> int )


• A different type of conversion will occur when a floating-point value is
assigned to an integer type
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 260.142;
System.out.println("\n Conversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);

System.out.println("\n Conversion of double to int.");


i = (int) d; Output
System.out.println("d and i " + d + " " + i);

System.out.println("Conversion of double to byte.");


b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
• One more program for conversion of data
types . Take own values
Default Values of Data types
Array
• Declaring an Array of Primitives
int[] key; // Square brackets before name (recommended)
int key []; // Square brackets after name (legal but less
readable)
• Declaring an Array of Object References
Thread[] threads; // Recommended
Thread threads []; // Legal but less readable
int[] testScores; // Declares the array of ints
testScores = new int[4]; //constructs an array and assigns it default values
class GFG 
{
    public static void main (String[] args) 
    {         
      int[] arr;     // declares an Array of integers.
            arr = new int[5]; // allocating memory for 5 integers.  
            arr[0] = 10; // initialize the first elements of the array
          arr[1] = 20;  // initialize the second elements of the array
arr[2] = 30;
       arr[3] = 40;
       arr[4] = 50;    
   
       for (int i = 0; i < 5; i++)
        System.out.println("Element at index " + i +  " : "+ arr[i]);          
    }
}
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5;i++){
result = result + nums[i]; }
System.out.println("Average is " + result / 5);

}
Multidimensional Arrays
• int twoD[][] = new int[4][5];

Program – after completion of For Loop


Operators
// Demonstrate the % operator.

class Modulus {
public static void main(String args []) {
int x = 42;
int ans= x%10;;
double y = 42.25;
double ans1=y %10;
System.out.println("x mod 10 = " + ans);
System.out.println("y mod 10 = " + ans1);
}
}

output:
x mod 10 = 2
y mod 10 = 2.25
• a = a + 4; or a += 4;

class OpEquals {
public static void main(String args[]) {
int a = 1; int b = 2;
a += 5;
b *= 4;
System.out.println("a = " + a);
System.out.println("b = " + b);

}
}
• The output of this program is shown here:
• a=6
• b=8
• Bitwise operators
• Relational Operators
• Turnary operator ?
(Expression1 ? Expression 2: Expression 3);
Where Expression1 results true or false
conditional if or Turnary operator

public class ConditionalIf {

public static void main(String[] args) {


int a=10, b ;
b= (a < 15 ? 10 :20);
System.out.print("b ="+b);
}

}
Output:
b=10
• instanceof operator

• operator is used for object reference variables only, and you can use it to
check whether an object is of a particular type.
By type, we mean class or interface type—in other words, if the object
referred to by the variable on the leftside of the operator passes the IS-A test
for the class or interface type.

class A { }

class B extends A {
public static void main (String [] args) {
B b = new B();
if (b instanceof A) {
System.out.print("b is an A");
}
}
• If statement
if (condition)
{
statement1;
}
else{
statement2;
}
Nested If Else statement .
if (condition)
{
if (Condition1)
{
statements;
}
if(condition2) { Statements4;}
}
else{
statement2;
}
• Else If ladder

if(condition) {
statement;
}
else if(condition){
statement;
}
else if(condition){
statement;
}
...
else{
statement;
}
• Switch
switch (expression) {
case 1:
// statement sequence
break;

case 2:
// statement sequence
break;
...

case n :
// statement sequence
break;
default:
// default statement sequence
}
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}}
This program generates the following output:

i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
• Nested switch
switch(count) {
case 1:
switch(target)
{
case 0:
System.out.println("target is zero");
break;
case 1:
System.out.println("target is one");
break;
}
break;
case 2:
// ..ements
break;
• While Loop

• class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
When you run this program, it will “tick” ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
• Do- While loop Syntax

do {

// body of loop

} while (condition);
While Loop
• While (condition){

//Statements
//increment or decrement
}
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
• For loop Syntax

• for(initialization; condition; inc/dec)


{
// body
}
class ForTick {
public static void main(String args[])
{
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
• Nested Loops

class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++) Output will be as like
{ .........
System.out.print("."); ........
.......
}
......
System.out.println(); .....
} ....
} ...
..
} .
• Jump Statement -break ,continue, return
• break
It force immediate termination of a loop, bypassing the conditional expression & any
remaining code in the body of the loop.

When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next.

• // Using break to exit a loop.


class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
This program generates the following output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
continue
• you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.

• public class ContinueExample {


public static void main(String args[]){
for (int j=0; j<=6; j++) {
if (j==4)
{
continue;
}
System.out.print(j+" ");
}
}
}

Output : 0 1 2 3 5 6
• The last control statement is return.

The return statement is used to explicitly return from a method.


class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}
The output
Before the return.

Note: If statemt not used then error- unreachable code


• Math Class

• The java.lang package also contains the Math class, which is used to perform
basic mathematical operations.

• max()
method takes two numeric arguments and returns the greater of the
two—for example,
x = Math.max(1024, -5000); // output is 1024.

The signatures of the


max() method are as follows:
public static int max(int a, int b)
public static long max(long a, long b)
public static float max(float a, float b)
public static double max(double a, double b)
• min() takes two numeric

• arguments and returns the lesser of the two—for example,


• x = Math.min(0.5, 0.0); // output is 0.0

• The signatures of the


• min() method are as follows:
• public static int min(int a, int b)
• public static long min(long a, long b)
• public static float min(float a, float b)
• public static double min(double a, double b)
• sqrt()
• The sqrt() method returns the square root of a double—f

• Math.sqrt(9.0) // returns 3.0

• The signature of the sqrt() method is as follows:


• public static double sqrt(double a)

• round()

• The round() method returns the integer closest to the argument.


• Math.round(-10.5); // result is –10

• The signatures of the round() method are as follows:


• public static int round(float a)
• public static long round(double a)
• abs()
• The abs() method returns the absolute value of the argument—for
example.
• Removing negation is called absolute value
• x = Math.abs(99); // output is 99
• x = Math.abs(-99) // output is 99

• The signatures of the abs() method are as follows:


• public static int abs(int a)
• public static long abs(long a)
• public static float abs(float a)
• public static double abs(double a)
public class MathDemo {

public static void main(String[] args) {


int x = 175;
int y = -184;
System.out.println(“absolute vale of x=" + Math.abs(x));
System.out.println(" absolute vale of y " + Math.abs(y)); System.out.println("
absolute vale of -0= " + Math.abs(-0));
}
}

Output
absolute vale of x=175
absolute vale of y= 184
absolute vale of -0=0
• exp(double a) 

•  java.lang.Math. exp(double a) returns Euler's number e raised to the power


of a double value. Special cases:

public class MathDemo {


public static void main(String[] args) {
double x = 5;
double y = 0.5;
// print e raised at x and y
System.out.println("Math.exp(" + x + ")=" + Math.exp(x));
System.out.println("Math.exp(" + y + ")=" + Math.exp(y));
}
}
OutPut:
Math.exp(5)=148.4131591025766
Math.exp(0.5)=1.6487212707001282
import java.lang.Math;

public class JavaMathExample1    
{    
    public static void main(String[] args)     
    {    
        double x = 28;    
        double y = 4;    
          
          System.out.println("Maximum number of x and y is: " +Math.max(x, y));   
          System.out.println(“Minuum number of x& y is ”+ Math.min(x,y));

        
       System.out.println("Square root of y is: " + Math.sqrt(y));   
         
                System.out.println("Power of x and y is: " + Math.pow(x, y));      
          
 
        System.out.println("exp of a is: " +Math.exp(x));    
          
          }    
}   

You might also like