Get ready to have fun in learning JAVA

shalini_goel14
@shalini-goel14-ASmC2J β€’ Oct 26, 2024

Are you afraid of Java? No need to be anymore because now you can have "Fun with Java" in this thread. πŸ˜€

After seeing very less no of Java programmers here, I thought of starting this thread. Hope it will not become dead and will benefit most of the CEans here.

The purpose of this thread is to:
Teach Java to everyone (CEans of different streams other than Computers or IT also) and make more and more CEans active here.

How this thread will work:
1. In this thread Java language will be taught and at the end of every lecture,assignments will be given.
2. Next lecture will start only if given assignments will be completed by CEans. If in any case they could not do so, they can reply back as "No" or can show/ask the problems.
3. References will be taken from "Complete Reference in Java J2SE5" by 'Herbert Schildt' ,"SCJP1.5 book" by 'Kaithy Seirra and Bert Bates' and trainer's learnings.

Very Important : Kindly keep following things in mind while posting further in this thread:
1. In any case- "Usage of sms text and languages other than English and Java will not be tolerated".
2. Off the topic discussions will not be allowed here.
3. No hesitation should be there in asking any questions.People here will be free to ask as dumb/stupid question as they can ask rather than not asking even a single one.
4. Assignment will consist of writing a Java program. (Initially starting from very simpler ones.)
5. Java Programmers other than trainer here are most welcome to share their knowledge or correct the trainer at any point of time.
6. Everyone is free to give assignments here.
7. Assignments are expected to be completed by end of every day so that learning process can be speed up.
8. Rules 1 to 7 are vapplicable to CE Admins/CE Mods/CE Editors/CE Ambassadors.

[Note: It will be really very pleasing if all points 1 to 8 mentioned above are followed by everyone here. 😁 ]

So kindly wait for Day 1 class which is going to start soon. πŸ˜‰
______________________________________________________

You all can follow following list of contents showing quick links for topics discussed so far in this thread.

Day1
Java Overview:
#-Link-Snipped-#
Setting up Java Environment in your machine:
#-Link-Snipped-#
Writing a simple Java Program
#-Link-Snipped-#

Day2
Identifiers and Declaration Rules
#-Link-Snipped-#
Variable Declarations
#-Link-Snipped-#

Day3
Control Statements
#-Link-Snipped-#
Iteration Statements
#-Link-Snipped-#
Break and Continue Statements
#-Link-Snipped-#

Day4
Array Declaration and Construction
#-Link-Snipped-#
Array Initialization
#-Link-Snipped-#

Day5
Introduction to classes
#-Link-Snipped-#
Declaration of objects and assignment of object reference variables
#-Link-Snipped-#

Day 6
Using Methods
#-Link-Snipped-#
Using Constructors
#-Link-Snipped-#

Day 7
Overloading Methods
#-Link-Snipped-#

Special Classes
Operators
#-Link-Snipped-#
Type Conversion and Type Casting
#-Link-Snipped-#

