Week 2

You might also like

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

Structure of JAVA program

1. documentation section  used to give the comments


1. Single Line Comment  //comments
2. Multi Line Comment  /* comments */
3. Documentation Comment  used to prepare documentation for a project
/** comments */* (each line begins with *)

2. import statement  similar to header files in C and C++ and All the pre-defined classes will be available in this. Methods and
interfaces available in classes
3. package statement  we can create our own user defined packages
Ex: package student;
4. interface statement  same as classes but it contains only method declarations and useful in order to implement multiple
inheritance
5. Class definition  must write the entire logic in class only
6. main method class  main() method should contain in one class
main method definition
Simple JAVA program
//sample program to print a content
class SamplePgm
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Save: SamplePgm.java Compilation: javac SamplePgm.java
Execution: java SamplePgm Output: Hello World
Main Method
 public static void main(String args [])

public access modifier (public, private, protected, default)


If any class / method is declared as public then that is accessed by any class / method in a
package i.e., accessible through out the program.

static direct access


any class / method can access the main method directly without creating of an object

void return type


If you are given return type the system will treat it as a constructor return type may be any
data type

main name of the function


It tells the compiler to start the execution from here

String args[] command line arguments


User can pass the data through this If you didn’t write this then it won’t execute
main
Every one
method String
can access
returns class
this method
nothing

public static void main(String args [])


Java Features / Java Buzzwords
Simple

 Similar to C/C++ in syntax


 But eliminates several complexities of
 No operator overloading
 No direct pointer manipulation or pointer arithmetic
 No multiple inheritance
 No malloc() and free() – handles memory automatically
Platform Independent and Portable

 “Write-Once Run-Anywhere”

 Changes in system resources will not force any change in the program.

 The Java Virtual Machine (JVM) hides the complexity of working on a particular
platform

 Convert byte code into machine level representation.


Robust and secure

 Designed with the intention of being secure


 No pointer arithmetic or memory management!

 Strict compile time and run time checking of data type.

 Exception handling

 It verify all memory access


Distributed and Network Oriented

• Java grew up in the days of the Internet


• Inherently network friendly

• Original release of Java came with Networking libraries

• Newer releases contain even more for handling distributed applications


• RMI (Remote Method Invocation), Transactions
Multithreaded and Interactive
• Handles multiple tasks simultaneously.
• Java runtime system contains tools to support multi-process
synchronization and construct smoothly running interactive systems.
Rules for Java Identifier
• There are certain rules for defining a valid java identifier. These rules must be followed, otherwise
we get compile-time error. These rules are also valid for other languages like C,C++.
• The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]),
‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java identifier as it
contain ‘@’ special character.
• Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java
identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 –
15 letters only.
• Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.
Naming convention
Class:
• Name should begin with capital letter (single word)
• First letter of every word should begin with capital letter (multi)
• Ex: Student, BranchName
Method:
• First letter of every word should begin with lower case (single word)
• First letter of first word should be small and First letter of every word
should begin with capital letter(multi)
• Ex: read(), getName(), nextLine
Data Types
• There are exactly eight primitive data types in Java
• Four of them represent whole valued signed numbers:
• byte, short, int, long
• Two of them represent floating point numbers:
• float, double
• One of them represents characters:
• char
• And one of them represents boolean values:
• boolean
Data type Size Default values Range

byte 1 0 -128 to +127 (-27 to +27-1)


short 2 0 -32768 to +32767 (-215 to +215-1)
int 4 0 -2147483648 to +2147483647 (-231 to +231-1)
long 8 0 -9223372036854775808 to +9223372036854775807 (-263 to +263-1)
float 4 0.0f/F 3.4e-038 to 3.4e+038
double 8 0.0 1.7e-308 to 1.7e+308 (14 or 15 digits after decimal)
char 2 blank space -32768 to +32767 (-215 to +215-1)
boolean 1 bit False 0 or 1
Variables
 Local:
Declared inside a method / constructor
Direct access and initialization is mandatory otherwise shows an error
Used in temporary calculations
 Instance / Member / Fields:
Declared inside the class but outside all the methods
Accessing is done through object (objectname.variablename)
Memory allocation can be done only after creation of object
 Static:
