java oops and java very important for .pptx

cherukuriyuvaraju9 39 views 117 slides Jun 06, 2024
Slide 1
Slide 1 of 117
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117

About This Presentation

ava oops and java very important for .pptx


Slide Content

Compiler Vs Interpreter Compiler It reads the entire program and converts it into the object code It shows errors of the entire program It links different code files into a runnable program(know as exe) Only error free programs are executed, once compiled, executed any no. of times Interpreter It reads only one line of a source code at a time and converts it into object code In case of errors the same will be indicated instantly No linking of files or machine code generation Need to execute every time

Programming Languages: Historically, we divide high level languages into two groups: – Procedural languages – Object-Oriented languages (OOP) POP OOP Top down approach Large program is divided into functions No access specifiers / modifiers There is no provision of inheritance Global data is shared among the functions in the program There is no proper way of hiding the data, so data is insecure Example: C, VB, FORTRAN, PASCAL Bottom up approach Entire program is divided into objects Access specifiers- public, private, protected Inheritance achieved in 5 modes as above Data is shared among the objects through the member functions Data is hidden in three modes public, private, and protected. hence data security increases Example: C++, JAVA, VB.NET, C#.NET

Principles of OOPS It is necessary to understand some of the concepts used extensively in object-oriented programming. These include: 1. Object 2. Class 3. Abstraction 4. Encapsulation 5. Inheritance 6. Polymorphism 7.Dynamic / Late binding 8. Message passing

Principles of OOPS 1. Class: A class is an entity that determines how an object will behave and what the object will contain Blue print / prototype / idea that object follows We can create as many objects as we like from the same class and then give each object its own set of properties Ex: student  name, rollno, dob read(), write(), play() A class defines the base structure, properties, and behavior of its instances

Principles of OOPS 2. Object: Real time entity(runtime entity) The object is an instance of a class An object is a real-world entity An object has state and behavior When a class is defined, no memory is allocated but when it is instantiated, memory is allocated Properties and tasks performed by object Ex: human  name, color, height etc.. read(), write(), walk(), run() etc…

Classes and Instances Class is the blueprint of a concept Instance is the actualization of the blueprint A class defines the base structure, properties, and behavior of its instances

Principles of OOPS 3. Abstraction: Showing only essential parts, Hiding the implementation / background details Exposing the essential details of an entity, while ignoring the irrelevant details, to reduce the complexity for the users Ex1: when you drive your car you do not have to be concerned with the exact internal working of your car. What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Here the knowledge you have of your car is abstract. Ex2: android application -> . apk and .exe There are two ways to achieve abstraction in java: Abstract class (0 to 100%) & Interface (100%)

Principles of OOPS 4. Encapsulation: Wrapping data and methods within single entity(classes) Bundling data and operations on the data together in an entity class  Name Variables Methods student Name, roll no, dob Read(), write(), play() Ex: Capsule which is mixed of several medicines

Principles of OOPS 5. Inheritance: one object acquires the properties and behaviors of the other object Derive a new type from an existing type, thereby establishing a parent-child relationship super / parent / base class to sub / child / derived class Types  single, multi level, hierarchical, multiple, hybrid

Principles of OOPS 6. Polymorphism: Ability to exist in more than one form Performing same task (method) in different ways Ex: drawpolygon()  square(), triangle(), rectangle() method overloading (compile time polymorphism) method overriding (run time polymorphism)

Principles of OOPS 7. Dynamic / Late binding: Linking of a procedure call to the code to be executed (or) method call & method function Connecting one program to another program that is to be executed in reply to the call When compiler is not able to resolve the call / binding at compile time, such binding is known as Dynamic or late Binding Method overriding is an example of dynamic binding as in overriding both parent and child classes have same method and in this case the type of the object determines which method is to be executed. The type of object is determined at the run time so this is known as dynamic binding

Principles of OOPS 8. Message passing: Communication between different threads within a process, different processes running on same node, different processes running on different nodes Sender / source process sends a message to receiver / destination process Types of communication links one-one, one-many, many-one, many-many

Advantages of OOPS Simple, clear and easy to maintain structure

Advantages of OOPs Enhances program modularity since each object exists independently

Advantages of OOPs New features can be easily added without disturbing the existing one

Advantages of OOPs Reusability (inheritance)

Advantages of OOPs Allows designing and developing safe programs using the data hiding

Advantages of OOPs Easy to partition the work in a project based on objects.

Advantages of OOPs Object-oriented system can be easily upgraded from small to large system

Applications of OOPs: 1. Mobile Applications: Android app development 2. Web Applications: By using internet we can use the web applications. All e-commerce applications, insurance, education, railway etc.… 3. Software Tools: Eclipse, netbeans 4. J2ME Apps: Nokia phones used J2ME apps which are designed using java programming language

5. Desktop GUI Applications: Acrobat reader , media player , antivirus, etc … 6. Enterprise Applications: banking applications 7. Client-Server Systems: Object-oriented Client-Server Systems provide the IT infrastructure (OS, Networks, Hardware), creating object-oriented Client-Server Internet (OCSI) applications. OCSI consist of three major technologies The Client Server Object Oriented Programming The Internet Scientific Applications, Embedded Systems, Web Servers and Application Servers, Robotics, Games, Real-time systems, Simulation and modelling, AI and Expert systems, Neural networks and parallel programming, Decision support and office automation systems etc …

