java Basic Programming Needs
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

java Basic Programming Needs

  • 1,820 views
Uploaded on

Presented By: ...

Presented By:
N.V.Raja Sekhar Reddy
www.technolamp.co.in

Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar

More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,820
On Slideshare
936
From Embeds
884
Number of Embeds
5

Actions

Shares
Downloads
33
Comments
0
Likes
0

Embeds 884

http://www.technolamp.co.in 856
http://technolamp.blogspot.in 18
http://feeds.feedburner.com 7
http://technolamp.blogspot.com 2
http://7283324474396191425_8a1362deeadb93e945419505c66c8dcbc5e1cbbf.blogspot.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Java Session 4
  • 2. Contents…Data TypesType Conversion and CastingVariablesScope and lifetime of variablesOperatorsExpressionsControl Statements
  • 3. DATA TYPES• Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.• Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory
  • 4. DATA TYPES
  • 5. Data Types• There are two data types available in Java: Primitive Data Types Reference/Object Data Typesbyte:Byte data type is a 8-bit signed two.s complement integer.Minimum value is -128 (-2^7)Maximum value is 127 (inclusive)(2^7 -1)Default value is 0Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.Example : byte a = 100 , byte b = -50
  • 6. short:Short data type is a 16-bit signed twos complement integer.Minimum value is -32,768 (-2^15)Maximum value is 32,767(inclusive) (2^15 -1)Default value is 0.Example : short s= 10000 , short r = -20000
  • 7. int:Int data type is a 32-bit signed twos complement integer.Minimum value is - 2,147,483,648.(-2^31)Maximum value is 2,147,483,647(inclusive).(2^31 -1)Int is generally used as the default data type for integral values unless there is a concern about memory.The default value is 0.Example : int a = 100000, int b = -200000long:Long data type is a 64-bit signed twos complement integer.Minimum value is -9,223,372,036,854,775,808.(-2^63)Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 - 1)This type is used when a wider range than int is needed.Default value is 0L.Example : int a = 100000L, int b = -200000L
  • 8. float:Float data type is a single-precision 32-bit IEEE 754 floating point.Float is mainly used to save memory in large arrays of floating point numbers.Default value is 0.0f.Float data type is never used for precise values such as currency.Example : float f1 = 234.5fdouble:double data type is a double-precision 64-bit IEEE 754 floating point.This data type is generally used as the default data type for decimal values. generally the default choice.Double data type should never be used for precise values such as currency.Default value is 0.0d.Example : double d1 = 123.4
  • 9. boolean:boolean data type represents one bit of information.There are only two possible values : true and false.This data type is used for simple flags that track true/false conditions.Default value is false.Example : boolean one = truechar:char data type is a single 16-bit Unicode character.Minimum value is u0000 (or 0).Maximum value is uffff (or 65,535 inclusive).Char data type is used to store any character.Example . char letterA =A
  • 10. Reference Datatypes• Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.• Class objects, and various type of array variables come under reference data type.• Default value of any reference variable is null.• A reference variable can be used to refer to any object of the declared type or any compatible type.• Example : Animal animal = new Animal("giraffe");
  • 11. Data TypesDataType Memory (Bytes) Rangebyte 1 -128 to 127short 2 -32768 t0 32767int 4 -2147483648 to 2147483647long 8 -922337263685477808 to -922337263685477807float 4 1.4e-045 to 3.4e+038double 8 4.9e-324 to 1.8e+308char 2 0 to 65536boolean - True/False
  • 12. TYPE CONVERSION Size Direction of Data Type  Widening Type Conversion (Casting down)  Smaller Data Type  Larger Data Type  Narrowing Type Conversion (Casting up)  Larger Data Type  Smaller Data Type Conversion done in two ways  Implicit type conversion  Carried out by compiler automatically  Explicit type conversion  Carried out by programmer using casting
  • 13. Type Conversion Widening Type Converstion  Implicit conversion by compiler automatically byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double
  • 14. Type Conversion Narrowing Type Conversion  Programmer should describe the conversion explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
  • 15. Type Casting• General form: (targetType) value Examples: 1) integer value will be reduced module bytes range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f;
  • 16. VARIABLES• type identifier [ = value][, identifier [= value] ...] ;• Here are several examples of variable declarations of various types 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.
  • 17. Types of variablesThere are three kinds of variables in Java: Local variables Instance variables Class/static variablesLocal variables are declared in methods, constructors, or blocksInstance variables are declared in a class, but outside a method, constructor or any block.Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • 18. Variable Scope
  • 19. Scope DefinitionA scope is defined by a block: { … }A variable declared inside the scope is not visible outside: { int n; } n = 1;
  • 20. Example: Variable Scopeclass Scope { public static void main(String args[]) { int x; x = 10; if (x == 10) { int y = 20; System.out.println("x and y: " + x + “ " + y); x = y * 2; } System.out.println("x is " + x + “y is” + y); }}
  • 21. Variable LifetimeVariables are created when their scope is entered by control flow anddestroyed when their scope is left:1) A variable declared in a method will not hold its value between different invocations of this method.2) A variable declared in a block looses its value when the block is left.3) Initialized in a block, a variable will be re-initialized with every re-entry.Variables lifetime is confined to its scope!
  • 22. Example: Variable Lifetimeclass LifeTime { public static void main(String args[]) { int x; for (x = 0; x < 3; x++) { int y = -1; System.out.println("y is: " + y); y = 100; System.out.println("y is now: " + y); } }}
  • 23. OPERATOR TYPES• Java operators are used to build value expressions.• Java provides a rich set of operators: 1) arithmetic (+,-,*,/,%) 2) assignment (+=,-=,*=,/=,%=,=) 3) relational (==,!=,<,>,<=,>=) 4) logical (&&,||,!) 5) bitwise (&,|,~,^,<<,>>,>>)
  • 24. Bit wise operators~ ~op Inverts all bits& op1 & op2 Produces 1 bit if both operands are 1| op1 |op2 Produces 1 bit if either operand is 1^ op1 ^ op2 Produces 1 bit if exactly one operand is 1>> op1 >> op2 Shifts all bits in op1 right by the value of op2<< op1 << op2 Shifts all bits in op1 left by the value of op2
  • 25. Other Operators?: shortcut if-else statement[] used to declare arrays, create arrays, access array elements . used to form qualified names(params) delimits a comma-separated list of parameters(type) casts a value to the specified typenew creates a new object or a new arrayinstanceof determines if its first operand is an instance of the second
  • 26. Table: Operator Precedencehighest() [] .++ -- ~ !* / %+ ->> >>> <<> >= < <=== !=&^|&&||?:= op=lowest
  • 27. Expressions• An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.• Examples of expressions are in bold below: int number = 0; anArray[0] = 100; System.out.println ("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2");
  • 28. CONTROL STATEMENTS• Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program.• Control statements are divided into three groups:1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression2) iteration statements enable program execution to repeat one or more statements3) jump statements enable your program to execute in a non-linear fashion
  • 29. Selection Statements• Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time.• Java provides four selection statements: 1) if 2) if-else 3) if-else-if 4) switch
  • 30. Iteration Statements• Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true.• Java provides three iteration statements: 1) while 2) do-while 3) for 4) for each(JDK1.5 version)
  • 31. • if-elseSyntax Exampleif (<condition-1>) { int a = 10; // logic for true condition-1 goes here if (a < 10 ) {} else if (<condition-2>) { System.out.println(“Less than 10”); // logic for true condition-2 goes here } else if (a > 10) {} else { System.out.pritln(“Greater than 10”); // if no condition is met, control } else {comes here System.out.println(“Equal to 10”);} } Result: Equal to 10s
  • 32. • switchSyntax Exampleswitch (<value>) { int a = 10; case <a>: switch (a) { // stmt-1 case 1: break; System.out.println(“1”); case <b>: break; //stmt-2 case 10: break; System.out.println(“10”); default: break; //stmt-3 default: System.out.println(“None”); Result: 10
  • 33. • do-while Syntax Example do { int i = 0; // stmt-1 do { } while (<condition>); System.out.println(“In do”); i++; } while ( i < 10); Result: Prints “In do” 11 times• while Syntax Example while (<condition>) { int i = 0; //stmt while ( i < 10 ) { } System.out.println(“In while”); i++; } Result: “In while” 10 times
  • 34. • for Syntax Example for ( initialize; condition; expression) for (int i = 0; i < 10; i++) { { // stmt System.out.println(“In for”); } } Result: Prints “In do” 10 times
  • 35. Jump Statements• Java jump statements enable transfer of control to other parts of program.• Java provides three jump statements: 1) break (3 uses:loop,switch,nested blocks) 2) continue 3) return• In addition, Java supports exception handling that can also alter the control flow of a program.
  • 36. TESTI m not giving the answers for these basic questions,please try and execute if possible. If you still want the answersthen copy and paste the entire question in google .
  • 37. What all gets printed when the following program is compiled and run. Select the two correct answers. public class test { public static void main(String args[]) { int i, j=1; i = (j>1)?2:1; switch(i) { case 0: System.out.println(0); break; case 1: System.out.println(1); case 2: System.out.println(2); break; case 3: System.out.println(3); break; } }} a) 0 b) 1 c) 2 d) 3
  • 38. Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer.a) public static void main(String args[])b) public static void MAIN(String args[])c) public static void main(String args)d) public static void main(char args[])e) static public void main(String args[])f) public static int main(char args[])
  • 39. Which of the following will compile without error1) import java.awt.*; package Mypackage; class Myclass {}2) package MyPackage; import java.awt.*; class MyClass{}3) /*This is a comment */ package MyPackage; import java.awt.*; class MyClass{}
  • 40. What’s the difference betweenconstructors and normal methods?Constructors must have the same nameas the class and can not return a value.They are only called oncewhile regular methods could be called manytimes and it can return a value or can bevoid.
  • 41. • Give a simplest way to find out the time a method takes for execution without using any profiling tool? long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println (“Time taken for execution is ” + (end – start));
  • 42. public class test { public static void main(String args[]) { String s1 = "abc"; String s2 = "abc"; if(s1 == s2) System.out.println(1); else System.out.println(2); if(s1.equals(s2)) System.out.println(3); else System.out.println(4);}}a)1b)2c)3d)4
  • 43. • Which of the following are legal array declarations. Select the three correct answers.a) int i[5][];b) int i[][];c) int []i[];d) int i[5][5];e) int[][] a;
  • 44. What is the range of values that can be specified for an int. Select the one correct answer. The range of values is compiler dependent.a) -231 to 231 - 1b) -231-1 to 231c) -215 to 215 - 1d) -215-1 to 215
  • 45. What would be the results of compiling and running the following class. Select the one correct answer. class test { public static void main() { System.out.println("test"); } }a)The program does not compile as there is no main method defined.b)The program compiles and runs generating an output of "test"c)The program compiles and runs but does not generate any output.d)The program compiles but does not run.
  • 46. What gets printed when the following program is compiled and run. Select the one correct answer.class test { public static void main(String args[]) { int i,j,k,l=0; k = l++; j = ++k; i = j++; System.out.println(i); }} a) 0 b) 1 c) 2 d) 3
  • 47. • Which operator is used to perform bitwise inversion in Java. Select the one correct answer. a) ~ b) ! c) & d)| e) ^
  • 48. What gets printed when the following program is compiled and run. Select the one correct answer.public class test { public static void main(String args[]) { byte x = 3; x = (byte)~x; System.out.println(x); }} a) 3 b) 0 c) 1 d) 11 e) 252 f) 214 g) 124 h) -4
  • 49. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.public class test { public static void main(String args[]) { int x,y; x = 3 & 5; y = 3 | 5; System.out.println(x + " " + y); }} a) 7 1 b) 3 7 c) 1 7 d) 3 1 e) 1 3 f) 7 3 g) 7 5
  • 50. What all gets printed when the following program is compiled and run. Select the one correct answer.public class test { public static void main(String args[]) { int i=0, j=2; do { i=++i; j--; } while(j>0);System.out.println(i);}}a) 0b) 1c) 2d) The program does not compile because of statement "i=++i;"
  • 51. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.public class test { public static void main(String args[]) { int x, y; x = 5 >> 2; y = x >>> 2; System.out.println(y); }} a) 5 b) 2 c) 80 d) 0 e) 64
  • 52. Thank You