0% found this document useful (0 votes)
17 views

Parameters Used in First Java Program

The document discusses different ways to write a Java program and parameters used in the first Java program. It explains concepts like class, public, static, void, main method, and String array. It also discusses how to compile and run a simple Java program and valid and invalid signatures for the main method.

Uploaded by

Yasir Imam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Parameters Used in First Java Program

The document discusses different ways to write a Java program and parameters used in the first Java program. It explains concepts like class, public, static, void, main method, and String array. It also discusses how to compile and run a simple Java program and valid and invalid signatures for the main method.

Uploaded by

Yasir Imam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Parameters used in first java program

Let's see what is the meaning of class, public, static, void, main,
String[], System.out.println().

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents
visibility, it means it is visible to all.
o static is a keyword, if we declare any method as static, it is
known as static method. The core advantage of static
method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM,
so it doesn't require to create object to invoke the main
method. So it saves memory.
o void is the return type of the method, it means it doesn't
return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will
learn it later.
o System.out.println() is used print statement. We will learn
about the internal working of System.out.println statement
later.

To write the simple program, open notepad by start menu ->


All Programs -> Accessories -> notepad and write simple
program as displayed below:
As displayed in the above diagram, write the simple program of
java in notepad and saved it as Simple.java. To compile and run
this program, you need to open command prompt by start
menu -> All Programs -> Accessories -> command
prompt.
To compile and run the above program, go to your current
directory first; my current directory is c:\new . Write here:
To compile: javac Simple.java
To execute: java Simple

How many ways can we write a java


program
There are many ways to write a java program. The modifications
that can be done in a java program are given below:

1) By changing sequence of the modifiers, method


prototype is not changed.

Let's see the simple code of main method.

1. static public void main(String args[])  

2) subscript notation in java array can be used after type,


before variable or after variable.

Let's see the different codes to write the main method.

1. public static void main(String[] args)  
2. public static void main(String []args)  
3. public static void main(String args[])  

3) You can provide var-args support to main method by


passing 3 ellipses (dots)

Let's see the simple code of using var-args in main method. We


will learn about var-args later in Java New Features chapter.

1. public static void main(String... args)  

4) Having semicolon at the end of class in java is optional.

Let's see the simple code.

1. class A{  
2. static public void main(String... args){  
3. System.out.println("hello java4");  
4. }  
5. };  

Valid java main method signature


1. public static void main(String[] args)  
2. public static void main(String []args)  
3. public static void main(String args[])  
4. public static void main(String... args)  
5. static public void main(String[] args)  
6. public static final void main(String[] args)  
7. final public static void main(String[] args)  
8. final strictfp public static void main(String[] args)  

Invalid java main method signature


1. public void main(String[] args)  
2. static void main(String[] args)  
3. public void static main(String[] args)  
4. abstract public static void main(String[] args)  

Resolving an error "javac is not recognized as an


internal or external command" ?
If there occurs a problem like displayed in the below figure, you
need to set path. Since DOS doesn't know javac or java, we need
to set path. Path is not required in such a case if you save your
program inside the jdk/bin folder. 

What happens at compile time?


At compile time, java file is compiled by Java Compiler (It does
not interact with OS) and converts the java code into bytecode.
What happens at runtime?
At runtime, following steps are performed:
Classloader: is the subsystem of JVM that is used to load class
files.
Bytecode Verifier: checks the code fragments for illegal code
that can violate access right to objects.
Interpreter: read bytecode stream then execute the
instructions.

Q)Can you save a java source file by other


name than the class name?
Yes, if the class is not public. It is explained in the figure given
below:

To compile: javac Hard.java


To execute: java Simple

Q)Can you have multiple classes in a java


source file?
Yes, like the figure given below illustrates:

JVM
JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides
runtime environment in which java bytecode
can be executed.
JVMs are available for many hardware and
software platforms. JVM, JRE and JDK are
platform dependent because configuration of
each OS differs. But, Java is platform
independent. There are three notions of the
JVM: specification, implementation, and
instance.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JRE
JRE is an acronym for Java Runtime
Environment. It is used to provide runtime
environment. It is the implementation of
JVM. It physically exists. It contains set of
libraries + other files that JVM uses at
runtime.
Implementation of JVMs are also actively
released by other companies besides Sun
Micro Systems.