C Vs Java S. No C Java 1 C was developed by Dennis M. Ritchie in 1972 Java was developed by James Gosling in 1995 2 C a procedural Programming language Java is object oriented language 3 It supports preprocessors and pointers It doesn’t support preprocessors and pointers 4 It supports structure and union It doesn’t support structure and union 5 Memory allocation can be done by malloc Memory allocation can be done by a new keyword 6 C supports Call by value and call by reference Java supports call by value only 7 C is platform dependent Java is a platform independent 8 Exception handling cannot be directly achieved in C Exception Handling is supported in Java 9 It has 32 keywords It has 50 keywords 10 Default members of C are public Default members of Java are private

C++ Vs Java S. No C++ Java 1 C++ was developed by Bjarne Stroustrup in 1979 Java was developed by James Gosling in 1995 2 C++ is not a purely object oriented language, since it is possible to write C++ programs without using a class or object Java is purely an object oriented language, since it is not possible to write java programs without using atleast one class 3 It is platform dependent It is platform independent 4 Allocating and deallocating of memory is responsible responsibility of the programmer Allocating and deallocating of memory will be taken care of JVM 5 Supports Multiple inheritance in C++ Doesn’t support multiple inheritance in java, but we can achieve this by interfaces 6 There are constructors and destructors in C++ Only constructors are available in C++ 7 There are 3 access specifiers in C++ i.e., private, public and protected There are 4 access specifiers in java i.e., private, public, protected and default 8 It has 52 keywords It has 50 keywords 9 Uses new and delete for storage allocation Uses garbage collector for storage allocation 10 Uses compiler only Uses compiler and interpreter 11 It supports call by value and call by reference It supports call by value only

C Vs C++ Vs Java C C++ Java #include< stdio.h > void main() { printf(“Hai”); } #include< iostream.h > void main() { cout <<“Hai”; } class Test { public static void main(String args[]) { System.out.println (“Hai”); } } Predefined support is in the form of header files Predefined support is header files Predefined support is in the form of packages. Here string & system are two classes comes under java.lang package Header file contains functions Header file contains functions import contains all packages Execution can be done by OS Execution can be done by OS Execution can be done by JVM

History / Evolution / Origin of Java Java is a general purpose object oriented programming language Initially sun microsystems got one project to develop a software for electronic devices like TVs that should be operated by remote This project is known as Stealth project later renamed as Green project James Gosling, Patrick Naughton and Mike Sheridan was developed this project at Sun Microsystems in 1991 Initially it was called as " Greentalk " with the file extension of . gt after that it was called Oak and finally it was renamed with Java in 1995   Now java was under oracle from 2010 Later it was changed to www (web applications)

History of Java

Java platforms / editions Java 2 Standard Edition (J2SE): J2SE can be used to develop client-side standalone applications or applets It includes Java programming APIs such as java.lang , java.io, java.net, java.util , java.sql , java.math etc… It includes core topics like OOPs, string, Exception, Inner classes, AWT, I/O Stream, Multithreading, Networking, Swing, Reflection, Collection, etc… Java 2 Enterprise Edition (J2EE) Used to develop web services, enterprise applications, networking, client-server applications It covers advanced topics of java like Servlet, JSP, Web Services, EJB, JPA etc... Java 2 Micro Edition (J2ME): It is a micro platform which is mainly used to develop mobile applications Very small Java environment for smart cards, pages, phones and set-top boxes JavaFX : Used to develop rich internet applications & uses a light weight user interface API

Java Environment Development tools-part of java development kit (JDK) Classes and methods-part of Java Standard Library (JSL), also known as Application Programming Interface (API) JDK: i . Appletviewer ( for viewing applets) ii. Javac (Compiler) iii. Java (Interpreter) iv. Javap (Java disassembler) v. Javah (for C header files) vi. Javadoc ( for creating HTML description) vii. Jdb (Java Debugger)

Java Environment 2. Application Package Interface (API) Contains hundreds of classes and methods grouped into several functional packages: i . Language Support Package ii. Utility Packages iii. Input / Output Packages iv. Networking Packages v. AWT Package vi. Applet Package

Core java: It is central hub of any language It is class and object based language Android applications, selenium (tester), hadoop (big data developer), application development framework, magic framework, master data management, Darwin web app (SAP), openscript, cloud computing, salesforce etc…depends on java Advanced java, struct class, springs, web services, tools, design pattern etc…depends on java class test { variables, methods constructors, instance blocks elements static blocks }

Key Words: data types: byte, short, int, long, float, double, char, boolean 8 flow control: if, else, switch, case, break, default, for, while, do, continue 10 exception handling: try, catch, finally, throws, throw 5 object level: new, this, super, instanceof 4 methods: void, return 2 java5: enum, assert 2 un used: goto, const 2 source file: class, extends, interface, implements, package, import 6 modifiers: public, private, protected, final, static, abstract, synchronized, strictfp, 11 volatile, transient, native

Java Methods: instance method 12. public method static method 13. private method normal method 14. protected method abstract method 15. default method accessor method(getters) 16. instance factory method mutator method(setters) 17. static factory method overridden method 18. pattern method overriding method 19. synchronized method final method 20. non- synchronized method native method 21. in-line method strictfp method 22. call-back method

