Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.

Slides:



Advertisements
Similar presentations
Basic Java Constructs and Data Types – Nuts and Bolts
Advertisements

The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
1 pritisajja.info Unlocking the World of Java Programming….. Priti Srinivas Sajja February, 2014 Visit pritisajja.info for detail Future Technology for.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
INHERITANCE BASICS Reusability is achieved by INHERITANCE
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
CS1010 Programming Methodology
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2: Object Oriented Programming I
Road Map Introduction to object oriented programming. Classes
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
* * 0 Chapter 6 Java Methods. * * 0 Method Syntax [access specifier][qualifier] return type method name(argument list) Access specifier public – method.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
JAVA—Bitwise. Compiling/Executing a Java Application Source Code Java Compiler ByteCode > Java Interpreter Machine Code >
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming Language Lecture27- An Introduction.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Topic: Classes and Objects
Chapter 7 User-Defined Methods.
Java Primer 1: Types, Classes and Operators
Road Map Introduction to object oriented programming. Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Group Status Project Status.
Recap Week 2 and 3.
Object Oriented Programming in java
Java Programming Language
Names of variables, functions, classes
Corresponds with Chapter 5
Presentation transcript:

Core Java Lecture 4-5

What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java Shift Operators (>>, >>) Use of final keyword in Java

Methods Fulfills the operational responsibilities of the class. Handles Operation part of Class Partial General Syntax [static][final] method-name(,…. ) { ……………………………. …………………………….. } BODY OF METHOD  public, protected, private or default package private

Method Components Method-Name Return Type Signatures[Type & Number of Parameters] Scope Examples: 1.public void display()  Signature: (), Return Type: void, Scope : public 2.private int show()  Signature: (), Return Type: int, Scope : private 3.intsum(int x, int y)  Signature: (int,int), Return Type: int, Scope : default 4.float computeSum(double a, char b, int c)  Signature : (double,char, int) Return Type : float, Scope default