JDK
JDK is an acronym for Java Development
Kit. It physically exists. It contains JRE +
development tools.
nternal Architecture of JVM
Let's understand the internal architecture of
JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM that is
used to load class files.
2) Class(Method) Area
Class(Method) Area stores per-class
structures such as the runtime constant pool,
field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects
are allocated.
4) Stack
Java Stack stores frames. It holds local
variables and partial results, and plays a part
in method invocation and return.
Each thread has a private JVM stack, created
at the same time as thread.
A new frame is created each time a method
is invoked. A frame is destroyed when its
method invocation completes.
5) Program Counter Register
PC (program counter) register contains the
address of the Java virtual machine
instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the
application.
7) Execution Engine
It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then
execute the instructions.
3) Just-In-Time(JIT) compiler: It is used
to improve the performance. JIT compiles
parts of the byte code that have similar
functionality at the same time, and hence
reduces the amount of time needed for
compilation.Here the term ?compiler? refers
to a translator from the instruction set of a
Java virtual machine (JVM) to the
instruction set of a specific CPU.

Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :

int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,

 Widening Casting(Implicit)

 Narrowing Casting(Explicitly done)

Widening or Automatic type converion


Automatic Type casting take place when,

 the two types are compatible

 the target type is larger than the source type

Example :

public class Test


{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}

Int value 100

Long value 100

Float value 100.0

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.
Example :

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}

Double value 100.04

Long value 100

Int value 100


Type conversion in Java with Examples
When you assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform
the conversion automatically known as Automatic Type Conversion and if not then they need to be casted or converted explicitly. For example, assigning an int
value to a long variable.

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This happens when:

 The two data types are compatible.


 When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also,
char and boolean are not compatible with each other.

Example:
class Test

    public static void main(String[] args)

    {

        int i = 100;

         

        //automatic type conversion

        long l = i;

         

        //automatic type conversion

        float f = l;

        System.out.println("Int value "+i);

        System.out.println("Long value "+l);

        System.out.println("Float value "+f);

    }

}
Int value 100

Long value 100

Float value 100.0

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.

char and number are not compatible with each other. Let’s see when we try to convert
one into other.
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
  public static void main(String[] argv)
  {
    char ch = 'c';
    int num = 88;
    ch = num;
  }
}
Run on IDE
Error:
7: error: incompatible types: possible lossy conversion from int to char

ch = num;

1 error

How to do Explicit Conversion?


Example:
//Java program to illustrate explicit type conversion
class Test
{
    public static void main(String[] args)
    {
        double d = 100.04;
         
        //explicit type casting
        long l = (long)d;
         
        //explicit type casting
        int i = (int)l;
        System.out.println("Double value "+d);
         
        //fractional part lost
        System.out.println("Long value "+l);
         
        //fractional part lost
        System.out.println("Int value "+i);
    }
}
Run on IDE
Output:
Double value 100.04

Long value 100

Int value 100

While assigning value to byte type the fractional part is lost and is reduced to modulo
256(range of byte).
Example:
//Java program to illustrate Conversion of int and
double to byte
class Test
{
    public static void main(String args[])
    {
        byte b;
        int i = 257;
        double d = 323.142;
        System.out.println("Conversion of int to
byte.");
         
        //i%256
        b = (byte) i;
        System.out.println("i = " + i + " b = " + b);
        System.out.println("\nConversion of double to
byte.");
         
        //d%256
        b = (byte) d;
        System.out.println("d = " + d + " b= " + b);
    }
}
Run on IDE
Output:
Conversion of int to byte.

i = 257 b = 1

Conversion of double to byte.

d = 323.142 b = 67

Type promotion in Expressions


While evaluating expressions, the intermediate value may exceed the range of
operands and hence the expression value will be promoted. Some conditions for type
promotion are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
2. If one operand is a long, float or double the whole expression is promoted to long, float or double respectively.
Example:
//Java program to illustrate Type promotion in
Expressions
class Test
{
    public static void main(String args[])
    {
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        float f = 5.67f;
        double d = .1234;
         
        // The Expression
        double result = (f * b) + (i / c) - (d * s);
         
        //Result after all the promotions are done
        System.out.println("result = " + result);
    }
}
Run on IDE
Output:
Result = 626.7784146484375

Explicit type casting in Expressions


While evaluating expressions, the result is automatically updated to larger data type  of
the operand. But if we store that result in any smaller data type it generates compile
time error, due to which we need to type cast the result.
Example:
//Java program to illustrate type casting int to byte
class Test
{
    public static void main(String args[])
    {
        byte b = 50;
         
        //type casting int to byte
        b = (byte)(b * 2);
        System.out.println(b);
    }
}
Run on IDE
Output
100

NOTE- In case of single operands the result gets converted to int and then it is type
casted accordingly.
Example:
//Java program to illustrate type casting int to byte
class Test
{
    public static void main(String args[])
    {
        byte b = 50;
 
        //type casting int to byte
        b = (byte)(b * 2);
        System.out.println(b);
    }
}
Run on IDE
Output
100

You might also like