Java Classes: normal classes abstract classes final class strictfp class immutable class mutable class public class default class single ton class

Features of Java Platform Independent: Run on any environment (WORA)

Features of Java Portable: java program written on one environment and can be executed in another environment

Features of Java Object – oriented concepts: In Java, everything is an Object Java can be easily extended since it is based on the Object model Abstraction, Encapsulation, Inheritance, Polymorphism

Features of Java Simple: No concept of pointers, explicit memory allocation, structures etc… Secure: Secure for internet application Raise out boundary exception in arrays

Features of Java Robust: Early checking of errors Automatic Garbage collector Exception Handling

Features of Java Multithreading: Concurrent execution of several parts of same program at the same time Improve CPU utilization

Features of Java High Performance: With the use of Just-In-Time compilers, Java enables high performance

Features of Java: Distributed applications: software that runs on multiple computers connected to a network at the same time Java is designed for the distributed environment of the internet RMI(remote method invocation) EJB(enterprise java beans) Architectural neutral: Irrespective of architecture the memory allocated to the variables will not vary

Execution process of java program JDK provides an environment to develop, compile and execute a java application It is a combination of compiler and JRE (Java Runtime Environment) JVM is used to execute byte code of Java programs which makes Java platform independent Each operating system has different / their own JVM The output they produce after execution of byte code is same across all operating systems.  JIT compiler(Just In Time) is the subset of JVM which is used to enhance the performance of JVM

Execution process of java program

Structure of Java Program: documentation section  used to give the comments Single Line Comment  //comments Multi Line Comment  /* comments */ Documentation Comment  used to prepare documentation for a project /** comments */* (each line begins with *) 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 package statement  we can create our own user defined packages Ex: package student; interface statement  same as classes but it contains only method declarations and useful in order to implement multiple inheritance class definition  must write the entire logic in class only main method class  main() method should contain in one class main method definition

Sample Java Program: //sample program to print a content import java.lang .*; class SamplePgm { public static void main(String args []) { System.out.println (“Hello World”); } } 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 Method public static void main(String args []) Every one can access this method This method can be called without instantiating the class main method returns nothing Arguments to the main method(used as command line arguments) String class

Access Modifiers The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it There are four types of Java access modifiers: Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package Private: The access level of a private modifier is only within the class. It can’t be accessed from outside the class Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc… Access Modifier within class within package outside package by subclass only outside package Public Y Y Y Y Private Y N N N Protected Y Y Y N Default Y Y N N

Access Modifiers ( Cont …) Public: The public access modifier is accessible everywhere It has the widest scope among all other modifiers package pack;   public class A{      public void  msg () { System.out.println ("Hello"); }    }   package  mypack ;   import pack.*;   class B{     public static void main(String  args []){       A  obj  = new A();        obj.msg();       }   }   O/P: Hello