*****
How to overcome Operator overloading in Java
#-Link-Snipped-#
How to confirm whether JDK is installed in your system or not
#-Link-Snipped-#
Command line arguments
#-Link-Snipped-#
Java Keywords
#-Link-Snipped-#
Size and range of Java primitive types
#-Link-Snipped-#
'this' keyword
#-Link-Snipped-#

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • raj87verma88

    @raj87verma88-ZpL2Wn Feb 9, 2009

    I wish you luck for this project. Hope more people will join it.
    Is the rule number 8 necessary?...πŸ˜›

  • ms_cs

    @ms-cs-Ab8svl Feb 9, 2009

    I am interested in this,, can u please give further deep details about java classes...

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 9, 2009

    [Day1- Class]

    Here my aim will be more on teaching how to work on Java rather than teaching theoretical concepts ok guys.

    This post is dedicated to internal execution of Java and reasons for being calling Java a platform independent language.

    Java is known as a platform independent language unlike C, C++. Now what makes Java a platform independent language? Unlike other programming languages output of Java compiler is not executable code rather it is a bytecode. Now what is this bytecode?

    Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system. Java Run time system is called as JVM. JVM works as an interpreter for bytecode.

    So a Java program is first compiled by Java compiler and then interpreted by JVM.

    This processing can be clear with the following diagram:

    [​IMG]

    In the above diagram, Java compiler converts .java file(source code) to .class file(bytecode) and then JVM which acts as a Java interpreter converts .class file(bytecode) to executable code(or machine code). Unlike other languages Source code is not directly compiled and converted into executable code. Java compiler first compiles the code and then interprets the bytecode and the finally generates the executable code.

    Now what is the use of including this extra headache of converting to byte code?

    The whole purpose is to make this language a platform independent language. This transalating a Java program into bytecode makes it much easier to run a program in a wide variety of environments. Only the JVM(whose purpose is to convert bytecode to executable code) needs to be implemented for each platform. Though the details of JVM differ from platform to platform. but they all still understand the same bytecode. This is the reason Java is a platform independent language and called "Write once, run anywhere & anytime".

    I would also like to show you JVM Architecture to make things more clear:

    [​IMG]


    Note: When we run Java program, JVM is loaded internally in memory and JVM in tun loads our Java application so Java do not have direct interaction with OS. Only JVM do the work of OS(Operation System) for Java program.
  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 9, 2009

    [Day 1 Class Contd...]

    Now this post will consist of setting up the environment for writing a Simple Java Program

    1. Install jdk1.6 (latest version) on your system. (If any issues in installation, do ask here). Look at the following link for downloads

    #-Link-Snipped-#


    2. Create a source folder in your system where all your Java programs will be stored (let it be C:\JavaSrcCode..This is my system made folder. I would recommed you all to make following folder structure D:\MyJava\source)

    3. Create Example.java file in the above created folder(My is JavaSrcCode, your will be 'source' folder)

    Example.java (Details of this file is discussed in next post )

    public class Example{
    
    public static void main(String args[]){
    System.out.println("Hello Example Test");
    }
    }
    

    4. Now for compiling from command prompt

    a)Switch your location to bin directory of installed location of your java(C:\Program Files\Java\jdk1.6.0_02\bin)
    b)Now from that location type "javac <your java file absolute location>" (eg javac C:\JavaSrcCode\Example.java)

    See following figure
    [​IMG]

    Above command successfully generates the Example.class file for Example.java file in C:\JavaSrcCode folder only where Example.java file is stored.

    5. Now for running the class file.Issue the following command from command prompt
    java -classpath <class file of Example.java location> <java file name>
    e.g. java -classpath C:\JavaSrcCode Example as shown in following diagram

    [​IMG]

    -classpath : is just nothing but the list of directories in which classes might be found e.g in above case C:\JavaSrcCode is used to tell the JVM to look for .class file in specified folder. While running the file , there is no need to give Example.java (because while running JVM takes .class file as input)

    So above commands in the diagram will successfully run the program showing the output.

    [ Note :There is one more method of making compiling and running of Java programs easier. Don't need to make Example.java file in any folder. Simply make it in bin folder of installed java in your system.

    Then while compiling the Example.java,
    a) Switch your location to bin directory of installed location of your java(C:\Program Files\Java\jdk1.6.0_02\bin)
    b) command will be simply javac Example.java

    and while running command will be simple java Example

    But we should avoid using this approach of using Java. ]

    One more easier way is to use Java IDE. If any of you can get Netbeans version 6 or Eclipse(freeware) or Gel. Then it will be well and good. It will reduce your effort in running and compiling java programs through Command prompt.

  • safwan

    @safwan-NH7W5Y Feb 9, 2009

    hay shalini can I join this thread litle late..
    I means after 22/02/09
    me also thinking to learn after exams.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 9, 2009

    [Day1 Class Contd..]

    If anyone here wants me to put some light on object-oriented concepts. Do let me know. As it is theoretical concept so I am not going into it here ok. πŸ˜€

    So now coming to writing a simple basic Program in java :

    I will consider the program written in above post

    public class Example{
     
    public static void main(String args[]){
    System.out.println("Hello Example Test");
    }
    }

    A simple class program in Java represents a generic thing for any real world object

    Now for writing a Java Program

    1. Open notepad (if not using Java IDE) and save the file with .java extension in source folder (the one we created in step 2 of last post)
    Let me name that file as Example.java

    2. Now add following lines of code for creating the class
    public class Example {

    }

    [Note:
    1. Always remember the Java class name should match with that of the file name for example in above post case. The file name was Example.java which was exactly same as class name in code(public class Example). 2. Java is case-sensitive language.
    ]
    So now my Java class is defined.

    3. Now add following lines:

    public static void main(String args[]){

    }

    Look carefully here
    Above lines of code is much similar like creating a method of name main

    Here public means this method is accessible from anywhere outside the class. As main method here is accessible as it must be called by code outside of its class when program is started.

    Now keyword static allows main() to be called without having to instantiate a particular instance of the class (Will teach in further lectures how to instantiate a class). Actually this is infact necessary since main() is called by JVM before any objects are made.

    The keyword void simply tells the compiler that main() does not return a value.

    Any information that we need to pass to the method is received by the variables(called as parameters) specified within the set of parentheses followed by the name of the method. So in above main() method there is only one parameter named as args which is an array of instances of the class String.Here args receives any command-line arguments present when the program is executed.

    { and } shows the main method's body start and end.

    4. Next add the following line of code in main() method's body

    System.out.println("Hello Example Test");

    Here System is a predefined class that provides access to the system and out is the output stream that is connected to the console.println() displays the string which is passed to it.

    Notice that println() command end with a semicolon ; .

    So with all this I take leave from this thread and hope you all would have enjoyed the first day with Java.πŸ˜€

    [Assignment: Setting up the environment on your system and writing a simple Java program that will print "Hello World " in output. ]

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 9, 2009

    hi,
    very nice initiative. Looking forward to more..

    Btw, in the first post, in all places inside the quote, Java is said to be platform dependent. Please correct it.

  • ms_cs

    @ms-cs-Ab8svl Feb 9, 2009

    how can we C constructs in java?

  • ms_cs

    @ms-cs-Ab8svl Feb 9, 2009

    how can we use C codings in java using native...can u give example...?

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 9, 2009

    silverscorpionhi,
    very nice initiative. Looking forward to more..

    Btw, in the first post, in all places inside the quote, Java is said to be platform dependent. Please correct it.

    Ha ha ha Sorry Scorpion 😁 . Thanks for correcting me out. It is corrected now.

    ms_cshow can we use C codings in java using native...can u give example...?

    Hi ms_cs,
    I am not clear about your question. If you want to learn Java here better keep your C and C++ aside(just take OOP concepts of C++ here πŸ˜‰) ok

    Oh yes 1 more thing, Please start a new thread for your C to Java conversion question and show me a C program which you want to get converted to Java. I will answer that question there ok. One more thing Java do not support pointers. πŸ˜€

    [PS: Waiting for people to ask more and more questions and complete the assignment. πŸ˜” ]

  • sanalgrover

    @sanalgrover-kzLITm Feb 9, 2009

    I m intersted in this project of yours. Can u pls send me its details.

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 9, 2009

    Hasnt the next lesson arrived yet? oh, no..

    By the way, I have had this doubt for a long time. As mentioned, Java doesnt support pointers. So, how does it handle memory allocation and addressing? What about data structures? Are there no data structures in java?

  • ms_cs

    @ms-cs-Ab8svl Feb 10, 2009

    I heard that ,there is a way in java to use the pointers...

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 10, 2009

    silverscorpionHasnt the next lesson arrived yet? oh, no..

    By the way, I have had this doubt for a long time. As mentioned, Java doesnt support pointers. So, how does it handle memory allocation and addressing? What about data structures? Are there no data structures in java?

    Socrpion, next day lecture will start only when people will complete the assignment given. This class is for others and you not for me. So no use of simply teaching and teaching and teaching right? Better see my very first post mentioning about rules setup in this thread. ok. πŸ˜€

    For answer of your question, look at the following link:
    #-Link-Snipped-#

    Hope this may help you. πŸ˜‰

    ms_csI heard that ,there is a way in java to use the pointers...

    Really is there any way of using pointers in Java? Frankly speaking I don't know how to use pointers in Java. Please ask that source only from where you heard so that "there is a way in Java to use the pointers". Don't forget to share the answer here.ok πŸ˜€ By the way why you want to take overhead of using pointers in Java.πŸ˜•. When Java was designed the purpose of removing pointers usage was to reduce the complexities involved in programming with it right?

    [PS:All Please complete the given assignement to allow me to start next class as soon as possible ]

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 11, 2009

    Can't believe it, you all CEans here cannot make such a simple program and set up the environment. I am sure it will not even take half of the time it took for me to give Day1-class over here. I really cannot help you all at all.😑

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 11, 2009

    Hey cool it.
    I completed the assignment. Now give your next lesson.

    PS - I couldnt come to CE earlier because of some other works. Anyhow, you cant expect people to take this up above all their other works. just wait.

    PS2 - That's why I suggested you go at your own pace and keep giving lessons(and assignments too), and those who like it, will follow it. Those who are slow, will also eventually catch up. No problem.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 11, 2009

    silverscorpionHey cool it.
    I completed the assignment. Now give your next lesson.

    Sorry to say Scorpion but I cannot see your program/assignment here. Do share it here. πŸ˜€

  • arunhero99

    @arunhero99-LRZv4M Feb 12, 2009

    hey... here goes the assignment...
    I couldn't set up the environment n paths.. since they were already in place... but i did the assignment as per specification.

    public class xyz {
    public static void main(String[] args) {
    System.out.print("Hello World ");
    }
    }

    now lets go ahead with the class... πŸ˜€

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    ok so only arunhero Sir has completed the assignment πŸ˜‰. So now Day2- class can be started.

    [Assignment: Setting up the environment on your system and writing a simple Java program that will print "Hello World " in output. ]

    So here goes the program for those who couldn't complete it. Others are still free to make it again and post it here but remember your program is always enclosed in

     tags and well compiled and executed successfully. ok :)
    [code]
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class HelloWorldProgram {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            System.out.println("Hello World ");
        }
    
    }
    

    PS: Day2 class is going to start soon. πŸ˜€

  • jatin-phoenix

    @jatin-phoenix-qCwzlm Feb 12, 2009

    the working of loops and constructs in java is similar to that of c or cpp. however as java is completely object oriented therefore slight modifications are needed for main function.
    one thing i'd like to suggest is please go through herbert schildt by yourself also. people here can help you effectively only when you study some concepts by yourself and supplement your studying by visiting this thread.
    herbert schildt is easy to understand. trust me.

    great initiative i must add.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    [Day2 -Class]

    So few important points about

    1. Identifiers:

    • Identifiers can begin with a letter, an underscore, or a currency character.
    • After the first character, identifiers can contain any combination of letters, currency characters, connecting chracters, or numbers.
    • Identifiers can be of any length.
    • Identifiers are case-sensitive.eg. foo and Foo are two different identifiers.
    • Java keywords(for list of Java keywords refer any Java book) cannot be used as identifier.

    2.Declaration Rules:

    • A source code file can have only one public class.
    • If the source file contains a public class, the filename must match the public class name.
    • A file can have more than one non public class. (Class access variables will be discussed in detail later)
    • Files with no public classes have no naming restrictions.

    Eg. If I consider HelloWorldProgram, then in that I can add as many number of other non public classes without getting any compiler errors.

    Source File name as: HelloWorldProgram.java

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class HelloWorldProgram {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            System.out.println("Hello World ");
        }
    
    }
    
    class NonPublicClass1{
       //some code here 
    }
    
    class NonPublicClass2{
      //some code here  
    }
    

    Following program NonPublicClass.java will also compile fine, even though source file name do not match with the name of class included in it. Reason is because that declared class is not of type public. In other words class with no public class has no naming restrictions.

      [FONT=Verdana][SIZE=2]  [/SIZE][/FONT][FONT=Verdana][SIZE=2]package myjava;
      [/SIZE][/FONT][FONT=Verdana][SIZE=2]class NonPublicClass1{
      [/SIZE][/FONT][FONT=Verdana][SIZE=2]   }[/SIZE][/FONT]
    

    Following program NonPublicClass.java will not compile fine because here file name do not match with the name of public class name.
    Compilation error is: β€œClass publicClass is a public Class

    
    package myjava;
    class NonPublic{       } 
    
      public class PublicClass{
        public static void main(String[] args) {
              System.out.println("Hello World ");
          }
        
      }
    

    One source file can have only one public class. Look at following ManyPublicClass.java which will not compile fine.

    package myjava;
    
    public class PublicClass1{
        
    }
    
    public class PublicClass1{
        
    }
    
  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    [Day2 -Class Contd..]

    So after learning how to write a simple program in Java and knowing rules of making a simple source file and rules of declaring identifiers, lets now come to know something about Variable declarations

    Variable Declarations:

    For declaring any variable in java program, use following forms

    type var-name;
    More generic form : type identifier [=value][,identifier [=value..]..];

    Here type specifies the type of variable. Now first let us see what all types Java provides us:

    We can have two kinds of variables in java

    • Primitive (byte, short, int, long, char, float, double and boolean)
    • Reference Variables (will be discussed more later)

    Few examples of primitive type variable declarations are:

    int a, b, c;
    int d=5, e=10;
    byte x=10;
    double y=3.14159;
    char z='a';
    boolean x=true;

    Few examples of declaring reference variables:

    Object o; (Object class of Java)
    Dog myNewDogReferenceVariable; (where Dog is any generic class for real world object)
    String s1, s2, s3; (declare three String variables)

    Let us see writing a simple program VariableDeclarationExample.java that uses primitive type of variables declaration.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class VariableDeclarationExample {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            
            int a=10;
            char b='b';
            double c=3.14;
            
            System.out.println("int a ="+a);
            System.out.println("char b ="+b);
            System.out.println("double c ="+c);
        }
            
        }
    

    Output is:

    int a =10
    char b =b
    double c =3.14

    In the above program, three types of primitive type of variables are declared and then while printing through System.out.println command , they are printed without enclosng them in quotes

    e.g. System.out.println("int a ="+a);
    So above line prints "int a=<a's value intialized above>" ie. int a=10;

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    [Day2- Class Contd..]

    So after this I end my Day2-class. πŸ˜€

    [Assignments:

    1*. Mark the following identifiers as legal or illegal:
    int _a;
    int :b;
    int this_is_a_very_detailed_name_for_an_identifier;
    int _$:
    int .f;
    int 7g;
    int ________2_w;
    int -d;
    int $c;
    int e#;

    *Note legal for those that will compile fine and illegal for rest.

    2. List all the keywords found in Java language(jdk1.5).

    3. List a table showing size and ranges of all 8 primitive datatypes mentioned in Day2-class.

    4. Write a program that includes the declaration of all 8 primitive datatypes and then print them using System.out.println command. (Similar to one I have made in Day2-Class with 3 variables only).Write output also.

    ]

    I will try to cover up control statements in Day3-Class. If anyone has any issues with my way of teaching here or topics covered. Do let me know. If you want me to put more light on any topic.Please feel free to tell here. It will be my pleasure to answer your questions well.

    Thanks..Hope you all have enjoyed today's lecture πŸ˜€ .

  • komputergeek

    @komputergeek-Yf5hJ4 Feb 12, 2009

    Soln to assignment 1 :

    int _a; //legal
    int :b; //illegal
    int this_is_a_very_detailed_name_for_an_identifier; //legal
    int _$; //legal
    int .f; //illegal
    int 7g; //illegal
    int ________2_w; //legal
    int -d; //illgal
    int $c; //legal
    int e#; //illegal

    Please correct me if I am wrong.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    Well done komputergeek 😁.Rest of the questions are also waiting for you.πŸ˜‰

    By the way can anyone tell me here why "e#" is not a legal identifier here? 😁

  • babloo0311

    @babloo0311-J22PBc Feb 12, 2009

    Sorry to join lately,

    According to java language specification, a java identifier can contain only A-Z, a-z, 0-9, _ and $, and start only with one of a-z,A-Z, or $.

    # is not one of these more over, the identifier rule says "After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers".

    so its illegal . shalini is this correct and now -onwards i wil join this thread. πŸ˜€

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 12, 2009

    babloo0311Sorry to join lately,

    According to java language specification, a java identifier can contain only A-Z, a-z, 0-9, _ and $, and start only with one of a-z,A-Z, or $.

    # is not one of these more over, the identifier rule says "After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers".

    so its illegal . shalini is this correct and now -onwards i wil join this thread. πŸ˜€

    Good explanation babloo 😁 Well done. Other questions are also waiting for your answer.

    For Socket Programming I will see if I can start and give time to a new thread ok.πŸ˜€

  • komputergeek

    @komputergeek-Yf5hJ4 Feb 14, 2009

    Soln to assignment 2 :

    Java Keywords :


    1. abstract
    2. assert
    3. boolean
    4. break
    5. byte
    6. case
    7. catch
    8. char
    9. class
    10. const
    11. continue
    12. default
    13. do
    14. double
    15. else
    16. enum
    17. extends
    18. final
    19. finally
    20. float
    21. for
    22. goto
    23. if
    24. implements
    25. improt
    26. instanceof
    27. int
    28. interface
    29. long
    30. native
    31. new
    32. package
    33. private
    34. protected
    35. public
    36. return
    37. short
    38. static
    39. strictfp
    40. super
    41. switch
    42. synchronized
    43. this
    44. throw
    45. throws
    46. transient
    47. try
    48. void
    49. volatile
    50. while
  • komputergeek

    @komputergeek-Yf5hJ4 Feb 14, 2009

    Soln to assignment 3 :

    #-Link-Snipped-#

    Soln to assignment 4 :

    
    public class PrimitiveTypesTest
    {
        public static void main(String args[])
        {    
            boolean booleanVar=false;
            byte byteVar=1;
            short shortVar=2;
            char charVar='3';
            int intVar=4;
            long longVar=5;
            float floatVar=6;
            double doubleVar=7;
    
            System.out.println( "booleanVar=" + booleanVar);
            System.out.println( "byteVar=" + byteVar);
            System.out.println( "shortVar=" + shortVar);
            System.out.println( "charVar=" + charVar);
            System.out.println( "intVar=" + intVar);
            System.out.println( "longVar=" + longVar);
            System.out.println( "floatVar=" + floatVar);
            System.out.println( "doubleVar=" + doubleVar);
        }
    }
    Output :
    booleanVar=false
    byteVar=1
    shortVar=2
    charVar=3
    intVar=4
    longVar=5
    floatVar=6.0
    doubleVar=7.0
  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 14, 2009

    Hey komputergeek

    Well done 😁 but I am sorry to say your solution to Qn 3 is not visible here.πŸ˜”

    Your answers to other questions is 100% right. Keep it up. :clap:

    [ PS: Day-3 class is going to start soon. ]

  • rohit330

    @rohit330-DvfKyG Feb 15, 2009

    Sorry for the delay @ shalini_goel14

    [u]Here comes the first assignment[/u]
    
    public class sample
    {
     
      public static void main(String args[])
      
      {
        System.out.println("Hello World");
      }
    }
    
    
    
  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    rohit330Sorry for the delay @ shalini_goel14

    [U]Here comes the first assignment[/U]
    
    public class sample
    {
     
      public static void main(String args[])
      
      {
        System.out.println("Hello World");
      }
    }
    
    
    

    Good rohit. Keep it up 😁. Always start a class name with capital letter. So here 'sample' should be renamed as 'Sample' ok.

    Note for all: Format used for naming Java classes is called as CamelCase.
    eg. Sample, Example, PrintWriter, HelloWorld, etc.. The first letter for the inner words should be uppercase.

    @rohit By the way what is the file name of you program?

  • komputergeek

    @komputergeek-Yf5hJ4 Feb 15, 2009

    shalini_goel14Hey komputergeek

    Well done 😁 but I am sorry to say your solution to Qn 3 is not visible here.πŸ˜”
    
    Data Type         Size      Default          Min Value         Max Value
                            (bits)     Value
    
    
    boolean                1        false               false               true
    
    byte                     8          0              -128 (-2^7)            +127(2^7-1)
    
    short                   16         0               -2^15                   +(2^15) - 1
    
    char                    16        β€˜\u0000’       β€˜\u0000’               '\uFFFF'
    
    int                       32         0                -2^31                 +(2^31)-1
    
    long                    64         0L              -2^63                  +(2^63)-1
    
    float                    32        0.0F            1.4E-45               3.4028235E38
    
    double                 64        0.0             4.9E-324              1.7976931348623157E308
    
    

    Sorry for poor formating

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    Its ok komputergeek and thanks 😁

    I would like to add something in komputergeek's answer.

    Very simple formula to learn the ranges of any primitive datatype just remember following formula

    if bits is the no of bits of a particular primitive datatype
    Minimum/negative range is -2[sup] (bits-1) [/sup]
    Maximum/positive range is 2[sup] (bits-1) [/sup] -1

    So if size of byte is 8 bits then minimum range is -2[sup]7[/sup] and maximum range is 2[sup]7[/sup] -1.

    [ Note for all: There is no range for a boolean type, a boolean can be true or false. So if anyone asks you what is the bit-depth of a boolean, just tell "That's virtual-machine dependent". ]

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    [Day 3- Class]

    Control Statements in Java is almost similar to other programming languages but enhanced for loop in Java is different from other languages.

    Selection statements:

    1. if statement
    Syntax: if(condition) statement1;
    else statement2;

    Example

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class IFExample {
        public static void main(String[] args) {
            
            int x = 1 ; //try with different different values of x
            if (x == 1) {
                System.out.println("x equals 1");
            }else{
                System.out.println("No idea what x is");
            }
        }
    
    }
    

    In the above program, output will be "x equals 1".

    2. Nested ifs
    These ifs are commonly used in programming.
    Syntax if(condition1) {
    statement1;
    if(condition2) statement2;
    else statement3;
    ........(sequences of if-else )
    }
    else{
    statement 4;
    }

    3. The if-else-if ladder

    Syntax: if(condition)
    statement;
    else if(condition)
    statement;
    else if(condition)
    statement;
    ......
    else
    statement;

    In this kind of ladder first if condition is checked if it is true then statement associated with it is executed and rest of the ladder is bypaased. If that if condition not true then it keeps on checking conditions associated with all elseif until it reaches the final else condition.

    Example

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class IfElseifExample {
    
        public static void main(String[] args) {
            int x = 3 ; //try with different different values of x
            if (x == 1) {
                System.out.println("x equals 1");
            } else if (x == 2) {
                System.out.println("x equals 2");
            } else if (x == 3) {
                System.out.println("x equals 3");
            }else{
                System.out.println("No idea what x is");
            }
    
    
        }
    }
    
    

    Output will be "x equals 3".

    4. switch
    It is always a good practice to use switch rather than using a large-series of if statements.
    Syntax:

    switch(expression)
    case value1:
    //statement sequence
    break;
    case value2:
    //statement sequence
    break;
    ..........
    case valueN:
    //statement sequence;
    default:
    //default statement sequence

    The expression must be of type byte, short, int or char (enum also from java5 onwards.Enumeration will be discussed later). You won't be able to compile if you use anything else, including reamining numeric types long, float and double.

    Example considering same if-else if ladder example

    
    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class SwitchExample {
        public static void main(String[] args) {
            int x = 3 ; //try with different different values of x
            switch (x) {
                case 1:
                System.out.println("x equals 1");
                break;
                case 2: 
                    System.out.println("x equals 2");
                    break;
                case 3:
                System.out.println("x equals 3");
                break;
                default:
                System.out.println("No idea what x is");
            }
        
        }
    
    }
    
    

    Output will be same but output differs if you don't use break statement. Try that in your homework 😁

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 15, 2009

    For the 1st program('if' program), the output will be "x equals one". It's given as "b is greater".

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    silverscorpionFor the 1st program('if' program), the output will be "x equals one". It's given as "b is greater".

    Oh so sorry Scorpion. Actually I was in hurry so messed up πŸ˜”.Thanks for pointing out, it is corrected now.

    [PS: Day3-class is not yet over. ]

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 15, 2009

    Let the rest of the lessons come quickly.. Eager for more..

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    silverscorpionLet the rest of the lessons come quickly.. Eager for more..

    If you are eager to learn next lessons. I am eager to see your(You Mr Scorpion) all homework. 😑. If you don't have time to do homework, I also don't have enough time to give classes regularly ok. I have other commitments also, still managing to do that also.* Tired *

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 15, 2009

    Do everyone visiting the thread have to submit assignments? Anyhow they are all going to be the same. We have not yet reached the point where there can be multiple solutions fr the same problem. So why don't you go on as soon as anyone posts the answers to the questions?

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 15, 2009

    silverscorpionSo why don't you go on as soon as anyone posts the answers to the questions?

    Dear Scorpion,

    I am doing that only but everyone can submit their answers. The best student here will be awarded by me here, thats secret.:sshhh:

  • silverscorpion

    @silverscorpion-iJKtdQ Feb 15, 2009

    oh, I didnt know that. Well, this is tempting. Then I'll try to do assignments here after.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 16, 2009

    [Day3 - Class Contd..]

    Iteration Statements

    1. while

    Syntax:
    while(condition){
    //body for loop
    }

    The body of the loop will be executed as long as the conditional expression is true(in below Example it is [x<=5])

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class WhileExample {
    
        public static void main(String[] args) {
         int x=1;
         while(x<=5){
             System.out.println(x);
             x++;
         }
        }
    }
    
    

    Output is:

    1
    2
    3
    4
    5

    2. do-while

    Syntax:
    do{
    //body of loop
    }while(condition);

    Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If that expression is true, loop will repeat, else it will terminate.

    Example: Same as above but with do-while statement now.

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class DoWhileExample {
    
        public static void main(String[] args) {
            int x=1;
         do{
             System.out.println(x);
             x++;
         }while(x<=5);
            
        }
    
    }
    

    Output same as above.
    Note : Notice the ';' after while statement in do-while case.

    3. 'for-in' / 'for-each' /'enhanced for' loop
    From Java 5 onwards, there are two types of for loop

    1. Basic For loop
    Syntax:
    for(declaration and initialization;condition;iteration){
    //body
    }
    Declaration & intialization lets you declare and initialize zero, one or multiple variables of the same type. If you declare more than variable of same type, then separate them with commas
    e.g for(int x=10, y=20 ;x<y;x++) is legal
    Condition expression must always evaluate t o boolean value. There can be only one test expression.
    e.g. for( int x=0; (x<5), (y<2); x++) //illegal -gives compiler error.
    Iteration is simple increment operation that tells the no. of times we want our for loop to execute.
    Example : Taking same example as above

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class BasicForLoopExample {
    
        public static void main(String[] args) {
          
            for(int x=1; x<=5;x++){
                System.out.println(x);
            }
        }
    
    }
    
    

    Output is same as above.


    2. Enhanced for loop or for-each version of for loop

    This type of loop is used for iterating collections including arrays. Its usage you can see more in Collections class.Right now I will consider its very simple usage here ok.

    Syntax:
    for(type itr-val : collection){
    //body
    }
    type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection.

    Example: Taking same example as above but I am creating an array which contains values 1 to 5 of type int

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class EnhancedForLoopExample {
    
        public static void main(String[] args) {
            
            int arrayTypeCollection[] = {1, 2, 3, 4, 5}; 
            for(int x : arrayTypeCollection){ //instead of x you can use anything
                System.out.println(x);
            }
    
        }
    
    }
    
    

    Output again same as above.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 16, 2009

    [Day3 - Class Contd..]

    Using break and continue statements

    The break statement causes the program to stop execution of the innermost loop and start processing the next line of code after the block.

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class BreakExample {
    
        public static void main(String[] args) {
              for(int x=1; x<=5;x++){
                System.out.println(x);
                break;
            }
              System.out.println("I am out of the loop now");
        }
    
    }
    
    

    Output of above program

    1
    I am out of the loop now

    Reason is just after first print statement when break; statement is executed, it tells the system to come out of the loop and prints the statement after for loop.

    If you use System.exit(); instead of break; in above program. It simply terminates the whole program execution.

    So output of above program will become

    1

    The continue statement causes only the current iteration of the innermost loop to cease and the next iteration of the same loop to start if the condition of the loop is met.
    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class ContinueExample {
    
        public static void main(String[] args) {
            for (int x = 1; x <= 5; x++) {
                System.out.println(x);
                continue;
            }
        }
    }
    
    

    Output of above program will not result in any endless loop. When continue statement is hit, the iteration expression ends in the natural way. So output will simply generate sequence of no.s from 1 to 5.

    return statement is explicitly used to return something from a method. It causes the program control to transfer back to the caller of the method.It immediately terminates the execution of the method in which it is executed.

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class ReturnExample {
    
        public static void main(String[] args) {
            boolean t = true;
            System.out.println("Before the return");
            if (t) {
                return;
            }
            System.out.println("This will not execute.");
        }
    }
    
    

    Output will be

    Before the return

    As soon as return statement is executed control passes to the caller and final println() statement is not executed.

    Labeled and Unlabeled Statements

    Both the break and continue statement can be unlabeled or labeled.
    All above discussed examples of break and continue statements were of unlabeled type.

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class LabeledBreakExample {
    
        public static void main(String[] args) {
            
            outer:
            for (int x = 1; x <= 5; x++) {
                while(true){
                System.out.println(x);
                break outer;
                }//end of inner while loop        
        //    System.out.println("Outer loop.");//This line won't even compile if uncommented
            }//end of outer loop
            System.out.println("Good Bye");
        }
    }
    
    

    In above code mark any label to your loop and then call break statement followed by that loop's labe name. Like in above example break outer;. Output of above program will be

    1
    Good Bye

    Similarly for continue statement. Example for continue is left as an exercise for everyone. πŸ˜€

    Note: Labeled continue and break statements must be inside the loop that has the same lable name; otherwise the code will not compile.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 16, 2009

    ok so with this I end up my Day3-Class.

    Assignment:
    1. Write a program that uses labeled continue statement.
    2. Write all types of operators used in Java with examples.

    [More question to be added later πŸ˜€ ]

  • komputergeek

    @komputergeek-Yf5hJ4 Feb 16, 2009

    Soln to assignment 1 :

    public class LabeledContinueExample 
    {
        public static void main(String[] args) 
        {        
            outer:
            for (int x = 1; x <= 5; x++) 
            {
                for(int y = 1;y <= 5; y++)
                {
                      System.out.print(x);
                      if (x==y)
                      {                                                
                            System.out.println();
                            continue outer;    
                      }
                }       
            }   
        }
    }
    
    //Output :
    
    1
    22
    333
    4444
    55555
    
    
  • Raviteja.g

    @ravitejag-02nJVr Feb 17, 2009

    i have a doubt shalini
    in every program there is a line

    public static void main(String args[ ]);

    can u kindly explain each word it contains i mean what is the purose of using that
    (especially the static keyword)

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 18, 2009

    Raviteja.gi have a doubt shalini
    in every program there is a line
    can u kindly explain each word it contains i mean what is the purose of using that
    (especially the static keyword)

    Hi Raviteja,
    A very good question. About that line Please check my Day1-Class and for that static if you are still not clear, you need to wait for more details on it. I will cover it later ok.πŸ˜€

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 19, 2009

    [ Special Class on "Operators" ]

    After looking at the response to Qn 2 of Day3- assignment, I am starting this special class on Operators used in Java.

    1. Arithmetic Operators
    + Addition
    - Subtraction
    * Multiplication
    / Division

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class BasicArithmeticOperatorsUsage {
    
        public static void main(String[] args) {
            int num1 = 20;
            int num2 = 10;
            int sum = num1 + num2;
            int multiply = num1 * num2;
            int divide = num1 / num2;
            int minus = num1 - num2;
            int negation = -num1;
    
            System.out.println("20 + 10 =" + sum);
            System.out.println("20 * 10 =" + multiply);
            System.out.println("20 / 10 =" + divide);
            System.out.println("20 - 10 =" + minus);
            System.out.println("- 20 =" + negation);
    
        }
    }
    

    Output:

    20 + 10 =30
    20 * 10 =200
    20 / 10 =2
    20 - 10 =10
    - 20 =-20

    2. Modulus Operator

    % - returns the remainder of a division operation.
    Example

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class ModulusOperatorExample {
    
        public static void main(String[] args) {
            int num1 = 100;
            int num2 = 101;
            int num3 = 10;
    
            System.out.println("100 % 10= " + num1 % num3);
            System.out.println("101 % 10= " + num2 % num3);
    
        }
    }
    

    Output:

    100 % 10= 0
    101 % 10= 1

    3. Arithmetic Assignment Operators

    += Addition assignment
    -= Subtraction assignment
    *= Multiplication assignment
    /= Division assignment
    %= Modulus assignment

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class AssignmentOperatorsExample {
    
        public static void main(String[] args) {
            int num1 = 20;
            int num2 = 10;
    
            num1 += num2;//it means num1=num1+num2
            System.out.println("num1 += num2 is: " + num1);
            num1 -= num2;//it means num1=num1-num2
            System.out.println("num1 -= num2 is: " + num1);
            num1 *= num2;//it means num1=num1*num2
            System.out.println("num1 *= num2 is: " + num1);
            num1 /= num2;//it means num1=num1/num2
            System.out.println("num1 /= num2 is: " + num1);
            num1 %= num2;//it means num1=num1%num2
            System.out.println("num1 %= num2 is: " + num1);
        }
    }
    

    Output:

    num1 += num2 is: 30
    num1 -= num2 is: 20
    num1 *= num2 is: 200
    num1 /= num2 is: 20
    num1 %= num2 is: 0

    4. Increment and Decrement Operators

    ++ Increment operator-> increases the operator value by one
    -- Decrement operator-> decreases the operator value by one

    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class IncrementDecrementOperatorsUsage {
    
        public static void main(String[] args) {
            int a = 1;
            int b = 2;
    
            int c = a++;//first assigns value of 'a' to 'c' and then increments value of 'a' by 1
            System.out.println("c = " + c);
            int d = ++b;//first increments value of 'b' by 1 and then assigns incremented value of 'b' to 'd' 
            System.out.println("d = " + d);
            int e = --a;//first decrements value of 'a' by 1 and then assigns decremented value of 'a' to 'e'
            System.out.println("e = " + e);
            int f = b--;//first assigns value of 'b' to 'f' and then decrements value of 'b' by 1
            System.out.println("f = " + f);
            f++;//simply increments value by 
            System.out.println("Again f = " + f);
        }
    }
    

    Output:

    c = 1
    d = 3
    e = 1
    f = 3
    Again f = 4

    5. Assignment Operator

    It is simple = sign operator.
    Syntax is : var=expression;
    but here type of var must be compatible with the expression.
    Example:

    int x, y, z;
    x=y=z=100; //sets x, y and z to 100

    6. Ternary(or ?) operator

    It can replace certain if-else statements
    Syntax is: expression1?expression2:expression3
    if expression1 is true expression2 executes else expression3 executes
    Example

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class TernaryOperatorExample {
    
        public static void main(String[] args) {
    
            int num1=10,num2=20;
            
            /* if num1>num2 is true,greaterNum will be assigned num1 otherwise num2 will be assigned */
            int greaterNum=num1>num2?num1:num2;
            
            System.out.println("Greater Number is:"+greaterNum);
        }
    
    }
    

    Output: "Greater Number is:20"

    7. Relational Operators

    == Equal to
    != Not equal to
    > Greater than
    < less than
    >= Greater than or equal to
    <= Less than or equal to

    Outcome of these opeartors is always a boolean value.
    Example:

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class RelationalOperatorsExample {
    
        public static void main(String[] args) {
    
            int num1 = 20;
            int num2 = 10;
            boolean b;
    
            b = num1 == num2;
            System.out.println("Is num1==num2? " + b);
            b = num1 != num2;
            System.out.println("Is num1!=num2? " + b);
            b = num1 > num2;
            System.out.println("Is num1>num2? " + b);
            b = num1 < num2;
            System.out.println("Is num1<num2? " + b);
            b = num1 >= num2;
            System.out.println("Is num1>=num2? " + b);
            b = num1 <= num2;
            System.out.println("Is num1<=num2? " + b);
    
        }
    }
    
    

    Ouput:

    Is num1==num2? false
    Is num1!=num2? true
    Is num1>num2? true
    Is num1<num2? false
    Is num1>=num2? true
    Is num1<=num2? false

    8. Boolean Logical Operators

    These operators opearte only on boolean operands(ie. only on true or false values)

    & Logical AND
    | Logical OR
    ^ Logical XOR
    || Short-cricuit OR
    && Short-cricuit AND
    ! Logical unary NOT
    &= AND assignment
    != OR assignment
    ^= XOR assignment
    == Equal to
    != Not equal to
    ?: Ternary if-then else //use is same as ternary operator discussed above

    Example

    package myjava;
    
    /**
     *
     * @author shalinig
     */
    public class BooleanLogicalOpeartorsUsage {
    
        public static void main(String[] args) {
    
            boolean a=true;
            boolean b=false;
            boolean result;
            
            result=a | b;//returns true if any of the operands is true
            System.out.println("a | b = "+result);
            result=a & b;//returns true only if both the operands are true
            System.out.println("a & b = "+result);
            result=a ^ b;//returns true if exactly one operand is true
            System.out.println("a ^ b = "+result);
            result=!a;//returns false if a is true and true if a is false
            System.out.println("!a = "+result);
            a &= b; //similar to a = a & b
            System.out.println("a &= b = "+a);
            a |= b;//similar to a= a | b
            System.out.println("a |= b = "+a);
            a ^= b;//similar to a= a ^ b
            System.out.println("a ^= b = "+a);
            result = a== b;//compares value of b to a, returns true if equal else false
            System.out.println("a == b = "+result);
             result = a!= b;//compares value of b to a, returns true if not equal else false
            System.out.println("a != b = "+result);
            
        }
    
    }
    

    Output:

    a | b = true
    a & b = false
    a ^ b = true
    !a = false
    a &= b = false
    a |= b = false
    a ^= b = false
    a == b = true
    a != b = false

    Short Circuit Logical operators

    If you look at above ementioned boolean logical operators,there are two short-circuit logical operators. These || ad && are exactly same as | and & opeartors.
    The short circuit operator && evaluates the left side of the operation first(operand one) and if it is false, it doesn't bother looking at right side of the expression(operand two) unlike & operator.
    Similarly the short circuit operator || evaluates the left side of the operation first(operand one) and if it is true, it doesn't bother looking at right side of the expression(operand two) unlike | operator.

    Note: It is a good practice to use these short-circuit opeartors in your program rather than logical operators from the point of view of performance.

    PS: I have not covered Bitwise opeartors because they are hardly used anywhere.

    Hope you people would have enjoyed this special lecture on Operators. πŸ˜€

    Assignment try each and every case in Example programs here like replacing int with double,long, float and making more complications in above sample programs.Keep on playing youself with these programs and have fun.

  • shalini_goel14

    @shalini-goel14-ASmC2J Feb 22, 2009

    Guys I request you all to not to make this thread dead. Please keep on playing with loops and try something new on your system and ask questions like why it happened like this and that. It will be really fun. I don't have as such any assignments for Day3-Class and Special Class on "Operators" but yes I am waiting for your stupid questions which you will face only when you will start playing with this language on your system.Share your stupid made programs here and ask questions Please.

    Please do all that stupid stuff so that I can start Day4 class soon. πŸ˜€