Method Example 1 class Test { public static double sum(double a, double b) { return (a+b); }// End of sum public static void main(String x[]) { double d = sum(10.6,4.5); System.out.println(d); System.out.println(sum(20,10)); }// End of main }// End of Test Class Call to sum Method from main() Method

Method OverLoading Two Methods in the Same Class are said to be overloaded if and only if they have same name BUT Different Signature Overloaded Methods may have same return type or different return type Overloaded Methods may have same return scope or different scope

Method Overloading Examples 1.voidsum(int a, int b) 2.intsum(float a, float b) 3.floatsum(double a, double b) 4.floatsum(int x, float y) 5.voidsum(float a, int b) SIGNATURES (int,int) (float,float) (int,float) (float,int) (double,double)

class Test { public static double sum( double a, double b) { System.out.println("Sum: Double Double Called"); return (a+b); }// End of sum public static int sum( int a, int b) { System.out.println("Sum: int int Called"); return (a+b); }// End of sum public static void main(String x[]) { System.out.println(sum(20,10)); System.out.println(sum(20.5,10.7)); System.out.println(sum(20.5f,10)); System.out.println(sum(20.0,10)); byte b = 10; short s = 8; System.out.println(sum(b,s)); }// End of main }// End of class Test Sum: int int Called 30 Sum: Double Double Called 31.2 Sum: Double Double Called 30.5 Sum: Double Double Called 30.0 Sum: int int Called 18

class Test { public static double sum( double a, float b) { System.out.println("Sum: Double Float Called"); return (a+b); }// End of sum public static double sum( float a, double b) { System.out.println("Sum: Float Double Called"); return (a+b); }// End of sum public static void main(String x[]) { System.out.println(sum(20.5,10.5f)); System.out.println(sum(20.5f,10.7)); System.out.println(sum(20.0,10)); }// End of main }// End of class Test Sum: Double Float Called 31.0 Sum: Float Double Called 31.2 Sum: Double Float Called 30.0

class Test { public static double sum( double a, float b) { System.out.println("Sum: Double Float Called"); return (a+b); }// End of sum public static double sum( float a, double b) { System.out.println("Sum: Float Double Called"); return (a+b); }// End of sum public static void main(String x[]) { System.out.println(sum(5.6f,4.5f)); System.out.println(sum(5.6,4.5)); }// End of main }// End of class Test Test.java:15: error: reference to sum is ambiguous, both method sum(double,floa ) in Test and method sum(float,double) in Test match System.out.println(sum(20.5f,10.7f)); ^ Test.java:16: error: no suitable method found for sum(double,double) System.out.println(sum(20.0,10.5)); ^ method Test.sum(float,double) is not applicable (actual argument double cannot be converted to float by method invocation conversion) method Test.sum(double,float) is not applicable (actual argument double cannot be converted to float by method invocation conversion) 2 errors

Scope and Life Time of Variables 1.Block scope 2.Method Scope // Test.java class Test { intx; public static void main(String args[]) { int y = 0; { int y1 =10; System.out.println(y); System.out.println(y1); } }// End of main() Method }// End of class block {}

Example 1 Method Variables and Block Variables class Test { intx; public static void main(String args[]) { int y = 0; // BLOCK 1 { int y1 =10; System.out.println(y); System.out.println(y1); } // BLOCK 2 { int y1 =100; System.out.println(y); System.out.println(y1); } }// End of main() Method }// End of class

Example 2 Method Variables and Block Variables class Test { intx; public static void main(String args[]) { int y1 = 0; // BLOCK 1 { int y1 =10; System.out.println(y); System.out.println(y1); } // BLOCK 2 { int y1 =100; System.out.println(y); System.out.println(y1); } }// End of main() Method }// End of class Test.java:8: error: y1 is already defined in main(String[]) int y1 =10; Test.java:9: error: cannot find symbol System.out.println(y); symbol: variable y location: class Test Test.java:13: error: y1 is already defined in main(String[]) int y1 =100; Test.java:14: error: cannot find symbol System.out.println(y); symbol: variable y location: class Test 4 errors

Example 3 Method Variables and Block Variables class Test { intx; public static void main(String args[]) { int y = 0; // BLOCK 1 { int y1 =10; System.out.println(y); System.out.println(y1); }// End of Block System.out.println(y1); }// End of main() Method }// End of class C:\Program Files\Java\jdk1.7.0\bin>javac Test.java Test.java:12: error: cannot find symbol System.out.println(y1); ^ symbol: variable y1 location: class Test 1 error

Command Line Arguments General Form of main public static void main(String[] args) String array[] is used to store command line arguments that are passed when program is being executed Assume Name of Source Java file is Test.java and name of Driver class is Driver java Driver  No command line arguments. args.length = 0

Command Line Arguments cont… If Execution is as follows: java Driver Hello I am fine args.length = 6 [Number of Arguments Passed] args[0] = “Hello” args[1] = “I”; args[2] = “am” ….. and so on

Converts String to int if String contains an integer in String form Exercise Print prime numbers from the list of numbers passed as command Line arguments class commandPrime { public static void main(String x[ ]) { for(int i=0; i<x.length;i++) { int number = Integer.parseInt(x[i]); boolean flag = true; for (int j=2; j< number/2 ;j++) { if( number % j ==0) { flag = false; break; } } // End of inner for if(flag) System.out.println(" "+number); } // End of outer for } // End of main } // End of CommandPrime String[ ] x

Tutorial Q1…… Running of CommandPrime D:\java\bin>java commandPrime D:\java\bin>java commandPrime x y Exception in thread "main" java.lang.NumberFormatException: For input string: "x “ at java.lang.NumberFormatException. forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at commandPrime.main(prime.java:9) D:\java\bin>java commandPrime x y 13 Exception in thread "main" java.lang.NumberFormatException: For input string: "x"at java.lang.NumberFormatException.forInputString (NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at commandPrime.main(prime.java:9)

There are Four different uses of static keyword in java. 1.static instance variables 2.static methods 3.static classes 4.static blocks Use of static keyword in Java Note : static field/methods of a class can be accessed/referenced even without creating the objects of that class [ Provided They are not static]. Syntax :. OR.

static instance variables/fields Static field/instance variables are allocated space in the heap area. Static field is just like a global variable for a class that is allocated memory once and all objects of that class share that common copy. For a static fields of any class, all the objects of that class share a common copy. Declaring an instance field as static makes it class variable that belongs to a whole class not an individual object. Any Field/Attribute/instance field of a class can be declared as static.

Example (Static Fields) class circle { static double PI= ; double radius; double area() { return PI * radius * radius; } double perimeter() { return 2*PI*radius; } } // End of circle class Static Member Non-static instance field circle c1 = new circle(); circle c2 = new circle(); c1c2 radius PI = Memory Map

Example (Static Fields) class A { static int a = 10; double b, c; ………. } A a1 = new A(); A a2 = new A(); Memory Map a1 a2 bc bc a=10

Static Methods static methods can use only static data static methods can be called/accessed/referenced even without creating the objects that class. Syntax. static method can not call non static methods. Examples: Math.sqrt (all math functions) Static method can declare local variables but from outside it can access only static data(fields/methods)

class num { int a,b,c; static int d = 10; static double e = 20.56; num(int a,int b,int c) { this.a = a; this.b =b; this.c =c; } static int sum(int a1, int b1) { // System.out.println(“a=”+a+”b=”+b+”c=”+c); System.out.println(“d=”+d+”e=”+e); return 40; } static Method Example a,b,c are non static fields and can not be accessed from a static method non static instance fields static instance fields static method

static double sum(double a, double b) { System.out.println(“d=”+d+”e=”+e); return 40.56; } static void pr() { System.out.println(“This is method pr”); } void print() { System.out.println(“This is method print”); pr(); //  call to static method from a non static method ----  Vaild System.out.println(“a=”+a+”b=”+b+”c=”+c); System.out.println(“d=”+d+”e=”+e); }

class BOX { private double l,b,h;// Instance Fields BOX(double a,double b,double c) { l=a;this.b=b;h=c;}// Constructor boolean isEqual(BOX other) { if (this.l == other.l && this.b == other.b && this.h == other.h) return true; else return false; } static boolean isEqual(BOX b1, BOX b2) { if (b1.l == b2.l && b1.b == b2.b && b1.h == b2.h) return true; else return false; } } // End of BOX class

class statictest { public static void main(String args[]) { BOX b1 = new BOX(10,6,8); BOX b2 = new BOX(10,6,8); BOX b3 = new BOX(1,16,18); BOX b4 = new BOX(2,6,8); System.out.println(b1.isEqual(b2)); System.out.println(BOX.isEqual(b1,b2)); System.out.println(b3.isEqual(b1,b2)); System.out.println(b4.isEqual(b2)); System.out.println(b4.isEqual(b4,b2)); } } D:\Java1>java statictest true false

Explain How You view the Following class // Test.java class A { privateinta,b,c; private static intd=10; public void show()// An Instance Method { System.out.println("a="+a+"b="+b+"c="+c+"d="+d); System.out.println("a="+this.a+"b="+this.b+"c="+this.c+"d="+A.d); //System.out.println("a="+this.a+"b="+this.b+"c="+this.c+"d="+this.d); display();//A.display(); Call to a static method from non-static method }// End of show() Method public static void display() { //System.out.println("a="+a+"b="+b+"c="+c+"d="+d); A a1 = new A(); System.out.println("a="+a1.a+"b="+a1.b+"c="+a1.c+"d="+a1.d); }// End of display() Method }// End of class A

class Test { public static void main(String args[]) { // What features of class A can be accessed here and How? A a1 = new A(); A a2 = new A(); // System.out.println(a1.a); a1.show(); A.display(); a1.display(); }// End of main() Method }// End of class Test

Use >>, >> Operators >> Right Shift Operator [Preserve Sign Bit] << Left Shift [ Left Shift via SignBit] >>> Unsigned Right Shift [ Fill 0 to Sign bit for each move]

Right Shift [>>] Each Right Shift will divide the number by 2 Preserve the Sign Bit Syntax : num >> k ; Where k is number of positions shifted. k = k % 32 ( if num is int, char, short or byte type) K = k % 64 (if num is long type)

Left Shift [<<] Each Left Shift will multiply the number by 2 May Change the Sign bit [ If Sign bit occurs then overflow has occurred] Syntax : num << k ; Where k is number of positions shifted. k = k % 32 ( if num is int, char, short or byte type) K = k % 64 (if num is long type)

Unsigned Right Shift [>>>] Each Right Shift will fill 0 in the sign bit and then number is shifted along with sign bit. If number is +ive then both >> & >>> will work the same way Negative numbers sign will change and also its value after single right shift. For int type after 32 shifting 0 will be filled in all places. Syntax : num >>> k ; Where k is number of positions shifted. k = k % 32 ( if num is int, char, short or byte type) K = k % 64 (if num is long type)