Access Modifiers ( Cont …) Private: The private access modifier is accessible only within the class If you make any class constructor private, you cannot create the instance of that class from outside the class Example: We have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error class A{   private  int  data=40;   private void  msg () { System.out.println ("Hello java"); }   }   public class Simple{     public static void main(String  args []){       A  obj =new A();       System.out.println ( obj.data ); //CT Error        obj.msg(); //Compile Time Error        }   }   class A{   private A(){} //private constructor    void  msg () { System.out.println ("Hello java");}   }   public class Simple{     public static void main(String  args []) {       A  obj =new A(); //Compile Time Error     }   }  

Access Modifiers ( Cont …) Protected: protected access modifier is accessible within package and outside the package but through inheritance only The protected access modifier can be applied on the data member, method and constructor but can't be applied on the class It provides more accessibility than the default modifier Example: We have created the two packages pack and mypack . The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance. package pack;   public class A {   protected void  msg () { System.out.println ("Hello"); }    }   package  mypack ;   import pack.*;   class B extends A{      public static void main(String  args []){       B  obj  = new B();       obj.msg();      }   }   O/P: Hello

Access Modifiers ( Cont …) Default: If you don't use any modifier, it is treated as default by default The default modifier is accessible only within package. It cannot be accessed from outside the package It provides more accessibility than private, but it is more restrictive than protected and public Example: We have created two packages pack and mypack . We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package In the above example, the scope of class A and its method msg () is default so it cannot be accessed from outside the package. package pack;   class A{     void  msg () { System.out.println ("Hello"); }    }   package  mypack ;   import pack.*;   class B{     public static void main(String  args []){       A  obj  = new A(); //CT Error        obj.msg(); //CT Error       }   }  

Naming Convention: The names should not be a keyword / Reserved word The name consists of alphabet (a-z), digit (0-9), underscore(_), dollor ($) Begin with alphabet (a-z, A-Z) / underscore(_) but not with digit (0-9) Variable, Object, Class and Method should follow the above rules Class: Name should begin with capital letter (single word) First letter of every word should begin with capital letter (multi) Ex: S tudent, B ranch N ame 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: r ead(), g et N ame(), n ext L ine

Data Types: Type of variable Memory space Range Primitive and non primitive data types Data type Size Default values Range byte 1 -128 to +127 ( -2 7 to +2 7 -1) short 2 -32768 to +32767 ( -2 15 to +2 15 -1 ) int 4 -2147483648 to +2147483647 ( -2 31 to +2 31 -1 ) long 8 -9223372036854775808 to +9223372036854775807 ( -2 63 to +2 63 -1 ) float 4 0.0f/F 3.4e-038 to 3.4e+038 (6 or 7 digits after decimal ) double 8 0.0 1.7e-308 to 1.7e+308 (14 or 15 digits after decimal ) char 2 blank space -32768 to +32767 ( -2 15 to +2 15 -1 ) boolean 1 bit False to 1

Variables are used to store values and the value of that variable may changed during program execution Variable is an alternate name given for the memory location Syntax: datatype variablename ; Variables: y is declared as float x is x is declared as integer as integer int x; float y; x=10 y=20.5

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

Variables: Ex: class Variable{ static int a=10; // static variable int c=30; // instance variable public static void main(String[] args) { int b=20; // local variable System.out.println (b); System.out.println (a); Variable obj =new Variable(); System.out.println ( obj.c ); } } o/p: 20 10 30

Scanner class functions: To read a single character, we use next(). charAt (0) Write a program to read and display name, gender, age, mobile number and cgpa using Scanner methods

Reading value to the variable from keyboard: import java.util.Scanner ; public class Sample { public static void main(String ar []) { int a; Scanner s = new Scanner(System.in); System.out.print ("Enter Value for a: "); a = s.nextInt (); System.out.println (“value of a is”+a ); } }

Identifiers: Identifiers are used for identification purpose. It can be a class name, method name, variable name or a label. Ex: public class Test { public static void main(String[] args) { int a = 20; } } In the above code, 5 identifiers are there : Test, main, String, args, a Rules for identifier construction Must not be a key word / reserved word Consists of a-z,A-Z,0-9,$,_ Should not start with digit Case sensitive No limit for length (4 – 15 letters are advisable)

Literals: Any constant value which can be assigned to the variable is called as literal / constant I nteger Literals Every literal is by default integer (32 bits) To specify a long literal, number should appended with an uppercase L or lowercase l 1. Decimal Literals (base 10) – Range is 0-9 Ex: 1, 2, 99 etc… 2. Octal Literals ( base 8) – Range is 0-7 Ex: 037 octal values are denoted in java by a leading 0 3. Hexa-decimal Literals ( base 16) – Range is 0-9, A-F(a-f) Ex: 0x/X35Ac hexadecimal values are denoted by leading 0x or 0X Floating point Literals Floating point literals are by default of type double To specify a float literal, we must append an F or f as suffix 1. Standard / Fractional Notation  3.14159, 0.6667, 2.0 etc…. 2. Scientific / Exponent Notation  m * b e 6.022 * 10 23 6.022E23, 2e+100, 3e-21 -6.022 * 10 23 -6.022E23,

Literals: Character Literals A literal character is represented inside a pair of single quotes Ex: ‘a’, ‘9’, ‘@’ and escape sequences like’\n’, ‘\t’ etc… String Literals Sequence of characters between a pair of double quotes String must begin and end on the same line Boolean Literals Two values  true and false True is not equal to 1 and false is not equal to 0 It can be assigned to variable declared as boolean Ex: boolean a=true;

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 Ternary Operator Logical Operators Bitwise Operators Unary Operators Assignment Operator Shift 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 Operators ( <, <=, >, >=, ==, != ) :  These operators are used to check for relations like equality, greater than, less than. They return Boolean result after the comparison. Only numeric types are compared using ordering operator The outcome of these operations is a boolean value = = , != can be applied to any type in java Ex: int done; if(!done) and if(done) // Valid in C /C++ but not in java if (done == 0) and if(done!=0) //Valid in Java

Conditional / Ternary Operator ( ?: ) Ternary operator is a shorthand version of if-else statement. It has three operands and hence the name ternary. The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value Syntax: (Expression / condition ? Statement-1 : Statement-2) Ex: (10==10) ? ”True” : ”False”

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. &&  both true then o/p true ||  both false then o/p false A B && || 1 1 1 1 1 1 1 1

Bitwise Operator ( &, |, ~, ^, >>, >>>, <<, <<< ): A=0011 1100 B=0000 1101

Bitwise Operator ( &, |, ~, ^, >>, >>>, << ): public class BitWise { public static void main(String[] args ) { int a=6; int b=5; System.out.println ( a|b ); System.out.println ( a&b ); System.out.println ( a^b ); System.out.println (~a); System.out.println (a<<2); System.out.println (a>>2); System.out.println (a>>>2); } } a= 6 a>>1 a>> 2 Output: 7 4 3 -7 24 1 1 ~ operation: a=6 0000 0110 Filp bits 1111 1001 (1) -7 in 2’s complement form 7 0000 0111 Flip bits 1111 1000 Add 1 1111 1001 (2) (1),(2) are same << 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 1 1 1 1 1

class RightShift { public static void main(String[] args ) { int x=2; int y=-2; System.out.println ("x<<2= "+(x<<2)); System.out.println ("x>>2= "+(x>>2)); System.out.println ("x>>>2= "+(x>>>2)); System.out.println ("y<<1= "+(y<<1)); System.out.println ("y>>1= "+(y>>1)); System.out.println ("y>>>1= "+(y>>>1)); }} x<<2= 8 x>>2= 0 x>>>2= 0 y<<1= -4 y>>1= -1 y>>>1= 2147483647 -2 :1111111111111110 y>>1:1111111111111111 -2 :1111111111111110 y>>>1:0111111111111111 >> arithmetic right shift >>> logical right shift Bitwise Operator ( &, |, ~, ^, >>, >>>, << ):

Unary Operators:  Unary operators need only one operand. They are used to increment, decrement or negate a value.– :Unary minus, used for negating the values. + :Unary plus, used for giving positive values. Only used when deliberately converting a negative value to positive. ++ :Increment operator, used for incrementing the value by 1. There are two varieties of increment operator. Post-Increment : Value is first used for computing the result and then incremented. Pre-Increment : Value is incremented first and then result is computed. — : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operator. Post-decrement : Value is first used for computing the result and then decremented. Pre-Decrement : Value is decremented first and then result is computed. Operators

Expressions: Expression consist of variables, operators, literals and method calls that evaluates to a single value Ex1: int score; score = 90; Here, score = 90 is an expression that returns int. Ex2: double a = 2.2, b = 3.4, result; result = a + b - 3.4; Here, result=a + b - 3.4 is an expression. Ex3: if (number1 == number2) System.out.println("Number 1 is larger than number 2"); Here, number1==number2 is an expression that returns Boolean. Similarly, "Number 1 is larger than number 2" is a string expression.

Precedence rules and Associativity: Operator precedence is used to determine the order of operators evaluated in an expression and it decrease from top to bottom and increase from bottom to top. Operator associativity is used to determine the order of operators with equal precedence evaluated in an expression ( ) [] . ++ -- ~ ! (right to left) * / % + - >> >>> << > >= < <= == != & ^ | && || ?: = *= /= %= += -= &= ^= |= <<= >>=

Primitive type conversion: Automatic Type Conversion When one type of data is assigned to another type of variable, an automatic type conversion will take place if: 1. Two data types are compatible 2. The destination data type is larger than the source data type It is known as widening conversion The numeric types, including integer and floating point types are compatible Numeric types are not compatible with char or boolean Char and boolean are not compatible with each other short  byte byte = int int i = 10; float f = 15.5; int  byte int = float char ch = ‘A’; double  float ok float = double i = f; f = i ; i = ch ; float  int char = any error i f ch short = char boolean = any vice versa 10 15.5 A 15 15.000000 65

class Test { public static void main(String[] a) { int i = 100; long x = i ; float f = x; System.out.println ("Int value "+ i ); System.out.println ("Long value "+x); System.out.println ("Float value "+f); } } Type conversion O/P: Int value 100 Long value 100 Float value 100.000000 Byte Short Int Long Float Double Promotion/Widening/Automatic conversion char in t

Type conversion: Narrowing or Explicit Conversion //incompatible data // type for explicit type conversion public class Test { public static void main(String[] argv ) { char ch = 'c'; int num = 65; ch = num ; System.out.println ( ch ); } } O/P: Error Double Floa t Long int Short Byte int char ch =(char)num A

Type Casting: Rules: 1. Type casting is also called as explicit type conversion.  2. To convert data from one type to another type we specify the target datatype in parenthesis is as a prefix to the data value that has to be converted. 3. If one operand is long, the whole expression is promoted to long. 4.All byte and short values are promoted to int. 5. (Target Datatype) DataValue Ex1: int total = 450, max = 600 ; float average ; average = (float) total / max * 100 ;  Ex2: byte b =42; char c=‘a’; short s=10; int i =50; float f=5.67f; double d=.1234; double result = (f * b) + ( i / c) – (d * s); (f * b) is promoted to float. ( i / c) is promoted to int. (d *s ) is promoted to double. float + int – double = float – double = double

Type conversion:Narrowing or Explicit Conversion Double Floa t Long int Short Byte int char class Test { public static void main(String[] args ) { double d = 100.04; long x = (long)d; //explicit type casting int i = (int)x; //explicit type casting System.out.println ("Double value "+d); //fractional part lost System.out.println ("Long value "+x); //fractional part lost System.out.println ("Int value "+ i ); } } O/P: Double value 100.04 Long value 100 Int value 100 (Target Datatype) expression

Flow of control In Java, there are several keywords that are used to alter the flow of the program Statements can be executed multiple times or only under a specific condition It can be divided into 3 categories Decision Making and Branching / Conditional Statements (if, switch, conditional) Looping Statements (while, do while, for, for each) Transfer Statements (break, continue, try, goto, return) Decision Making and Branching / Conditional Statements When a program breaks the sequential flow and jumps to another part of the code, it is known as branching. When branching is done on a condition it is known as conditional branching. Decision making statements are: if, switch, conditional operator

Flow of control Decision Making and Branching / Conditional Statements 1. Simple if statement: it always returns the boolean value (true/false) but not 0/1 ------- ------- if(condition) { //code executed if condition is true }  

Flow of control Decision Making and Branching / Conditional Statements 2. if-else statement: if(condition) { //code if condition is true } else { //code if condition is false } ----- -----

Flow of control Decision Making and Branching / Conditional Statements 3. nested-if statement: if(condition) { //code to be executed if(condition) { //code to be executed } }

Flow of control Decision Making and Branching / Conditional Statements 4. else-if ladder statement: if(condition1){   //code to be executed if cond1 is true   } else if(condition2){   //code to be executed if cond2 is true   }   else if(condition3){   //code to be executed if cond3 is true   }   ...   else{   //code to be executed if all the  cond’s are false   }

Flow of control Decision Making and Branching / Conditional Statements 2. switch statement 1. The switch statement evaluates an expression, then attempts to match the result to one of several possible cases 2. The expression of a switch statement must result in an integral type , meaning an int or a char switch ( expression ) it takes byte, short, int and char data type & enum (>1.5v), string (>1.7v) { case value1 : cases allows expressions also as a label statement-1; break; case value2 : not possible to give duplicate case labels statement-2; break; not possible to give any statement outside of case / default case value3: variables are not allowed as a case labels statement-3; break; default: it allows only one default and executes if all cases failed statement-3; both cases and default are optional and it wont produce any output }

Flow of control Decision Making and Branching / Conditional Statements 3. conditional operator statement i ) The conditional operator is ternary because it requires three operands ii) (condition) ? ( expression1) : ( expression2) iii) If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated iv) The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value

Flow of control Looping Statements When a program code repeats multiple times or repeatedly then it is known as looping Four looping statements: for, while, do while, for each 1. for statement 1 2/5 3/6 4/7 for(initialization; condition; modification) initialization  condition  body  modification { statements / body; } default condition is true provided by the compiler i.e., infinite times the code will execute for(; ; ) also allows and infinite times the code will execute multiple S.o.p are allowed in initialization as well as modification part unreachable statement can be occurred if condition is true i.e., boolean const in for loop for (int i = 0; i <= 10; i = i + 2) { System.out.println(i); }

Flow of control Looping Statements 2. for-each(enhanced for) statement (1.5v) Used to retrieve elements from array and collection for( datatype item : array) { } SYNTAX for (T element:Collection obj / array) { statement(s) } class  ForEachExample  {   public static void main(String[]  arg ){   //Declaring an array     int   arr []={12,23,44,56,78};   //Printing array using for-each loop    for( int  i:arr){      System.out.print ( i );    } } }     O/P: 12 , 23 , 44 , 56 , 78

Flow of control Looping Statements 3. while statement while(condition) { statements / body; } check the condition and execute the statements unreachable statement can be occurred if condition is true i.e., boolean constant stop the loop execution by break Also called as entry controlled loop

Flow of control Looping Statements 4. do-while statement do { statements / body; } while(condition) ; While must end with semi colon Before checking the condition it executes the statements once atleast condition is mandatory i.e., illegal start of expression unreachable statement can be occurred if condition is true i.e., boolean constant stop the loop execution by break Also called as exit controlled loop

Flow of control Transfer Statements Used to transfer the control from one place / position to another place / position Five transfer statements: break, continue, goto, try, return 1. try statement When the exception is raised in try then the control immediately goes to catch block EX: try{ S.o.p (10/0); } catch( ArithmeticException ae ){ S.o.p (10/2); } 2. goto statement Transfer the control from one pace to some other part of the program EX: forward jump backward jump goto label: label: statement; ------- ------- ------- ------- label: statement; goto label:

Flow of control: 4. continue statement Used to skip the particular iteration We can use this only inside the loops Ex: class Test{ public static void main(String args []) { for( int i =0; i <10; i ++) { if( i ==4) { continue; } else { System.out.print ( i );} } } 3. break statement It simply stop the execution We can use this inside the switch case / inside the loops / inside the blocks Ex: class Test{ public static void main(String args []) { for(int i =0; i <10; i ++) { if( i ==4) { break; } else { System.out.println ( i );} } } } O/P: 0 1 2 3 O/P: 0 1 2 3 5 6 7 8 9

Flow of control: Transfer Statements 5. return statement break is used to exit (escape) from the for-loop, while-loop, switch-statement that you are currently executing return will exit the entire method you are currently executing O/P: 0 1 2 3 Ex: class Test{ public static void main(String args []){ for( int i =0; i <10; i ++) { if( i ==4){ return; } else{ System.out.println ( i ); } } } }

Basic concept Programs: public class LargestNumber { public static void main(String[] args) { int num1 = 10, num2 = 20, num3 = 7; if( num1 > num2 && num1 > num3) System.out.println(num1+" is the largest Number"); else if (num2 > num1 && num2 > num3) System.out.println(num2+" is the largest Number"); else System.out.println(num3+" is the largest Number"); } } public class LargestNumber { public static void main(String[] args ) { int num1 = 10, num2 = 20, num3 = 7; if( num1 > num2) if( num1 > num3) System.out.println (num1+" is the largest Number"); else if (num2 > num1) if(num2 > num3) System.out.println (num2+" is the largest Number"); else System.out.println (num3+" is the largest Number"); } }

Basic concept Programs Cont …: import java.util .*; class FactorialExample { public static void main(String args[]) { Scanner sc =new Scanner(System.in); int i,fact =1; System.out.println("Please Enter the Value of n: "); int number= sc.nextInt (); for( i =1;i<= number;i ++) { fact=fact* i ; } System.out.println("Factorial of "+number+" is: "+fact); } } O/P: Please Enter the Value of n: 6 Factorial of 6 is: 720

Basic concept Programs Cont …: import java.util.Scanner ; public class SumOfEvenNos { public static void main(String[] args) { int number,i,evenSum =0; i number evensum Scanner sc =new Scanner(System.in); System.out.print (" Please Enter any Number: "); number= sc.nextInt (); for( i =1;i<= number;i ++) { if((i%2)==0) { evenSum = evenSum+i ; } } System.out.println("\n The Sum of Even Numbers upto " + number + " = " + evenSum ); } } 11 10 30

Basic concept Programs Cont …: import java.util .*; class FiboSequence { public static void main(String args[]) { Scanner sc =new Scanner(System.in); int fib1=0,fib2=1,fib3,i,fibseq; System.out.print ("Please Enter a number for printing Fibonacci Sequence: "); fibseq = sc.nextInt (); System.out.print (fib1+" "+fib2); for( i =2;i< fibseq ;++ i ) { fib3=fib1+fib2; System.out.print (" "+fib3); fib1=fib2; fib2=fib3; } } } O/P: Please Enter a number for printing Fibonacci Sequence: 8 0 1 1 2 3 5 8 11

Program on Prime Numbers: class PrimeNumbers { public static void main (String[] args){ int i =0, num =0; String primeNumbers = " "; //Empty String for ( i = 1; i <= 100; i ++){ int counter=0; for( num = i ; num >=1; num --){ if( i%num ==0){ counter = counter + 1; } } if (counter ==2){ primeNumbers = primeNumbers + i + " "; //Appended the Prime number to the String } } System.out.println("Prime numbers from 1 to 100 are :"); System.out.println( primeNumbers ); } }

Program on Literals: public class Literals{ public static void main(String[] args ) { int decimalValue = 123; // decimal-form literal int octalValue = 01200; // octal-form literal int hexaDecimalValue = 0xAce; // Hexa-decimal form literal int binaryValue = 0b00101; // Binary literal System.out.println("Decimal form literal is "+decimalValue); System.out.println("Octal form literal is "+octalValue); System.out.println("Hexa-decimal form literal is "+hexaDecimalValue); System.out.println("Binary literal is "+binaryValue); } } O/P: Decimal form literal is 123 Octal form literal is 640 Hexa-decimal form literal is 2766 Binary literal is 5

Program on Literals: O/P: * ** *** **** ***** class JavaPyramid1 {  public static void main(String[] args ) { for( int i =1; i <= 5 ; i ++) { for( int j=0; j < i ; j++) { System.out.print ("*"); } //generate a new line System.out.println (""); } } }

Program on Reverse of a given Number: import java.util.Scanner ;  class ReverseNumber {  public static void main(String args []) {  int n, rev = 0;   System.out.println ("Enter the number to reverse ");  Scanner sct = new Scanner(System.in);  n = sct.nextInt (); //User Input   while( n != 0 )  { rev = rev * 10; rev = rev + n%10; n = n/10; }   System.out.println ("Reverse of number is "+rev);  } }

Program on Reverse of a given String: import java.util .*; class ReverseString {   public static void main(String args []) {   String original, reverse = "";   Scanner sct = new Scanner(System.in);   System.out.println ("Enter string to reverse"); original = sct.nextLine (); //read String int length = original.length ();   for( int i = length - 1 ; i >= 0 ; i -- ) //Reversing the String reverse = reverse + original.charAt ( i );   System.out.println ("Reverse of entered string is: "+reverse);   } }

Assignment 1. a. Write the differences between C and Java? b. Write the differences between POPL and OOPL? 2. a. Briefly explain about features of Java b. List out the principles of OOPs and explain any 3 principles 3. a. What is JVM and why it is required? b. Write and explain the program structure in Java 4. a. What is datatype and explain about it? b. What is operator and explain any 3 operators with examples. 5. a. List out the applications of OOPs b. Write a Java program to find the sum of all even numbers from 1 to 100

https://www.youtube.com/watch?v=tZswK9PWBUo&list=PLXj4XH7LcRfDlQklXu3Hrtru-bm2dJ9Df&index=13

Who invented Java Programming? a) Guido van Rossum b) James Gosling c) Dennis Ritchie d) Bjarne Stroustrup Which statement is true about Java? a) Java is a sequence-dependent programming language b) Java is a code dependent programming language c) Java is a platform-dependent programming language d) Java is a platform-independent programming language Which component is used to compile, debug and execute the java programs? a) JRE b) JIT c) JDK d) JVM Which one of the following is not a Java feature? a) Object-oriented b) Use of pointers c) Portable d) Dynamic and Extensible

Which of these cannot be used for a variable name in Java? a) identifier & keyword b) identifier c) keyword d) none of the mentioned What is the extension of java code files? a) . js b) .txt c) .class d) .java What will be the output of the following Java code? Which environment variable is used to set the java path? a) MAVEN_Path b) JavaPATH c) JAVA d) JAVA_HOME class increment { public static void main(String args []) { int g = 3; System.out.print (++g * 8); } }