Declared inside a method / class with static keyword
Direct access (by variable / classname.variable)
Memory allocated only once and it happens when the class is loaded in memory
Useful when all the objects are using the same value of that variable
class Variable
{ To Compile
static int a =10; //access by all objects
C:\> Javac Variable.java
int c;
public static void main(String args[])
To Run
{
int b = 20; C:\> java Variable
System.out.println(b);
System.out.println(a); Output:
Variable obj = new Variable();
20
Variable obj1 = new Variable();
10
obj.a=500; 30obj=500, obj1= 500
obj.c=30; 0
System.out.println(obj.c+ "obj=" + obj.a + ", obj1= " +obj1.a); 0
System.out.println(obj1.c);
}
}
Reading variable from Key board
• Command line argument
• Scanner class
Command Line Argument
class CommandLine{
1. Save the program as CommandLine.java
public static void main(String args[])
{ 2. For compilation c:\> javac CommandLine.java
int a, b, c;
a= Integer.parseInt(args[0]); 3. For Run c:\> java CommandLine 5 6
b= Integer.parseInt(args[1]);
c= a+b; 4. Output
System.out.println("the sum of " +a +" and " +b+ " is " +c);
} the sum of 5 and 6 is 11
}
Scanner Class
To Compile
import java.util.Scanner;
class Sample C:\> Javac Sample.java
{
To Run
public static void main(String args[])
{ C:\> java Sample
int a;
Scanner s = new Scanner(System.in); Output:
System.out.println("Enter value for a: ");
a = s.nextInt(); Enter value for a:
System.out.println(“value of a is:”+a); 20
} Value of a is: 20
}
Scanner class function
Operators
Java provides many types of operators which can be used according to the need. They are classified
based on the functionality they provide Some of the types are-
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Unary Operators
 Assignment Operator
 Ternary Operators
Arithmetic operator
• If either or both operands associated with an arithmetic operator are floating point, the result is a
floating point
• % operator applies both to floating-point type and integer types

public class Reading


{
public static void main(String args[])
{
int a = 20, b = 10 ;
string x = "welcome", y = "java"; output
System.out.println("a + b = " + (a + b)); // a+b = 30
System.out.println("a - b = " + (a - b)); // a-b = 10
System.out.println("x + y = " + (x + y)); // x+y = welcomejava
System.out.println("a * b = " + (a * b)); // a*b = 200
System.out.println("a / b = " + (a / b)); // a/b = 2
System.out.println("a % b = " + (a % b)); // a%b = 0
}
}
Relational Operator
• > greater than
• >= greater than or equal to
• < less than
• <= less than or equal to
• == equal to
• != not equal to

• The outcome of these operations is a boolean value.


• = = , != can be applied to any type in java.
• Only numeric types are compared using ordering operator.
class Relopr
{
public static void main(String args[])
{
int a, b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(a>b)
System.out.println(a+ " is greater than " +b);
if(a>=b)
System.out.println(a+ " is greater than equal" +b);
if(a<b)
System.out.println(a+ " is less than " +b);
if(a<=b)
System.out.println(a+ " is less than equal" +b);
if(a==b)
System.out.println(a+ " is equal to " +b);
if(a!=b)
System.out.println(a+ " is not equal to " +b);
}
}
Logical Operator
 These operators are used to perform “logical AND” and “logical OR” operation i.e. the function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision.
 The logical boolean operators &&, || and ! operates in the same way that they operate on the bits of
integer.
(10!=10) && (5==5) &&  both true then o/p true
||  both false then o/p false
class Logopr
{
public static void main(String args[])
{
int a, b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);

if((a>b)&&(a>c))
System.out.println(a + " the greatest number among all");
if((a>b)||(a>c))
System.out.println(b + " may be the greatest number among all");
if(!(a>b)&&(a>c))
System.out.println(c + " may be the greatest number among all");
}
}
Bitwise operator
A=0011 1100 B=0000 1101
Output:
public class BitWise {
public static void main(String args[]) 7 ~ operation:
{ 4 a=6 0000 0110
int a=6; 3 Filp bits 1111 1001(1)
int b=5; -7 -7 in 2’s complement form
System.out.println(a|b); 24 7 0000 0111
System.out.println(a&b); 1 Flip bits 1111 1000
System.out.println(a^b); Add 1 1111 1001 (2)
System.out.println(~a); (1),(2) are same
System.out.println(a<<2);
System.out.println(a>>2);
<< operation:
}
a=6 0000 0110
}
a<<1 0000 1100  12
a<<2 0001 1000  24

>> operation:
a=6 0000 0110
a>>1 0000 0011  3
a>>2 0000 0001  1
Unary operator
• The increment and decrement operators are arithmetic and operate on one operand
• The increment operator (++) adds one to its operand
• The decrement operator (--) subtracts one from its operand
• The statement count++;
• is functionally equivalent to count = count + 1;
• If count currently contains 45, then the statement
total = count++;
assigns 45 to total and 46 to count
• If count currently contains 45, then the statement
total = ++count;
assigns the value 46 to both total and count
Assignment operator
• The right hand side of an assignment operator can be a complex expression

• The entire right-hand expression is evaluated first, then the result is combined with the original
variable

• There are many assignment operators, including the following:


Ternary / Conditional operator
• The conditional operator is similar to an if-else statement, except that it forms an expression that
returns a value
• For example:
larger = ((num1 > num2) ? num1 : num2);
• If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to
larger
• The conditional operator is ternary because it requires three operands
class Oprt
{
public static void main(String args[])
{
int a, b, m;
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
System.out.println("the value of a is " +a);
System.out.println("the value of b is " +b);
m= (a>b)? a:b;
System.out.println(m + " is larest number between " +a + " "+ b);
}
}

You might also like