What will be the output of the following Java program? Which of the following is not an OOPS concept in Java? a) Polymorphism b) Inheritance c) Compilation d) Encapsulation What is not the use of “this” keyword in Java? a) Referring to the instance variable when a local variable has the same name b) Passing itself to the method of the same class c) Passing itself to another method d) Calling another constructor in constructor chaining class output { public static void main(String args []) { double a, b,c ; a = 3.0/0; b = 0/4.0; c=0/0.0; System.out.println (a); System.out.println (b); System.out.println (c); } }

What is the extension of compiled java classes? a) .txt b) . js c) .class d) .java Which exception is thrown when java is out of memory? a) MemoryError b) OutOfMemoryError c) MemoryOutOfBoundsException d) MemoryFullException Which of these are selection statements in Java? a) break b) continue c) for() d) if() Which of these keywords is used to define interfaces in Java? a) intf b) Intf c) interface d) Interface

Which of the following is a superclass of every class in Java? a) ArrayList b) Abstract class c) Object class d) String Which of these packages contains the exception Stack Overflow in Java? a) java.io b) java.system c) java.lang d) java.util Which of these statements is incorrect about Thread? a) start() method is used to begin execution of the thread b) run() method is used to begin execution of a thread before start() method in special cases c) A thread can be formed by implementing Runnable interface only d) A thread can be formed by a class that extends Thread class Which of these keywords are used for the block to be examined for exceptions? a) check b) throw c) catch d) try

Which one of the following is not an access modifier? a) Protected b) Void c) Public d) Private What is the numerical range of a char data type in Java? a) 0 to 256 b) -128 to 127 c) 0 to 65535 d) 0 to 32767 Which class provides system independent server side implementation? a) Server b) ServerReader c) Socket d) ServerSocket When does method overloading is determined? a) At run time b) At compile time c) At coding time d) At execution time

Which concept of Java is a way of converting real world objects in terms of class? a) Polymorphism b) Encapsulation c) Abstraction d) Inheritance Which concept of Java is achieved by combining methods and attribute into a class? a) Encapsulation b) Inheritance c) Polymorphism d) Abstraction What is it called if an object has its own lifecycle and there is no owner? a) Aggregation b) Composition c) Encapsulation d) Association Method overriding is combination of inheritance and polymorphism? a) True b) false

What is the range of short data type in Java? a) -128 to 127 b) -32768 to 32767 c) -2147483648 to 2147483647 d) None of the mentioned What is the range of byte data type in Java? a) -128 to 127 b) -32768 to 32767 c) -2147483648 to 2147483647 d) None of the mentioned Which of the following are legal lines of Java code? int w = ( int )888.8; byte x = (byte)100L; long y = (byte)100; byte z = (byte)100L; a) 1 and 2 b) 2 and 3 c) 3 and 4 d) All statements are correct

An expression involving byte, int , and literal numbers is promoted to which of these? a) int b) long c) byte d) float Which of these literals can be contained in float data type variable? a) -1.7e+308 b) -3.4e+038 c) +1.7e+308 d) -3.4e+050 Which data type value is returned by all transcendental math functions? a) int b) float c) double d) long What will be the output of the following Java code? a) 16.34 b) 16.566666644 c) 16.46666666666667 d) 16.46666666666666 class average { public static void main(String args []) { double num [] = {5.5, 10.1, 11, 12.8, 56.9, 2.5}; double result; result = 0; for ( int i = 0; i < 6; ++ i ) result = result + num [ i ]; System.out.print (result/6); } }

What will be the output of the following Java code? a) 301.5656 b) 301 c) 301.56 d) 301.56560000 What is the numerical range of a char data type in Java? a) -128 to 127 b) 0 to 256 c) 0 to 32767 d) 0 to 65535 Which of these coding types is used for data type characters in Java? a) ASCII b) ISO-LATIN-1 c) UNICODE d) None of the mentioned class area { public static void main(String args []) { double r, pi, a; r = 9.8; pi = 3.14; a = pi * r * r; System.out.println (a); } }

Which of these values can a boolean variable contain? a) True & False b) 0 & 1 c) Any integer value d) true Which one is a valid declaration of a boolean? a) boolean b1 = 1; b) boolean b2 = ‘false’; c) boolean b3 = false; d) boolean b4 = ‘true’ What will be the output of the following Java program? a) 66 b) 67 c) 65 d) 64 class mainclass { public static void main(String args []) { char a = 'A'; a++; System.out.print (( int )a); } }

What will be the output of the following Java code? a) 0 b) 1 c) true d) false Which of these is long data type literal? a) 0x99fffL b) ABCDEFG c) 0x99fffa d) 99671246 class booloperators { public static void main(String args []) { boolean var1 = true; boolean var2 = false; System.out.println ((var1 & var2)); } }

What is the stored in the object obj in following lines of Java code? Box obj ; a) Memory address of allocated memory of object b) NULL c) Any arbitrary pointer d) Garbage Which of these keywords is used to make a class? a) class b) struct c) int d) none of the mentioned Which of the following is a valid declaration of an object of class Box? a) Box obj = new Box(); b) Box obj = new Box; c) obj = new Box(); d) new Box obj ;

Which of these operators is used to allocate memory for an object? a) malloc b) alloc c) new d) give Which of these statement is incorrect? a) Every class must contain a main() method b) Applets do not require a main() method at all c) There can be only one main() method in a program d) main() method must be made public What will be the output of the following Java program? a) 9 b) 8 c) Compilation error d) Runtime error class main_class { public static void main(String args []) { int x = 9; if (x == 9) { int x = 8; System.out.println (x); } } }
Tags