Get ready to have fun in learning JAVA
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-#
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
-
raj87verma88I wish you luck for this project. Hope more people will join it.
Is the rule number 8 necessary?...π -
ms_csI am interested in this,, can u please give further deep details about java classes...
-
shalini_goel14[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:
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:
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[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" (eg javac C:\JavaSrcCode\Example.java)
See following figure
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
e.g. java -classpath C:\JavaSrcCode Example as shown in following diagram
-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. -
safwanhay shalini can I join this thread litle late..
I means after 22/02/09
me also thinking to learn after exams. -
shalini_goel14[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. ] -
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. -
ms_cshow can we C constructs in java?
-
ms_cshow can we use C codings in java using native...can u give example...?
-
shalini_goel14
Ha ha ha Sorry Scorpion π . Thanks for correcting me out. It is corrected now.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.
Hi ms_cs,ms_cshow can we use C codings in java using native...can u give example...?
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. π ] -
sanalgroverI m intersted in this project of yours. Can u pls send me its details.
-
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? -
ms_csI heard that ,there is a way in java to use the pointers...
-
shalini_goel14
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. π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?
For answer of your question, look at the following link:
#-Link-Snipped-#
Hope this may help you. π
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?ms_csI heard that ,there is a way in java to use the pointers...
[PS:All Please complete the given assignement to allow me to start next class as soon as possible ] -
shalini_goel14Can'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.π‘
-
silverscorpionHey 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
Sorry to say Scorpion but I cannot see your program/assignment here. Do share it here. πsilverscorpionHey cool it.
I completed the assignment. Now give your next lesson. -
arunhero99hey... 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_goel14ok 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 intags 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-phoenixthe 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[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.
- 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.
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[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)
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
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
char b =b
double c =3.14
e.g. System.out.println("int a ="+a);
So above line prints "int a=" ie. int a=10; -
shalini_goel14[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 π .
-
komputergeekSoln to assignment 1 :
int _a; //legal
Please correct me if I am wrong.
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 -
shalini_goel14Well 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? π -
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. π -
shalini_goel14
Good explanation babloo π Well done. Other questions are also waiting for your answer.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. π
For Socket Programming I will see if I can start and give time to a new thread ok.π -
komputergeekSoln to assignment 2 :
Java Keywords :
- abstract
- assert
- boolean
- break
- byte
- case
- catch
- char
- class
- const
- continue
- default
- do
- double
- else
- enum
- extends
- final
- finally
- float
- for
- goto
- if
- implements
- improt
- instanceof
- int
- interface
- long
- native
- new
- package
- private
- protected
- public
- return
- short
- static
- strictfp
- super
- switch
- synchronized
- this
- throw
- throws
- transient
- try
- void
- volatile
- while
-
komputergeekSoln 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_goel14Hey 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. ] -
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"); } }
-
shalini_goel14
Good rohit. Keep it up π. Always start a class name with capital letter. So here 'sample' should be renamed as 'Sample' ok.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"); } }
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? -
komputergeekshalini_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_goel14Its 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[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 π -
silverscorpionFor the 1st program('if' program), the output will be "x equals one". It's given as "b is greater".
-
shalini_goel14
Oh so sorry Scorpion. Actually I was in hurry so messed up π.Thanks for pointing out, it is corrected now.silverscorpionFor the 1st program('if' program), the output will be "x equals one". It's given as "b is greater".
[PS: Day3-class is not yet over. ] -
silverscorpionLet the rest of the lessons come quickly.. Eager for more..
-
shalini_goel14
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 *silverscorpionLet the rest of the lessons come quickly.. Eager for more.. -
silverscorpionDo 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
Dear Scorpion,silverscorpionSo why don't you go on as soon as anyone posts the answers to the questions?
I am doing that only but everyone can submit their answers. The best student here will be awarded by me here, thats secret.:sshhh: -
silverscorpionoh, I didnt know that. Well, this is tempting. Then I'll try to do assignments here after.
-
shalini_goel14[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. do-while
2
3
4
5
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 ;xCondition 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[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
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.
I am out of the loop now
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
Similarly for continue statement. Example for continue is left as an exercise for everyone. π
Good Bye
Note: Labeled continue and break statements must be inside the loop that has the same lable name; otherwise the code will not compile. -
shalini_goel14ok 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 π ]
-
komputergeekSoln 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.gi 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
Hi Raviteja,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)
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[ 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
2. Modulus Operator
20 * 10 =200
20 / 10 =2
20 - 10 =10
- 20 =-20
% - 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
3. Arithmetic Assignment Operators
101 % 10= 1
+= 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
4. Increment and Decrement Operators
num1 -= num2 is: 20
num1 *= num2 is: 200
num1 /= num2 is: 20
num1 %= num2 is: 0
++ 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
5. Assignment Operator
d = 3
e = 1
f = 3
Again f = 4
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;
6. Ternary(or ?) operator
x=y=z=100; //sets x, y and z to 100
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
Ouput:= num2; System.out.println("Is num1>=num2? " + b); b = num1 <= num2; System.out.println("Is num1<=num2? " + b); } }
Is num1==num2? false
8. Boolean Logical Operators
Is num1!=num2? true
Is num1>num2? true
Is num1Is num1>=num2? true
Is num1<=num2? false
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
Short Circuit Logical operators
a & b = false
a ^ b = true
!a = false
a &= b = false
a |= b = false
a ^= b = false
a == b = true
a != b = false
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_goel14Guys 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. π -
safwanhay i am not getting jdk1.6 where to go even i searched it on googel but not precise link is not there.
and i am back after exam . now i started learning java. -
komputergeek@safwan : Check this
#-Link-Snipped-# -
shalini_goel14ok I am very depressed with the responses I am getting here from you guys, especially from Day 3 class.π
Anyways Day 4 class is going to start soon. Hope you people will show some interest in it. I am doing it for you people only not for me. -
komputergeek@shalini :This thread is definitely interesting but in my opinion,we should not wait for assignments at this difficulty level.You should increase speed of teaching.
-
shalini_goel14
Good suggestion komputergeek,komputergeekYou should increase speed of teaching.
Even I also want to do so but cannot find time. It takes time for me to create those lectures referring different books and the biggest problem with me is the text editor here which has very limited functionalities. π -
silverscorpionYep, I thought of exactly the same thing.
Things will automatically get sorted out as classes progress. I'm waiting for the oops concepts here.
Dont get me wrong here, but I really dont like writing programs to find sum of two numbers.Well, I can hear you shouting, but that's it.
As the class progresses to more tougher concepts, I assure you I'll participate more, as only then can I effectively learn by writing programs.
Dont get angry for this, now..chill. -
silverscorpionoops, seems like you have already replied to komputergeek's opinion.. I didnt see that..
-
shalini_goel14[Day 4-Class ]
This class will include "Array Declaration, Construction and Intialization"
How to declare an array
a) array of primitives
int[] intArray; (more recommended)
or
int intArray[]; ->avoid using this form.
b) array of object references
Suppose you have a your own made class Employee or an inbuilt Java class like Thread, Long, Integer etc. Array declaration will be like
Employee[] employeeArray;
Thread[] threadsArray;
Long[] longArray;
Integer[] intArray;
or
Employee employeeArray[];
Thread threadsArray [];
Long longArray [];
Integer intArray [];
c) Multidimensional arrays declaration(arrays of arays)
String[] [] [] string3DArray;
String[] string2DArray;
Constructing an array
Constructing array means creating the array object on the heap(where all objects live). So to create an array object Java must know how much space to allocate on the heap for it, so we need to specify the size of the array at creation time.
A) Constructing One-Dimensional Arrays
new is a java keyword(more about it in later classes) but here it works like a special operator that allocates memory.
So now how will I construct a 1-D array:
Step 1: First I will declare it like told above.
Syntax: type var-name;
int[] intArray; //it simply declares the array of int
Step2: Next I need to allocate memory for arrays using new keyword
Syntax: var-name = new type[size] ;
intArray = new int[4];//constructs an array and assigns it the intArray variable.
Now see what happens behind the scenes :
Below is the figure showing A one-dimensional array on the heap.
So line step2 puts one new object on the heap (name intArray) holding 4 elements of int type each with default values as 0.
We can also declare and construct an array in one sentence:
int[] intArray = new int[4];
[ Qn: How many objects are created on the heap by following line:
Thread[] threadsArray = new Thread [5];
Qn: Will the following line Compile? Give reason also.
int[] intArray =new int[] ;
]
Constructing multi-dimensional Array
Multi-dimensional arrays are simple arrays of arrays. So a 2D array of type int is really an object of type int array(int []) with each element in that array holding a reference to another int array.The second dimension actually holds the actual int primitives.
int[][] int2DArray= new int[3][];
Note that only first brackets are given a size. This is acceptable in Java since the JVM needs Following picture demonstrates this example:
int[] [] int2DArray =new int[3][];
int2DArray[0]= new int[2];
int2DArray[0][0]=6;
int2DArray[0][1]=7;
int2DArray[0]= new int[3];
int2DArray[0][0]=9;
int2DArray[0][0]=8;
int2DArray[0][0]=5;
[PS I: Day4-class next part will include intializing an array.You all need to give me some time. Please do answer the two questions asked here by that time. Feel free to ask your doubts.
PS II :I wonder how you people are so clear about what I taught you till now. I think I need to ask all my doubts to you guys. Right komputergeek and Scorpion?π
] -
silverscorpion
this should be intArray=new int[4], right?shalini_goel14intArray = new intArray[4];//constructs an array and assigns it the intArray variable. -
silverscorpion
well, you might as well be right. you can try asking us your doubts in the fundamentals, because, you would always be immersed in advanced concepts, and on the other hand, I never moved beyond the fundamentals in java..πshalini_goel14PS II :I wonder how you people are so clear about what I taught you till now. I think I need to ask all my doubts to you guys. Right komputergeek and Scorpion?π
] -
silverscorpion
well, for the first question, only one object is created in the heap, because it's a single dimensional array.shalini_goel14[ Qn: How many objects are created on the heap by following line:
Thread[] threadsArray = new Thread [5];
Qn: Will the following line Compile? Give reason also.
int[] intArray =new int[] ;
]
]
as for the second line, it will not compile, because, the size of the array is not specified and the compiler will not know how much space to allocate for that.
Are these answers correct?π -
shalini_goel14Yes absolutely correct Scorpion π. Good
One more question for you all, What will be your answer if I make
Thread[] threadsArray = new Thread [5];
a 2-D array. How many objects will be created now?
[Qn: How many objects will be created on the heap by following line:
Thread[] threadsArray = new Thread [5];
]
-
shalini_goel14[Day4 -Class ..Contd ]
Initializing primitive data types array:
int[] intArray =new int[5];
This step only creates a reference variable intArray and allocates space of 5 elements in the array with default values as 0.
[ Qn Write a program for putting values in a 1-D Array and then printing them on console.]
Initializing non-primitive data types array:
Array[] pets=new animal[3];
This creates one array object on the heap with 3 null references of type Animal (class) but we donβt have any Animal class objects, so next step is to create some Animal objects and assign them to index positions in the array referenced by variable pets
pets[0]=new Animal ();
pets[1]=new Animal ();
pets[3]=new Animal ();
So now above 3 lines put 3 new Animal objects on the heap ad assigns them to the 3 index positions (elements) in the pets array.
[ Qn Write a program for putting values in a 2-D Array and then printing them on console.]
Initializing a 2-D Array:
int[][] scores =new int[3][]; //Declare and create an array holding 3 references to int arrays
scores[0]=new int[4]; //the first element in the scores array is an int array of four int elements
scores[1]=new int[6]; //The second element in the scores array is an int array of 6 elements
scores[2]=new int[1];//The third element in the scores array is an int array of one int element.
Declaring, constructing and initializing on one line:
Following lines of code are legal to use in Java
A)int[] dots={6,5,8}
[Note: In above line, no size limit is mentioned. Size is determined by the comma-separated items in the curly braces. ]
B)int x=5;
Above two lines of code is also legal.
int[] dots={6, x, 8}
C)Dog dogObj= new Dof(βFrodoβ);
In above piece of code, in total 4 objects are created
Dog[] myDogs={ dogObj, new Dog(βCloverβ), new Dog(βAikoβ) };
1 Dog object referenced by dogObj and by myDogs[0]
1 Dog[] array object referenced by myDogs
2 Dog objects referenced by mydogs[1] and myDogs[2]
D)Similarly for multi-Dimensional arrays:
int[] scores ={ {5,2,4,7}, {9,2}, {3,4} );
It creates total of 4 objects on the heap.
1 object of int array type referenced by scores[0]
1 object of int array type referenced by scores[1]
1 object of int array type referenced by scores[2]
1 object of array of int arrays type referenced by scores
In actual what happens behind the scenes:
First an array of int array is constructed (scores as reference variable to it). The scores array has a length of three (as found from items in curly braces). Each of the 3 elements in the scores array is a reference variable to an int array, so the 3 int arrays are constructed and assigned to the 3 elements in the scores array.
The size of each of the int arrays is derived from the no. of items within the corresponding inner curly braces.
First array has length of four {5,2,4,7}
Second array has length of two{9,2 }
Second array has length of two{3,4 }
So in all we have 4 objects, 1 array object referencing int arrays and 3 int arrays each initialized with actual int values
See below a sample 1-D Array program:
package myjava; /** * * @author shalinig */ public class ArrayExample { public static void main(String[] args){ /*Declaring, constructing and intializing 1-D array in a single line */ int[] nums={5, 6, 7, 8, 9}; /* nums.length gives the length of array (in this case it is 5 */ for(int i=0; i
Ouput is:
Element at index 0 = 5
[Qn Write down the default values for each of the following variable types :
Element at index 1 = 6
Element at index 2 = 7
Element at index 3 = 8
Element at index 4 = 9
a)Object reference
b)Byte
c)Short
d)Int
e)Long
f)Float
g)Double
h)Boolean
i)Char
]
PS I: Now with this Arrays in Java is finished in Day4-Class. Few difficult things in thsi topic are still left but I cannot discuss them without classes.So they will be taught later. If anyone has any doubt till now or feels I have missed something important thing, Please do let me know.π
PS II: I will soon start Classes part. Just give me some time.
Thanks -
shalini_goel14
Yes you are right Scorpion. I am correcting it.silverscorpionthis should be intArray=new int[4], right?
Thanks for correcting me everytime. π -
arunhero99wow..his has become a full fledged training room...kudos shailini....gr8 job
-
shalini_goel14
Thanks Sir. πarunhero99wow..his has become a full fledged training room...kudos shailini....gr8 job
PS: SMS language is not allowed here. Please read my first post in this thread.π Better correct it. -
shalini_goel14[Day5 -Class]
Introduction to Classes
Class is nothing bur is a template for an object and object can be nay real worl object. Let us say Dog is a real world thing and it can be of different types or can have diferent names. So Dog can be made as a class and then we can instantiate that class to make an object which will have its own properties or attributes Eg. Dog is a class and Dog with name "Frodo" is 1 object and Dog with name "Aiko" is another object.
So overall it is said
"Class is a template for an object and an object is an instance of a class."
Both are used interchangeably.
Class Definition:
General form of a class definition is:
class classname{
instance variable: The data, or variables , defined within a class are called instance-variables.
type instance-variable1;
type instance-variable2;
..........
type instance-variableN;
type methodname1(parameter list){
//body of method
}
type methodname2(parameter list){
//body of method
}
.............
type methodname1(parameter list){
//body of method
}
}
Methods: The actual code is contined within them.
Collectively, instance-variables and methods are called as clas members of a class.
Instance variables are called so because each instance(or object of the class) contains its own copy of these variables. Thus the data for one object is separate and unique from the data for another.
Static variables are just opposite of instance variables. They share the same data for all objects or instances of a class.
Java classes need not to have a main method.
A simple clas Example
package myjava; import java.util.Date; /** * * @author shalinig */ class CrazyEngineer{ String memberName; String engineeringTrade; String location; }
The above class does not have any methods but yes has instance variables.
A class defines a new data type so here CrazyEngineer is a new datatype. So now we can use this CrazyEngineer datatype to declare objects. A class do not create an object in actual, we need to create it using new operator.
So to actually create a CrazyEngineer object, we will use the following statement:
/* creates a CrazyEngineer object called crazyEngineerObj */
After this line executes crazyEngineerObj will be an instance of CrazyEngineer
CrazyEngineer crazyEngineerObj = new CrazyEngineer();
Thus every CrazyEngineer object will have its own copies of instance variables memberName, engineeringTrade and location. To access these variables a dot(.) operator is used. It links the name of the object with the name of the instance variable. Dot(.) operator is also used to access methods contained within a class.
e.g. To assign value="shalini_goel14" to memberName, following statement will be used:
crazyEngineerObj.memberName="shalini_goel14" ;
The above line tells the compiler to assign the copy of memberName that is contained within the crazyEngineerObj object the value "shalini_goel14"
A sample class program using dot operator:
package myjava; import java.util.Date; /** * * @author shalinig */ class CrazyEngineer{ String memberName; String engineeringTrade; String location; } public class CrazyEngineerDemo{ public static void main(String[] args){ CrazyEngineer crazyEngineerObj =new CrazyEngineer(); StringBuilder profileInOneLine=null; //assigns values to crazyEngineerObj's instance variables crazyEngineerObj.memberName="shalini_goel14"; crazyEngineerObj.engineeringTrade="Computer Science"; crazyEngineerObj.location="Bangalore"; //write profile in one line profileInOneLine = new StringBuilder(crazyEngineerObj.memberName+" is a crazy "); profileInOneLine.append(crazyEngineerObj.engineeringTrade+" engineer"); profileInOneLine.append(" located in "+crazyEngineerObj.location+";"); //prints the profile in one line System.out.println("Profile is:::"+profileInOneLine); } }
Output is:
Profile is:::shalini_goel14 is a crazy Computer Science engineer located in Bangalore;
[Qn Write the same program as shown above but declare two CrazyEngineer objects and the print them as done in above program only]
PS: Day5 class next part will include objects declaration and behind the scenes happenings but need to wait for it. π -
Yamini LFirst i would like to congratulate you for all your efforts shalini..Good job..
Now my answer for your assignment question
Qn:Write a program to store values in a 1 d array and print them in the console.
import java.io.*;
import java.lang.*;
class arr
{
public static void main(String args[])
{
//creating and initializing arrays
int[] a={1,4,6,8,10};
for(int i=1;i{
System.out.print("value at position"+i);
System.out.println(" "+a);
}
}
}
__________________ -
shalini_goel14Thanks for good words miniyπ
PS: Please enclose your code within code tags(use icon # shown above) and Please try to make class name with intial capital letter e.g 'Arr' instead of 'arr'
Thanks -
Yamini L[Qn Write the same program as shown above but declare two CrazyEngineer objects and the print them as done in above program only]
Now i am doing the most recent assignment you had given....Hope it works..
import java.io.*;
import java.lang.*;
import java.util.*;
class CrazyEngineer{
String memberName;
String engineeringTrade;
String location;
}
public class CrazyEngineerDemo{
public static void main(String[] args){
CrazyEngineer crazyEngineerObj =new CrazyEngineer();
CrazyEngineer crazyEngineerObj1=new CrazyEngineer();//second object
StringBuilder profileInOneLine=null;
//assigns values to crazyEngineerObj's instance variables
crazyEngineerObj.memberName="shalini_goel14";
crazyEngineerObj.engineeringTrade="Computer Science";
crazyEngineerObj.location="Bangalore";
//assigns values to crazyEngineerobj1's instance variables
crazyEngineerObj1.memberName="miniy";
crazyEngineerObj1.engineeringTrade="Computer Science";
crazyEngineerObj1.location="India";
//write profile in one line
profileInOneLine = new StringBuilder(crazyEngineerObj.memberName+" is a crazy ");
profileInOneLine.append(crazyEngineerObj.engineeringTrade+" engineer");
profileInOneLine.append(" located in "+crazyEngineerObj.location+";");
//prints the profile in one line
System.out.println("Profile is:::"+profileInOneLine);
//second profile
profileInOneLine = new StringBuilder(crazyEngineerObj1.memberName+" is a crazy ");
profileInOneLine.append(crazyEngineerObj1.engineeringTrade+" engineer");
profileInOneLine.append(" located in "+crazyEngineerObj1.location+";");
//prints the profile in one line
System.out.println("Profile is:::"+profileInOneLine);
}
} -
shalini_goel14
What does that mean "Hope it works". Man, write well compiled and executed programs only. Don't do copy paste in one only ok.π Well Good keep it up. Rest of the questions are also waiting for you.miniy[Qn Write the same program as shown above but declare two CrazyEngineer objects and the print them as done in above program only]
Now i am doing the most recent assignment you had given....Hope it works.. -
Yamini L[Qn Write down the default values for each of the following variable types :
a)Object reference
b)Byte
c)Short
d)Int
e)Long
f)Float
g)Double
h)Boolean
i)Char
]
Object Reference-> NULL
Byte -> 0
Short -> 0
Int -> 0
Long -> 0L
Float -> 0.0f
Double -> 0.0d
Boolean -> false
Char -> '\u0000' -
Yamini L
Hey you wanted it in the same format..Thats why i just included another object in it:smile:..I compiled it,got the output..anyways am also waiting for your forthcoming classes and assignments..πshalini_goel14What does that mean "Hope it works". Man, write well compiled and executed programs only. Don't do copy paste in one only ok.π Well Good keep it up. Rest of the questions are also waiting for you. -
shalini_goel14
Perfect, miniy Please write the output also if it was giving output πminiyHey you wanted it in the same format..Thats why i just included another object in it:smile:..I compiled it,got the output..anyways am also waiting for your forthcoming classes and assignments..π
PS: There are many more pending assignements for you. Complete them by the time I start new class. π -
Yamini L[Qn Write the same program as shown above but declare two CrazyEngineer objects and the print them as done in above program only]
Output
Profile is:::shalini_goel14 is a crazy Computer Science engineer located in Banalore;
π
Profile is:::miniy is a crazy Computer Science engineer located in India; -
shalini_goel14Miny, good one. This was cheating π, you ate 'g' in Bangalore and made it 'Banalore' right? while your program is having 'g' at its corect place.
Anyways leave it. Don't post anymore here for that same program. Devote time on other assignments ok. And from next time try to include output with program in same post only ok. It makes easier for others to understand ok. π -
Yamini LLast post for this assignment..Please do forgive me for this..Just like to justify..This was the actual output i got..While i tried to copy it from command prompt, i missed out 'g'π..Believe meπ..
Profile is:::shalini_goel14 is a crazy Computer Science engineer located in Bang
Now onwards,i would be shifting my focus on to other assignments..π
alore;
Profile is:::miniy is a crazy Computer Science engineer located in India; -
Yamini L[ Qn Write a program for putting values in a 2-D Array and then printing them on console.]
Code
import java.io.*; class Arrtwod { public static void main(String args[]) { int[][] a={ {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}; //Creating and initializing 2-D Array for(int i=0;i<4;i++) { for(int j=0;j<3;j++) { System.out.println("Value at a["+i+","+j+"] = "+a[i][j]); //printing the values at console } } } }
Output
Value at a[0,0] = 1
Value at a[0,1] = 2
Value at a[0,2] = 3
Value at a[1,0] = 4
Value at a[1,1] = 5
Value at a[1,2] = 6
Value at a[2,0] = 7
Value at a[2,1] = 8
Value at a[2,2] = 9
Value at a[3,0] = 10
Value at a[3,1] = 11
Value at a[3,2] = 12 -
ms_csI have one doubt.Whether goto statement is avilable in java?
-
shalini_goel14
In the Java(tm) programming language, goto is a reserved word; the Java programming language does not have a goto statement. However there are alternative statements that you can use in the Java programming language in place of the goto statement.(ue break and continue to avoid use of goto )ms_csI have one doubt.Whether goto statement is avilable in java?
ms_cs, I woould again say to you- "Don't try to use complicated features of C/C++ in Java" Java provide many better things to avoid those complicated faetures. π Keep C/C++ aside while learning Java , that would be better. -
shalini_goel14[Day5-Class ..contd]
Declaring Objects
Declaring objects for a new datatype(which is actually of defined class type) is a 2-step process:
Step1: We must declare a variable of class type. Considering the example of class CrazyEngineer
CrazyEngineer crazyEngineerObj;
It declares a reference to object. Note, object is not created in actual. It is simply a variable that can refer to an object. After execution of above line , object is assigned default value that is null. So crazyEngineerObj=null right now.
Step2: Now we need to acquire an actual physical copy of the object and assign it to that variable. This is done using new operator.
crazyEngineerObj = new CrazyEngineer();
It allocates a CrazyEngineer object. Now crazyEngineerObj is no more null.
Now what this new operator does in actual?
It dynamically allocates (that is allocates at runtime) memory for an object and returns a reference to it. This reference is actually the address of the object in memory allocated by new. This reference is then stored in the
variable (here like crazyEngineerObj)
All above things will become more clear to you with following diagram.
Assigning Object Reference variables
Anyone any ideas what happens inside when following two lines execute?
CrazyEngineer crazyEngineer1=new CrazyEngineer ();
As we all know now in first statement crazyEngineer1 object is created and
CrazyEngineer crazyEngineer2= crazyEngineer1; //assigns a copy of the crazyEngineer1 object to crazyEngineer2.
and allocated memory also but what about crazyEngineer2 object?Is is also allocated space in memory? The answer is no.
See the situation with the help of following fig:
Actually what happens, there remains only one object which was created usin new operator but there are two reference variables that refer to single CrazyEngineer object.Those variables are crazyEngineer1 and crazyEngineer2. So simply crazyEngineer2 refers to the same object as does crazyEngineer1. Thus any changes made to the object through crazyEngineer2 will affect the object which crazyEngineer1 is referring, since they both refer to the same object.
One more important thing is even if object crazyEngineer1 is made to refer any other object or is assigned value null , then in any case it will not affect crazyEngineer2. crazyEngineer2 will keep on referrring to the same CrazyEngineer object. It will not become null even if crazyEngineer1 is made null
CrazyEngineer crazyEngineer1= new CrazyEngineer();
Look, though crazyEngineer1 is made as null but cazyEngneer2 will keep on pointing to the original object.
CrazyEngineer crazyEngineer2= crazyEngineer1;
...
crazyEngineer1=null;
Though situation is somewaht different in case of assignment of local primitives. Will discuss it separately more.
PS: Any questions till now , Please feel free to ask and do complete the assignments. I need to give many more questions to you all. π -
Raviteja.gi have doubt about operators
can i ask now because i didn't have completed the assignments because of lack of time but still trying to adjust -
shalini_goel14
Sure, there is no boundations of doing assignments and asking questions here. π Take your own time but just try to not to make all my efforts in vain. πRaviteja.gi have doubt about operators
can i ask now because i didn't have completed the assignments because of lack of time but still trying to adjust -
Raviteja.gits ok mam
and my doubt is about operator overloading in matrices
i was asked to design a java program explaining operator overlaoding
for which i have designed a program that will explain the function of +(operator)
but they expected in matrices which i don't know -
shalini_goel14
Very good question but can you first put some more light on what exactly is operator overloading?-actually I don't know C/C++ πRaviteja.gits ok mam
and my doubt is about operator overloading in matrices
i was asked to design a java program explaining operator overlaoding
for which i have designed a program that will explain the function of +(operator)
but they expected in matrices which i don't know
Then I can answer your question.π -
Raviteja.gOperator overloading means the work the same operator is different in different situations
for example
case 1:a+b
where a,b are two int variables and the +(operator) is used for addition here
case 2:ravi+teja
where ravi,teja are two strings
now comes the point
here the same +(operator) was used but here it concatenates the two strings and gives
raviteja as output
i don't remember the syntax for second one correct me if i'm wrong
i think you understand now what is operator overloading
It is a specific case of polymorphism in which some or all of operatorsOperator %28Programming%29 like +, =, or == have different implementations depending on the types of their arguments. -
shalini_goel14Man, I love Java. It provides such a good feature that you don't need to even think about your old C++ operator overloading.π
String class in Java takes care of your problem. It will add integer values but append string values.
If you add
int + int = output is always int value
int +String = int will be appended to String value (int is automatically converted to String value)
String +String = again appended String
Look at the following example
package myjava; /** * * @author shalinig */ public class OperatorOverloadingInJava { public static void main(String[] args){ int integerVal1=10; int integerVal2=20; String stringVal1="Shalini"; String stringVal2="Goel"; System.out.println("(integerVal1 + integerVal2)= "+(integerVal1+integerVal2)); System.out.println("integerVal1 + integerVal2 = "+integerVal1+integerVal2); System.out.println("stringVal1 + stringVal2= "+stringVal1+stringVal2); } }
Output:
(integerVal1 + integerVal2)= 30
Hope I have cleared your doubt π
integerVal1 + integerVal2 = 1020
stringVal1 + stringVal2= ShaliniGoel -
Raviteja.goops!
you misunderstood.
i'm talking operator overloading in java i too don't know about c++
but my problem is how can operator overloding is done in matrices. -
shalini_goel14
Raviteja,Raviteja.goops!
you misunderstood.
i'm talking operator overloading in java i too don't know about c++
but my problem is how can operator overloding is done in matrices.
I showed you an example right? There is no need of any operator overloading concept here right?
In my shown example , you see that same "+" operator is adding two integers also as well as appending two Strings also(the way you explained me Operator overloading in your last post right?), then operator overloading done or not? Why you are going round and round to the question then. Tell? -
komputergeek
Most of the people suggest to avoid use of 'goto' even in languages other than java.What is the reason?shalini_goel14it is good practice to avoid its usage in Java. . -
MaRo
#-Link-Snipped-#komputergeekMost of the people suggest to avoid use of 'goto' even in languages other than java.What is the reason? -
gohmEven though the only thing I know of java is a warm, caffeinated beverage in a mug, this is a great thread!
-
shalini_goel14I request all the people here to refer following link.
#-Link-Snipped-#
It may clear the doubts of those who are not cleared about features removed in Java π -
Raviteja.g
sorry mam,shalini_goel14Raviteja,
I showed you an example right? There is no need of any operator overloading concept here right?
In my shown example , you see that same "+" operator is adding two integers also as well as appending two Strings also(the way you explained me Operator overloading in your last post right?), then operator overloading done or not? Why you are going round and round to the question then. Tell?
i did the same in my external lab exam but they said it is not appreciable
so i asked you to say how to do operator overloading in matrices
sorry if my way of asking is wrong!π -
safwanhi all ceans and specially mam ,
but i am late offcorse i am not able to run my firs programm "Example.java" any sujjetion mam. -
shalini_goel14
No early late funda here safwan.π Tell what problems you are getting and also tell what all steps you followed?safwanhi all ceans and specially mam ,
but i am late offcorse i am not able to run my firs programm "Example.java" any sujjetion mam.
Have you installed jdk on your system? -
safwan
i first downloaded jdk1.6 as your given link then i installed it on my directory D. where i had already made new folder with name myjava.shalini_goel14No early late funda here safwan.π Tell what problems you are getting and also tell what all steps you followed?
Have you installed jdk on your system?
so the directory will be D:myfolder
then i started writing programm example.java but unluckily how to comile i dont know i saved it as example.java now what to do?π
i think its not like vb where we have a code area and we can start debugging by pressing start button.so clear my doubt. -
shalini_goel14Yes safwan, it is not like vb where running programs is darn easy.
Could you see those black colour images shown by me in Day-1 class. ok leave them right now
First let me confirm whether jdk is installed on your system or not ok
Follow following steps right now
Step 1: Go to Start Menu
Step2: Click on Run
Step 3: Enter "cmd"
Step 4: Command prompt window opens and enter there "java -version"
Now show me that image here-what it shows to you ok π -
safwanhi cmd showd me the following message when i typed java-version in it.
'javaoversion'is not recognized as an internal or external command,operable program ot batch file.
(sorry unable to insert image becose i dont know as it is asking url) -
Yamini L
Hey safwan,safwanhi cmd showd me the following message when i typed java-version in it.
'javaoversion'is not recognized as an internal or external command,operable program ot batch file.
Did you type java-version or java -version?? -
safwan
thanks miniy my doubt was same.miniyHey safwan,
Did you type java-version or java -version??
now after typing java -version
the message shown by cmd is:
java version "1.6.0_12" java
@shalini so what next step mam.SE runtime Environment java hotspot client VM c:\users\safwan> -
shalini_goel14ok good safwan. Now exactly follow the steps I told in Day -1 Class ok.
If any issues do post here. π -
shalini_goel14[Day6 Class]
Aplogoies to all for not continuing any classes here from a long time π
How to use methods
As we have seen in last class , how to include variables in a Java class .In the same way we can include methods in a Java class
Syntax for any method in Java language is
type name(parameter-list){
type specifies the type of data returned by the method. If method does not ahve anything to return , at that time write void. Whenever we return anything from a method return term is mandatory in the body of method.
//body of method
}
name specifies the name you want to give to your method.
parameter-list is a sequence of type and identifier pairs separated by comma. If the method has no parameters to pass, this list is empty.
So now look at the following program for adding a method in CrazyEngineer class-one I used in last class.Following prgram is same as the one used before but only difference is now I have encapsulated "printing profile in one line" lines of code in a method and transferred that method to CrazyEngineer class instead of keeping it in CrazyEngineerDemo class. And finally I call that method from CrazyEngineer class in my main class using object.
Simple Method Example
package myjava; /** * * @author shalinig */ class CrazyEngineer { String memberName; String engineeringTrade; String location; //write profile in one line void printProfile() { StringBuilder profileInOneLine = null; profileInOneLine = new StringBuilder(memberName + " is a crazy "); profileInOneLine.append(engineeringTrade + " engineer"); profileInOneLine.append(" located in " + location + ";"); //prints the profile in one line System.out.println("Profile is:::" + profileInOneLine); } } public class CEClassWithMethod { public static void main(String[] args) { CrazyEngineer crazyEngineerObj = new CrazyEngineer(); //assigns values to crazyEngineerObj's instance variables crazyEngineerObj.memberName = "shalini_goel14"; crazyEngineerObj.engineeringTrade = "Computer Science"; crazyEngineerObj.location = "India"; crazyEngineerObj.printProfile(); } }
Output:
Profile is:::shalini_goel14 is a crazy Computer Science engineer located in India;
Now look at another example showing usage of methods but returning a value from it.
Method with Return value Example
package myjava; /** * * @author shalinig */ class CrazyEngineer { String memberName; String engineeringTrade; String location; //write profile in one line StringBuilder printProfile() { StringBuilder profileInOneLine = null; profileInOneLine = new StringBuilder(this.memberName + " is a crazy "); profileInOneLine.append(this.engineeringTrade + " engineer"); profileInOneLine.append(" located in " + this.location + ";"); return profileInOneLine; } } public class CEClassMethodWithReturn { public static void main(String[] args) { CrazyEngineer crazyEngineerObj = new CrazyEngineer(); StringBuilder profileInOneLine = null; //assigns values to crazyEngineerObj's instance variables crazyEngineerObj.memberName = "shalini_goel14"; crazyEngineerObj.engineeringTrade = "Computer Science"; crazyEngineerObj.location = "India"; //calls the method that returns StringBuilder object profileInOneLine = crazyEngineerObj.printProfile(); //prints the profile in one line System.out.println("Profile is:::" + profileInOneLine); } }
Output same as above program. The only difference is in above program I am trying to make print statement ready in method and then returning that StringBuilder object to my main class for printing on console.
Method that takes Parameters Example
package myjava; /** * * @author shalinig */ class CrazyEngineer { String memberName; String engineeringTrade; String location; //sets the values to member variables void setProfileData(String m,String e,String l){ memberName=m; engineeringTrade=e; location=l; } //write profile in one line StringBuilder printProfile() { StringBuilder profileInOneLine = null; profileInOneLine = new StringBuilder(memberName + " is a crazy "); profileInOneLine.append(engineeringTrade + " engineer"); profileInOneLine.append(" located in " + location + ";"); return profileInOneLine; } } public class CEClassMethodWithParameters { public static void main(String[] args) { CrazyEngineer crazyEngineerObj = new CrazyEngineer(); StringBuilder profileInOneLine = null; /* set the values to variables of crazyEngineer Object * using setProfileData parametrized method */ crazyEngineerObj.setProfileData("shalini_goel14", "Computer Science", "India"); //calls the method that returns StringBuilder object profileInOneLine = crazyEngineerObj.printProfile(); //prints the profile in one line System.out.println("Profile is:::" + profileInOneLine); } }
Output same but in the above program, you all can see a special method setProfileData() that takes parameters values as String(though all the values can be of different type- like int, float, etc.). These parameters are assigned values from main class method CEClassMethodWithParameters using following statement:
crazyEngineerObj.setProfileData("shalini_goel14", "Computer Science", "India");
So using above statement ,
shalini_goel14 is assigned to m
Computer Science to e
India to l
And finally these values are assigned to member variables- "memberName", "engineeringTrade" and "location" of class CrazyEngineers and get printed using printProfile method.
[Assignment :
Write a program to calculate the Area of a rectangle using all type of approaches of writing method in one simple program
a) using Method with return values
b) using method with parameters
]
Note: Day6 -class will include constructors soon -
Yamini L[Assignment :
Write a program to calculate the Area of a rectangle using all type of approaches of writing method in one simple program
a) using Method with return values
b) using method with parameters
]
Here i have used method overloading..
method area()->(I}simple method with no parameters and return values
(2)method that takes parameters but does not return any
value
(3)method that takes parameters and returns a value
import java.io.*; class Method { void area() [COLOR=red]//simple method no parameters and [/COLOR] { [COLOR=red]return values[/COLOR] System.out.println("Enter x and y:");//[COLOR=red]get value from user[/COLOR] try { DataInputStream dis=new DataInputStream(System.in); int x=Integer.parseInt(dis.readLine()); int y=Integer.parseInt(dis.readLine()); int z=(x*y); System.out.println("Area of Rectangle is " +z); [COLOR=red]//find area and display[/COLOR] } catch(Exception e){} } void area(int x,int y) [COLOR=red] //method that takes integer parameters[/COLOR] { int z=(x*y); System.out.println("Area of Rectangle is " +z); [COLOR=red]//display area[/COLOR] } double area(double x,double y) [COLOR=red]//method that takes parameters and returns value [/COLOR] [COLOR=red][COLOR=black]{[/COLOR] [/COLOR] double z=(x*y); return z; } } class Methodsdemo { public static void main(String args[]) { Method m=new Method(); [COLOR=red]//declare object for Method class[/COLOR] System.out.println("Using method with no parameters and no return types"); m.area(); [COLOR=red]//call simple method[/COLOR] System.out.println("Using method with parameters and no return types"); m.area(5,10); [COLOR=red]//call method with parameters[/COLOR] System.out.println("Using method with parameters and return types"); double b=m.area(10.123,20.324); [COLOR=red]//call method that returns a value[/COLOR] System.out.println("Area of Rectangle is" +b); } }
Output
C:\Documents and Settings\USER1\Desktop>java Methodsdemo
Using method with no parameters and no return types
Enter x and y:
6
7
Area of Rectangle is 42
Using method with parameters and no return types
Area of Rectangle is 50
Using method with parameters and return types
Area of Rectangle is205.739852 -
safwanhi all
@shallini
a i am not able to uderstand day 1 class proprly specially steps and related to those three figurs which you showd us. i tryed but failed.
can you explain it again in more detail. and in an easy way.π
(Sorry for inconvinice)
π -
shalini_goel14[Day6 -Class ..contd.]
Constructors
Sometimes there is a case when we want the member variables of any class to be initialized with values (can say assigning defult values to member variables) whenever a new object is created.So this kind of automatic intiaation is done through the use of constructors.
A constructor is just like a method but the only difference is they never have a return type, not even void. A constructor intializes an object immediately upon creation. It has the same name as that of class in which it is present.
Note: The implicit return type of any constructor is the class type itself.
Look at the following program that makes the constructor of CrazyEngineers class
package myjava; /** * * @author shalinig */ class CrazyEngineer { String memberName; String engineeringTrade; String location; /* Constructor is created */ CrazyEngineer() { System.out.println("Constructing default Crazy Engineer"); memberName = "CEMember"; engineeringTrade = "Crazy Engineer"; location = "CE Forum"; } //write profile in one line StringBuilder printProfile() { StringBuilder profileInOneLine = null; profileInOneLine = new StringBuilder(memberName + " is a crazy "); profileInOneLine.append(engineeringTrade + " engineer"); profileInOneLine.append(" located in " + location + ";"); return profileInOneLine; } } public class CEConstructor { public static void main(String[] args) { CrazyEngineer crazyEngineerObj = new CrazyEngineer(); StringBuilder profileInOneLine = null; //calls the method that returns StringBuilder object profileInOneLine = crazyEngineerObj.printProfile(); //prints the profile in one line System.out.println("Profile is:::" + profileInOneLine); } }
Output:
Constructing default Crazy Engineer
In above program whenever following line is called, consructor CrazyEngineer() is also called everytime setting the value of member values as specified in the constructor. If no values are assigned then it assigns default values by itself.It assigns default value as zero to all instance variables.
Profile is:::CEMember is a crazy Crazy Engineer engineer located in CE Forum;
Note :Even if we don not create a constructor ,Java creates a default constructor for the class everytime.
Parametrized Constructors
The way we pass parameters to methods, in the same way we can pass parameters to a consructor. These types of constrcutors are helpful when I don't want default values to my all objects of same class.Instead I want to change them with different values for each object of same class. In that case we use parametrized constructors.
Look at the following example
package myjava; /** * * @author shalinig */ class CrazyEngineer { String memberName; String engineeringTrade; String location; /* Paramerized Constructor is created */ CrazyEngineer(String m, String e, String l) { System.out.println("Constructing default Crazy Engineer using parameters"); memberName = m; engineeringTrade = e; location = l; } //write profile in one line StringBuilder printProfile() { StringBuilder profileInOneLine = null; profileInOneLine = new StringBuilder(memberName + " is a crazy "); profileInOneLine.append(engineeringTrade + " engineer"); profileInOneLine.append(" located in " + location + ";"); return profileInOneLine; } } public class CEParamterizedConstructor { public static void main(String args[]){ CrazyEngineer crazyEngineerObj1 = new CrazyEngineer("CEMember", "Crazy Egineer", "Ce Forum"); CrazyEngineer crazyEngineerObj2 = new CrazyEngineer("shalini_goel14", "Computer Science", "India"); StringBuilder profileInOneLine = null; //calls the method using crazyEngineerObj1 object profileInOneLine = crazyEngineerObj1.printProfile(); //prints the profile in one line System.out.println ("Profile1 is:::"+profileInOneLine); //calls the method using crazyEngineerObj2 object profileInOneLine = crazyEngineerObj2.printProfile(); //prints the profile in one line System.out.println ("Profile1 is:::"+profileInOneLine); } }
Output:
Constructing default Crazy Engineer using parameters
So in above programs two objects are created and each of them is intialized with different values.
Constructing default Crazy Engineer using parameters
Profile1 is:::CEMember is a crazy Crazy Egineer engineer located in Ce Forum;
Profile1 is:::shalini_goel14 is a crazy Computer Science engineer located in India;
[Assignment:
Qn1 Write the same program for calculating the area of a rectangle using both kind of constructors setting default values as 10.0 and 20.0 as breadth and length respectively.
Qn2 Write a short note on "this" keyword along with sample CrazyEngineer class program
]
[ So now I take a leave and with this I end up Day6-class.Hope you people are still following the thread. π . I am waiting for more and more participation of you guys in asking questions. ] -
kavihi,
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.
#-Link-Snipped-# -
shalini_goel14
Thanks for good words and correcting me but I am wondering how could you find "Java is said to be platform dependent " in my first post. Long time back, it was corrected and I could not find it anymore.πkavihi,
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.
-
Saandeep SreerambatlaHello people is "String[] args" this necessary to declare ?
What inputs we are giving to the main function. -
Yamini LThe phrase String[]args says that main()has a parameter which is an array of String references.The elements of the array refer to String that contain text from the command line that starts the program.
If you give any input at command line then this String array would accept and store those values.If not,it remains with null value.Also,instead of args you can use any other valid name in JAVA..
for ex,
C:> java programname str1 str2
Now args[0] contains str1 and args[1] contains str2
Do have a look at this simple program wherein command line argument is used..
import java.io.*; class command { public static void main(String args[]) { System.out.println("HAI " +args[0]); } }
Output
C:\Documents and Settings\USER1\Desktop>java command CrazyEngineer
Here CrazyEnginner is the command line argument..
HAI CrazyEngineer
Also see what happens when you dont give String[] args in main function
import java.io.*; class command { public static void main() { System.out.println("HAI " ); } }
C:\Documents and Settings\USER1\Desktop>javac command.java
C:\Documents and Settings\USER1\Desktop>java command
Exception in thread "main" java.lang.NoSuchMethodError: main -
shalini_goel14Thanks miniy for saving my time and efforts π
-
Yamini L
Most Welcomeπ..Probably if the query would have been a bit tough, i would have left it for you;-)..shalini_goel14Thanks miniy for saving my time and efforts π -
shalini_goel14Assignments of Day 6 class is pending for everyone here. π . If any problems in that, please do ask here.
[Day 7 class ]
Overloading Methods
Method overloading is just like functional overloading of C++. Same method within the same class have same names but their signatures may vary(By signature we mean no of parameters passed to the method.)
For method overloading, it is necesary that parameters type or count should vary in method signatures.
Example:
package myjava; /** * * @author shalinig */ class Demo{ void method(){ System.out.println("Method with no parameters and no return values."); } void method(int a){ System.out.println("Method with parameter a="+a+" and no return values."); } void method(int a, float b){ System.out.println("Method with parameter a="+a+" b="+b+"and no return values."); } double method(double c){ System.out.println("Method with parameter c="+c+" and return values as c="+c); return c; } } public class MethodOverloading { public static void main(String args[]){ Demo demoObj = new Demo(); int a=10; float b=20; double c=30; double returnVal; demoObj.method(); demoObj.method(a); demoObj.method(a,b); returnVal=demoObj.method(c); System.out.println("Value returned is :"+returnVal); } }
Output:
Method with no parameters and no return values.
In the above shown program,
Method with parameter a=10 and no return values.
Method with parameter a=10 b=20.0and no return values.
Method with parameter c=30.0 and return values as c=30.0
Value returned is :30.0
void method() is a simple method with no parameters and return type also as void i.e no value is returned.
void method(int a ) differs with the above method in that, it includes one additional parameter passed of int type.
void method(int a, int b) differs with the above method in that, it includes one more additional parameter passed of float type.
double method (double c) differs in many aspects in all the above programs. It passes a return value of double type and also it is passed a parameter of different type.
Note In method overloading, it is always necesarry to change the parameters-list passed to the method.
e.g in above program, if I add following method declarations , program will not compile
double method(){
Reason is because only change in return type of method will not lead to method overloading, methods parameters-list(either type or number) ould always change.
//some body
}
double method(int a){
//some body
}
double method(int a, float b){
//some body
}
Overloading Constructors
Similar is the case with Overloading with constructors
Recursion
Recursion is the process of calling a method again and again. A method that calls itself repeatedly is called as a recursive method.
Command line Arguments
[Already explained by miniy -check the thread carefully]
[Assignment:
Qn 1: Write a sample program showing overloadng of constructors.
Qn 2: Write a sample program showing overloading of methods just as example shown above but parameters passed should be of object type(not PRIMITIVE DATA TYPES)
Qn3 : Write a recursive program to find out the factorial of any number.
] -
Saandeep SreerambatlaThankyou yamini for the quick reply.
π -
Yamini LAssignment Day 5 class
Qn1 Write the same program for calculating the area of a rectangle using both kind of constructors setting default values as 10.0 and 20.0 as breadth and length respectively.
import java.io.*; class Rectangle { int m,n; Rectangle() { System.out.println("Parameterless Constructor"); m=10; n=20; } Rectangle(int a,int b) { System.out.println("Parametrized Constructor"); m=a; n=b; } void display() { System.out.println("Area of Rectangle is " + (m*n)); } } class Rectdemo { public static void main(String args[]) { Rectangle r1=new Rectangle(); //parameterless constructor overloaded r1.display(); Rectangle r2=new Rectangle(10,20); ..parametrized constructor overloaded r2.display(); } }
output
C:\Documents and Settings\USER1\Desktop>javac Rectdemo.java
Qn2 Write a short note on "this" keyword along with sample CrazyEngineer class program
C:\Documents and Settings\USER1\Desktop>java Rectdemo
Parameterless Constructor
Area of Rectangle is 200
Parametrized Constructor
Area of Rectangle is 200
The keyword "this" is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid
name conflicts.It just provides a reference to the current object β the object whose method or constructor is being called. You
can refer to any member of the current object from within an instance method or a constructor by using this.
import java.io.*; class CrazyEngineer { String name; String location; CrazyEngineer() { this.name="abc"; this.location="India"; } CrazyEngineer(String name,String location) { this.name=name; //name and location refers to insatance variable this.location=location; //this.name and this.location refers to instance variable } void display() { System.out.println( " " +name+ " is a CrazyEngineer located at " +location); } } class CE { public static void main(String args[]) { CrazyEngineer c1=new CrazyEngineer(); //object creation c1.display(); CrazyEngineer c2=new CrazyEngineer("xyz","USA"); CrazyEngineer c3=new CrazyEngineer("def","UK"); c2.display(); c3.display(); //display } }
Output
C:\Documents and Settings\USER1\Desktop>javac CE.java
C:\Documents and Settings\USER1\Desktop>java CE
abc is a CrazyEngineer located at India
xyz is a CrazyEngineer located at USA
def is a CrazyEngineer located at UK -
shalini_goel14If anyone here is following this thread, do let me know then only I will continue it further
Before tellling me please make sure you show interest in doing assignments or asking questions.OK -
Yamini LI am following this thread mam..I had JAVA in my curriculum..But still learning it in this way,its totally different and I really enjoy ..As of now,i dont have any doubts..I am waiting for other topics..Please continue your classes:smile:..
-
shalini_goel14
Thanks for such a sweet reply π but miniy you already know java. You are rather helping me here. I was asking rest of the people here-the old followers of this thread.miniyI am following this thread mam..I had JAVA in my curriculum..But still learning it in this way,its totally different and I really enjoy ..As of now,i dont have any doubts..I am waiting for other topics..Please continue your classes:smile:.. -
mgautam1991Hey thanks,
Im a first year CSE student,
I dont knw even d basics of java....
Wishin to be a part of your process....
Please help me through..... -
sarveshguptaπ great effort! i joined in today.. so can you please tell me which jdk i hav to download jdk 6 update12 or jdk 6 update12 with java EE
-
sarveshguptagreat effort! i joined in today.. so ca u tell me which download to do - jdk 6 update 12 or jdk 6 update 12 with java EE?
-
shalini_goel14
Hi mgautam, Welcome to the class. Please ask what specific help you need here. There are lot of things in Java to tell ok.mgautam1991Hey thanks,
Im a first year CSE student,
I dont knw even d basics of java....
Wishin to be a part of your process....
Please help me through.....
No need of Java EE, only J2SE ok. Please show your regularity and interest here in asking questions and asignments, then only class will be continued further.sarveshguptaπ great effort! i joined in today.. so can you please tell me which jdk i hav to download jdk 6 update12 or jdk 6 update12 with java EE -
utirhanshi.......
I must say its a vry gud initative nd even i want to join this......
can i join it now????? -
gohmSure! Tell us about yourself in the introduction forum, read all the sticky topics on rules of CE then post away! We look forward to your contributions!
-
shalini_goel14
Yes you can join by asking questions/doubts till now.utirhanshi.......
can i join it now?????
Please check following two linksfirst π
#-Link-Snipped-#
#-Link-Snipped-#
Thanks -
TRIDSSISTTIME OUT....For a funny story!
Hi! I just became a part of this forum here and I would love to be a part of it. I love contributing to the community.I can probably add some humour to start with. Here are some funny stories that I read somewhere.A patient comes to a Dentist with a tooth pain.Dentist : Two of you teeth are infected and we need to extract them.Patient: How much will it cost?Dentist: Seven hundred and fifty dollars for both.Patient: What? Seven hundred and fifty dollars for 10 minutes of work?Dentist: Well, if you like, I can pull them out slowly! Here is another one:Husband and wife have just left their home for camping. Wife: We should turn the car back! I forgot to turn off the gas stove and it might burn our appartment! Husband: It's okay, the apartment will not burn, I forgot to turn off the shower.The last one:A trial is in progress in the court room.Lawyer: Your Honour, if a person has 18 criminal records he is not a criminal. Judge: Then who is he? Lawyer: He is a Collector.Thanks for reading. I hope you enjoyed it. -
hridesh007very good man.... looking forward for more...
____ ****_____ -
shalini_goel14Re: TIME OUT....For a funny story!
Welcome to CE Mr/Ms TRIDSSIST !TRIDSSISTHi! I just became a part of this forum here and I would love to be a part of it. I love contributing to the community.I can probably add some humour to start with. Here are some funny stories that I read somewhere.A patient comes to a Dentist with a tooth pain.Dentist : Two of you teeth are infected and we need to extract them.Patient: How much will it cost?Dentist: Seven hundred and fifty dollars for both.Patient: What? Seven hundred and fifty dollars for 10 minutes of work?Dentist: Well, if you like, I can pull them out slowly! Here is another one:Husband and wife have just left their home for camping. Wife: We should turn the car back! I forgot to turn off the gas stove and it might burn our appartment! Husband: It's okay, the apartment will not burn, I forgot to turn off the shower.The last one:A trial is in progress in the court room.Lawyer: Your Honour, if a person has 18 criminal records he is not a criminal. Judge: Then who is he? Lawyer: He is a Collector.Thanks for reading. I hope you enjoyed it.
Can't believe it that you are really an engineer and you joined and made a first post in this thread. * God save this site from such people *
Dear TRIDSSIST ,FYI, this is neither a joke related thread nor this site is a joke. If you want to add your humour kind of stuff-jump over to the famous junk sction of this forum. Our engineers here have started lot of funny threads there π
#-Link-Snipped-#
PS: Avoid any such posts in this thread further. π
Thanks -
silverscorpionha ha, I can hear Shalini shouting,
"Hey, you chose to spam MY thread. How dare you??!! I will kill you!!π‘π‘" -
markkIt's a shame I didn't spot this thread earlier, I could have joined in.
-
shalini_goel14
So who is stopping you from joining now? By the way what you studied in this thread till now? Don't forget to ask questions and doing assignments πmarkkIt's a shame I didn't spot this thread earlier, I could have joined in. -
markkI thought that because I have missed the first six days lessons and not handed in the homework then I will be really behind the rest, does that not matter?
-
shalini_goel14
It doesn't matter at all. If you will show interest, you will get class on more topics also in Java . Just don't get lost here after some time. πmarkkI thought that because I have missed the first six days lessons and not handed in the homework then I will be really behind the rest, does that not matter?
Happy learning Java π ! Glad to have such a nice student in my class. -
utirhansi'm done with my introductions.....
just wanted to know what i'm supposed to do next....... -
shalini_goel14
Do start reading this thread from start and if some thing is going overhead- Please ask any kind of questions here .OK π Rest is my work.utirhansi'm done with my introductions.....
just wanted to know what i'm supposed to do next.......
Thanks -
Yamini LGuys,please dont make this thread deadπ.Do learn JAVA and start asking questions,if you really dont understand something.Shalini mam is there to help us all out.
On behalf of the followers of this thread,i would just like to say that we all are looking forward for your class on more topics in JAVA mam:smile:. -
shalini_goel14Sure miniy, I will try to continue further. I got one more way of making people's interest in this thread. Lets see how much it works π
So now idea is - I will throw a question for you all, so called "Already perfect Java Programmers" π . If any of you answers within my own specified time limits, you will get next question and like this series of questions and if at point of time none of you answers, I will give class on that specific topic only amd then you have to answer the question. OK
You guys are also free to tell me to take class on which particular or difficult topic of Java. OK π
So here goes my simple question :
class MyClass{
public static void main(String args[]){
int[][] a={{1,2},{3,4}} ;
int[] b=(int[]) a[1];
Object o1=a;
int[][] a2=(int[][]) o1;
int[] b2=(int[]) o1;
System.out.println(b[1]);
}
}
What is the result? Explain properly Please ? -
ms_cs
Exception Name : ClassCastException I think...I did not Run..shalini_goel14int[] b2=(int[]) o1;///
It is not possible ..Exception will be thrown... -
shalini_goel14
Well, it was damn easy to find just by running it on your system.ms_csIt is not possible ..Exception will be thrown...
That's why I asked you to "Explain properly Please" so please explain which exception will be thrown and why it is thrown. Explain clearly OK. We have few dumb people also. π
Thanks -
ms_cs
As a CS students We got these type of questions in semester exams too...shalini_goel14So now idea is - I will throw a question for you all,
You guys are also free to tell me to take class on which particular or difficult topic of Java. OK π
So here goes my simple question :
We 's want something tough...It may be also from theoretical part too... -
ms_csLet we see How shalini makes 's π....
It is challenge to you...You have to make π... -
shalini_goel14
I accept your challenge but first you have to explain properly my last asked question ok.ms_csLet we see How shalini makes 's π....
It is challenge to you...You have to make π...
PS: Never throw back questions to the person who is asking questions. A tip for you if you are preparing for interview π -
ms_csException Name : ClassCastException ,I think...I did not Run..
Reason : o1 is of the type, two dimensional array...
It is not possible to typecast it into a One Dimensional Array...
Shalini...If I was wrong with my answer..Please Do correct me... -
shalini_goel14Well, Good Senthil, I give up before you. You are very smart. π
People like me don't have capability of acceptng challenges of people liek you.
OK As a award for answering right and quick, Will you do me a favour now? Can you give a special class here on "Type Casting"? -
ms_cs
One small correction here I think...shalini_goel14People like me don't have capability of acceptng challenges of people liek you.
People like ___ don't have capability of acceptng Shalini's challenges ...
π -
arbiffileNice post.
I'm new to the forum. Nice post. -
shalini_goel14Re: Nice post.
Hi arbiffile !arbiffileNice post.
Really very nice post by you π
By the way what made you to make such a post here? π Was it a trial post? I think then we should have a "Trial" section for people like you to make sample posts there. :sshhh: -
Anil JainRe: Nice post.
Calm Down fellas !!shalini_goel14Hi arbiffile !
Really very nice post by you π
By the way what made you to make such a post here? π Was it a trial post? I think then we should have a "Trial" section for people like you to make sample posts there. :sshhh:
@ Shalini - He is a newbie we can explain him and hopefully he will take care of this thing in future.
@ arbiffile - Its a technical thread and we have a separate section as #-Link-Snipped-# where you post this type of posts.
@ ms_cs - Even if you know answers you should not make mockery of the question (As a CS students We got these type of questions in semester exams too...
), it may be useful for other non CS guyz.
@ Shalini -PS: Never throw back questions to the person who is asking questions. A tip for you if you are preparing for interview :wink:
- Nice thoughts.
Apology, If you felt that this is spamming, I was tryingto chill down the atmosphere.
-Crazy -
shalini_goel14
Hi livewirelivewire09Thanks for making things light and easy for the new comers.I know Java is one tough subject but one has to crack it there are no 2 options I guess.What is Java Action Scripting anything similar?
Good question. Even I was not aware of Java Action Scriting till now but just now checked it out. It includes syntax of both Java and ActionScript so ultimately we get a combination of programming language +scripting language. I don't think there is anything similar. π
FYI check following link:
#-Link-Snipped-#
Actionscript
If anyone here has more idea about it, please put some more light on it.
Thanks -
shalini_goel14[Special class on: Type Conversion and Type Casting]
Type Conversion is assigning a value of one type to variable of another type. If both the types are comaptible and destination type is bigger than source type, then java do automatic conversion(also called as widening conversion).
Type Casting : When both the types are compatible but destination type is smaller than source type , then 'cast' is used to assign value of bigger type to a variable of smaller type.
Here goes the list of datatypes in descending order of their size
Integers
1. long (64 bits/8 bytes)
2. int (32 bits/ 4 bytes)
3. short (16 bits/2 bytes)
4. byte (8 bits/ 8 bytes)
Floating Point types
1. double (64 bits /8 bytes)
2. float (32 bits/ 4 bytes)
Characters
char (16 bits / 2 bytes)
Boolean
boolean (Machine dependent)
Now what all types are compatible
1.The numeric types including integer and floating point types are compatible with each other.
2. Numeric types are not comaptible with char and boolean .
3. char and boolean are not compatible to each other.
Now when java do automatic conversion
1. When two types are comaptible.
2. Destination type is bigger than source type.
Now if we look at the size of types mentioned above and check compatibility , it is seen that types compatibilty hierarchy is byte >short > int> long > float > double
So double being the biggest type can be assigned any of type from byte to double (following hierarchy). Check the following example for this:
package src; public class TypeConversion { public static void main(String[] args) { long longType=625578; int intType=625578; short shortType=31257; byte byteType=127; float floatType=2578.96f; double doubleType; /* assigning byte to double without casting*/ doubleType=byteType; System.out.println("[ double d= byte "+byteType+" ] ="+doubleType); /* assigning short to double without casting*/ doubleType=shortType; System.out.println("[ double d= short "+shortType+" ] ="+doubleType); /* assigning int to double without casting*/ doubleType=intType; System.out.println("[ double d= int "+intType+" ] ="+doubleType); /* assigning long to double without casting*/ doubleType=longType; System.out.println("[ double d= long "+longType+" ] ="+doubleType); /* assigning float to double without casting*/ doubleType=floatType; System.out.println("[ double d= float "+floatType+" ] ="+doubleType); } }
Output is:
[ double d= byte 127 ] =127.0
Now considering the reverse case when we want a double value to be assigned to byte type or want to go in reverse direction in compatibilty hierarchy. To do so casting is done.
[ double d= short 31257 ] =31257.0
[ double d= int 625578 ] =625578.0
[ double d= long 625578 ] =625578.0
[ double d= float 2578.96 ] =2578.9599609375
Syntax for casting is : (target-type) value
where target-type specifies the desired type to convert the specified value to.
e.g if syntax showing how to assign an int value to byte variable
int a;
byte b;
//some code here..
b =(byte) a;
Now check the following example:
package src; public class TypeCasting { public static void main(String[] args) { double doubleType=25678.956; float floatType=2578.96f; long longType=625578; int intType=625578; short shortType=31257; byte byteType; /* assigning double to byte using casting*/ byteType=(byte) doubleType; System.out.println("[ byte b= double "+doubleType+" ] ="+byteType); /* assigning float to byte using casting*/ byteType=(byte) floatType; System.out.println("[ byte b= float "+floatType+" ] ="+byteType); /* assigning long to byte using casting*/ byteType=(byte) longType; System.out.println("[ byte b= long "+longType+" ] ="+byteType); /* assigning int to byte using casting*/ byteType=(byte) intType; System.out.println("[ byte b= int "+intType+" ] ="+byteType); /* assigning short to byte using casting*/ byteType=(byte) shortType; System.out.println("[ byte b= short "+shortType+" ] ="+byteType); } }
Ouput:
[ byte b= double 25678.956 ] =78
Now you might be wondering that the value shown in output is very much different from that assigned to the variable Right?
[ byte b= float 2578.96 ] =18
[ byte b= long 625578 ] =-86
[ byte b= int 625578 ] =-86
[ byte b= short 31257 ] =25
Note:
a) If the value of source type is larger than the range of the assigned variable(in above case byte), it will be reduced to modulo destination type range(in above case byte)
b) If floating point value is assigned to an integer value, fractional part is lost because integers don't have fractions (this is called as truncation).
c) Also if again the whole number component of truncated value is larger to fit into destination type, modulo operation is followed(Note no. a)).
So this was basic about type conversion and type casting
[Assignment:
Qn Which of the following pieces of code would COMPILE and RUN successfully (Note both COMPILE + RUN ) and WHY ? If any one don't compile, suggest an ALTERNATIVE remedy for it. If it compiles fine what will be output value of 'b' in each case?
a) byte b =3;
b) byte b =128;
c) byte b = b +c ;
d) int a =100;
long b= a ;
e) float f=100.001f;
int b=(int) a;
f) double d=100L;
g) int b=3957.229 ;
h) long l=56L;
byte b = (byte) l;
g) byte b =3;
b+=7;
h) float b=32.2;
i) float b=32.3f;
j) float b=32.3F;
k) float b= (float) 32.3;
]
[spam]
If anyone has any issues/problems with the length of this thread making it difficult for readers to grasp things, Please request mods/admin to split it into separate separate threads, the way you/they want. π
[/spam]
Feel free to ask any questions/doubts till now.
Thanks
-
saniasHey good to know that these kinda helpful threads exist! I am interested in knowin more about the same too... kindly give me more details plz
-
shalini_goel14
Hi saniassaniasHey good to know that these kinda helpful threads exist! I am interested in knowin more about the same too... kindly give me more details plz
In what topic you are more interested here? What kind of details you need? π -
sreenidhibs
i think i found a small error ,shouldnt the byte take one byte( instead of 8).shalini_goel14[Special class on: Type Conversion and Type Casting]
Type Conversion is assigning a value of one type to variable of another type. If both the types are comaptible and destination type is bigger than source type, then java do automatic conversion(also called as widening conversion).
Type Casting : When both the types are compatible but destination type is smaller than source type , then 'cast' is used to assign value of bigger type to a variable of smaller type.
Here goes the list of datatypes in descending order of their size
Integers
1. long (64 bits/8 bytes)
2. int (32 bits/ 4 bytes)
3. short (16 bits/2 bytes)
4. byte (8 bits/ 8 bytes)
answers to assignment coming soon. -
saniasWell actually i am gonna just start off my course... and i am planning to go for a laptop i found a student offer for a mac.. . but then people are saying they are not compatible? and stuff?
-
George453Hi
Hi,
This is a wonderful opinion. The things mentioned are unanimous and needs to be appreciated by everyone.
George,
-
Sorcerer-Entityits really a great thread for new comers thanks for such a good thread
-
madhumurundihi, shalini can i have your email id plz..i need guidence from you about some courses..plz..you can send me a test mail to this id--> #-Link-Snipped-#
-
foryounowOh, very useful thread, how I was afraid of Java.
-
aashu_itdudeHi all,
I need to know how can we accept input through a microphone using java? I want to record sound using it and then process it for some other task like a speech to text converter.
please help -
Kaustubh Katdare@ashu_itdude: Post your question in a separate thread. This thread is only for the discussions related to tutorial.
-
sumitjamiMAM PLEASE MAY I COME IN.....?
Actually i am back after a few months and missed whole of this forum......
but today when i saw your thread i felt it so interesting that i read the whole thread and all the complete classes in a single day.........yes i have not done any of the assignments because i already have that basic knowledge in java.......i can assure you this as i have already done a few projects in java.
I really liked your thread a lot and kindly request you to please continue.....can you please largely elaborate on the io classes in java......i find them really confusing
THANKX
MAM PLEASE MAY I COME IN.....? -
shalini_goel14Hi Sumit,
Glad to know that you have done projects in Java. π
1. First thing stop making fun of me by calling "MAM" or using words like "MAM PLEASE MAY I COME IN.....? ". Its very irritating .
2.
Glad to hear that people can cover such big threads in a single day also. πsumitjamiwhen i saw your thread i felt it so interesting that i read the whole thread and all the complete classes in a single day
3.
Even if you know Java more than me , then also there is no harm in helping rest of the world by answering those few questions which requires only your 1% of time.sumitjamiyes i have not done any of the assignments because i already have that basic knowledge in java
4. Sure, I will soon come up with "IO classes in Java" but before that can you give me an idea about what kind of confusions you are getting in it?
Thanks ! -
Rohan_sKHi Shalini,
I am not from the computer branch, so I dont have much knowledge about these programming languages. Except C++ which I learned as a part of my curriculum ( that too just sneaked through the paper) I have not tried to learn any other language, rather didint feel the direct necessity.
But after seeing this thread my interest is rising in this field. And firstly a huge compliment to you for such an initiative taken by you. So can you please enlighten me as much as you can on how Java or any other language can be of direct benefit and use for a Mechanical engineer( we only use reeady made softwres like autocad, catia etc.) like me. This detailed thread has really tickled my interest and desire to learn a new thing, so can you please guide me. Do let me know.
Thanks -
shalini_goel14
Yes sure Rohan_SK π but can you share your knowledge about autocad and catia.(Yes ofcourse in new thread π ) as I don't know much about it .Rohan_sKHi Shalini,
So can you please enlighten me as much as you can on how Java or any other language can be of direct benefit and use for a Mechanical engineer( we only use reeady made softwres like autocad, catia etc.) like me. This detailed thread has really tickled my interest and desire to learn a new thing, so can you please guide me. Do let me know.
Thanks -
Rohan_sKOk Shalini, Thanks for replying. And I got a question back in return of a question:dance:, wow!! Anyway are you really unaware of Autocad and Catia ...lol..π² is it so ...
And what made you think I will not share my knowledge?
For the answer , they are softwares used for designing and modelling of prototypes and mechanical components or designs. The newer version of autocad has even better features and better visualisation of the design.There are others like solidworks, pro-e also.
And I will try to give some info on the topic in the fututre, when I can give it some time; but I wont make a commitment right now. I hope to do it someday and you'll know itfor sure:smile:
Anyway, my question to you still remains unanswered. How can Java be benificial to a Mechanical engineer??
Do educate us.
Thanks and best luck!! -
shalini_goel14@Rohan_SK Mechanical engineer students can use it in making Robots and also for automation of various machinery tools which can be programmed using Java.
I would say few words to you : Try to make any mechanical part and try to automate it using some programming and that too using Java rather than C or C++. No harm in always giving a trial rather than saying "I cannot do"
Correct me if I am wrong this machinery part designing and creation is what mechanical engineers do right? -
Rohan_sKshalini thanks for letting me know where Java can be used in the Mechanical field. I actually wanted to know whether Java could be directly used in the core mechanical field. As for robotics, let me tell you that Robotics is a very specialised field in the Mechanical branch. It was well realised that robotics just not involves the core mechanical subjects , but also the other prime required subjects like basic electronics, hardware, microprocessors, software programming, electrical components. And these subjects cant be integrated with the basic mechanical subjects in a four year course. Thus very rightly these days Robotics is seperated from core mechanical and made into an independent stream. This is exacctly why Mechatronics is altogether a different ball game and a individual stream.
It is not expected from a Mechanical engineer to know a full fletched programming language, it is not a NECESARY REQUISITE but can be only an ADDED ADVANTAGE for certain domains and profiles. In fact a very basic language like C++ and the designing and modellling softwares which I mentioned earlier very much do the job in the core mechanical industry, which we are quite versed with.. This is exactly the reason that we never had a professional necesity to learn another language in depth, well it would be a different case if someone was really keenly interested in the programming field.
I am sure you must be knowing this as a software professional that you are not expected to know the technical details pertaining to the mechanical aspects of any mechanical project you handle. You guys must be involved with only the software development part of it and the mechanical engineers must be taking care of the mechanical design part, isnt it. Please correct me if I am wrong here. Itherwise you guys would have gone places learning subjects like Vibrations, IC Engines, Dynamics of Machinery, Power plant and what not.
I actually couldnt figure out how you thought that I say that " I cannot do " something even without trying it.
I suppose that you concluded it from my statement " I did not feeel the necessity to learn another programming language" which I made earlier. But i think you should have given little more effort to ponder and figure out what I actuaally wanted to convey, which I have explained above.
I was wondering if your " few words for me" were some sort of a cynical sarcasm.... or a constructve friendly advice. If its the latter then point well taken. And thats exactly why I am trying to learn a new thing to enhance my skills and add another tool to my arsenal. If it was otherwise I think I have answered you.
Anyway for your last point, Yes we are the ones who have been designing and manufacturing machinery and machine components right since the medival times till now and ofcourse in the future. Afterall ours is the mother branch from which all other modern day streams have evolved. And Yeh, we are also involved in the design of one of your basic systems ie the heat transfer rates in your CPUs ( otherwise they would have fried up in no time).
thanks and have a nice time. -
ms_csI read that initially java much used for embedded system design. But for robotics I did not heard about design and working done using java. What are the resources available to program the robot using java, ie., what are the api's. Is it possible?
-
shalini_goel14[SPAM]
Hey Mr Rohan_SK I am so sorry to say that I don't have time to waste in reading your essay type post. May be reason is in a very quick read I found words like "sarcasm" and "cynical" .I am avoiding discussing such posts.If you still want to discuss such issues with me, don't spoil MY THIS thread , start your own thread , I will discuss it there. If you don't want to learn Java, DON'T DO. OK. Its your life , your thing, do whatever you want. OK
@ms_cs I said so because somewhere Scorpion in his Robotics thread mentioned so OK . No more arguments Please.
[/SPAM] -
gohmI apologize for the off topic intrusion. I'd like to suggest that all participants please keep this thread on topic and all parties remain respectful to each other. This will allow the thread to continue to be of service. Thanks everyone for a great thread discussion.
-
Rohan_sKMs Shalini neither do I have the time to entertain your blabbering. I have never tolerated anybodys NONSENSE and you are NO EXCEPTION to it.
If you dont have the common sense and etiquette left to simply understand what the other person is trying to say actually, without any offence made in the first place, then its not my fault.
And once again dont jump to your weird conclusions of me NOT WANTING TO LEARN JAVA, anyway you are free to draw any conclusion you want, I have no control over your brain.
And stop giving UNWANTED ADVICES ( that too pumped with ego) to others when your not asked for; it will HELP you in life.
@ Gohm- I am sorry Gohm, but youre a friend , you can understand. I too am not interested in entertaining anybodys attitude, but If someone is continously directing awful statements at me then I reserve all the right to answer back.( especially when I didnt start it)
Anyway I dont have the time to read anyones crap anymore , we've got much better things to do on this forum, isnt it?? And always Respect to you gohm , your a friend!! -
Kaustubh KatdareI request all participants to be respectful. We are not here to make fun of each other or be sarcastic in posts.
@ Shalini: I believe this thread is too long already for new members to read and participate. Would you mind limiting the posts to 50 and starting a new thread for each new topic? π -
shalini_goel14@Gohm and @Big_K Then what/who is stopping you people to mark this thread as "Closed" ? Use your powers
-
Kaustubh KatdareWe need permission from the thread owner to do that because this is one very useful thread on CE.
-
shalini_goel14OK . Close it.
-
silverscorpionNot yet closed, I guess!!
-
Kaustubh KatdareI believe this thread should be left open as there could be questions about topics discussed in this thread.
It would help if the new topics in this initiative are covered under separate new threads. -
shalini_goel14
OK then is it not possible to break its separate topics and related questions to that particular topic in separate threads and then this thread can be closed?The_Big_KI believe this thread should be left open as there could be questions about topics discussed in this thread.
It would help if the new topics in this initiative are covered under separate new threads. -
Ashraf HZAh, what a little misunderstanding can cause!
Shalini, try to copy the "permalink" of the beginning of each class in this thread and create a mini table of contents at your first post by editing it. Once that is done, perhaps we can then close it and your future classes will have their own threads. -
Kaustubh KatdareIt will be bit difficult for me to do so as I haven't been following this thread closely π
How about covering each new topic in a separate thread from now on? Let's leave this thread as it is. -
Ashraf HZYes, thats why Shalini is the best one to do it π
It will help those new CEans who want to follow it. -
shalini_goel14
Good solution ash. I will surely do that soon but still it would not be in exact table format as I guess tables are not allowed in posts.ashShalini, try to copy the "permalink" of the beginning of each class in this thread and create a mini table of contents at your first post by editing it. Once that is done, perhaps we can then close it and your future classes will have their own threads. -
shalini_goel14Ash, as per your suggestion I have updated my first post here, if you feel this thread looks better if get closed then Please do so. I will start new topics in separate threads or don't do if you want me to continue in this only.
Thanks ! -
gohmIt is getting a bit long. maybe a java II thread is in order? java threads on topics?Tough for newbies to read the whole thread to pick up the discussion.
I just wanted to jump in and halt the impolite tone that was developing amongst some of the members. Thread closing is always a last resort as folks should be always allowed to voice their different opinions as long it is respectful. We have many unique and different personalities and that should be allowed as a forum is a group and that is life. -
enthudrivesI have a doubt. Why is the statement "package myjava;" used in all programs?
-
shalini_goel14
Hi enthudrivesenthudrivesI have a doubt. Why is the statement "package myjava;" used in all programs?
Very good question asked. Java is a package-centric language, so for good organization and name scoping we should put all our java classes into packages.
Consider a situation where there are 3 different programmers working on different parts of a project and write a class name "CrazyEngineers". Now if each of those programmers don't use package thing in their class then it would be very difficult for the JVM or compiler to identify which "CrazyEngineers" class (out of 3 versions available written by each programmer) to use.
Well, I have used myjava package for writing my made programs in my machine. That's why you could see "package myjava" in most of my programs here. Hope I answered you, if still any doubts feel free to ask. π
[ Note: Package statement should be very first line in your any Java program. ] -
Ashraf HZShalini, good work on making the table of contents!
Closing threads will also be useful in continuing discussions to another thread, rather than bumping it up all the time. Kind of like what we did for the CE Bot and CE Messenger threads π
Shalini, please start java part II whenever you can. Are you okay with having dedicated threads for each class? -
shalini_goel14
Yeah I have planned it to start in any case by this weekend. Lets see. I have no issues, you guys know more about this thread and posts thing. Well I like similar things at one place onlt thats why I ignored Big_K's idea of starting separate threads for each topic but after seeing it as an incoveneince to all, I agreed to this.ashShalini, please start java part II whenever you can. Are you okay with having dedicated threads for each class?
By the way , is it not possible to start new threads and related discussions now for topics I have already covered based on table created? My this thread is looking very bad to me now. All spoiled π‘ I want all my work to be maintained neat and clean, that's it? -
enthudrivesYeah. I started following this thread only yesterday. Its difficult for me to find out where I stopped reading yesterday. π
-
Kaustubh Katdare
It's something what we call experience :sshhh:shalini_goel14Well I like similar things at one place onlt thats why I ignored Big_K's idea of starting separate threads for each topic but after seeing it as an incoveneince to all, I agreed to this. -
shalini_goel14Guys ! No more classes here. If you cannot follow this thread, your bad luck .Sorry I can't help and if any of you want to know and learn about any specific topic in Java, just post the topic here and constantly keep on searching this forum for your mentined topic, may be you can find them someday at any point of time.
Happy never ending search. π
PS: Can call this post as sarcacism. π -
sarveshguptaHi Shalini
I want to ask whether you have done these programs in notepad or some IDE
If I want to download some IDE can you tell me which of the following packages i should download at the site
#-Link-Snipped-# -
sarveshguptaAnd also you have included
package myjava;
in your starting programs ( I have read till class of day2)
can you tell me what does this mean?
What is its use
Another thing I want to ask is that you have mentioned that if we want to change the template go to tools and so on is it referring to some editor?
Which editor/IDE do you use? -
shalini_goel14Hi sarvesh !
I have done all the program except first one using IDE [Sometimes Netbeans and some using Eclipse] . It is always better to download "All" option package but remember while installing keep all settings as default.[Don't change anything as it may ask for path of installed "Bundled Softwares" in your system. So you can uncheck those options while installing if you don't need them. I guess you wouldn't even need that for just making simple programs. If all what I am saying is sounding difficult to do, no issues -Simple go with "Java SE" version.sarveshguptaI want to ask whether you have done these programs in notepad or some IDE
#-Link-Snipped-#
Note: Make sure "JDK" is already installed in your system before installing Netbeans.
Any doubts feel free to ask. π
sarveshguptaAnd also you have included
package myjava;
What is its use
Another thing I want to ask is that you have mentioned that if we want to change the template go to tools and so on is it referring to some editor?
Which editor/IDE do you use?
- About "package myjava" -Check this post of mine #-Link-Snipped-#
- About editor - I prefer Netbeans over Eclipse for obvious reasons. Prefer Eclipse [Not Netbenas] when your system RAM is less.
- Regarding following this thread - Go to following link and change "Number of Posts to show per page" value to "Show posts 40 per page"
- Regarding Tools /Template thing. In Netbeans you get by default that option in your program. Yes you can change the template in that IDE. It is basically used for big organization to put copyrighted statements in every program's code.
Thanks ! -
shalini_goel14[ How to make a simple "Hello World" Java program in Netbeans ]
Check the following link showing stepwise how to make, build and run a Java program in Netbeans.
#-Link-Snipped-#
Thanks ! -
sarveshguptaThanks a lot Shalini yes you cleared my doubts very well
-
sarveshguptaCan you also throw some light on getting input from keyboard and the classes or keywords involved
-
sarveshguptaAnd For the package myjava;
I want to know what actually a package is to be a bit more clear
How do we create a package and where it is seen and how the classes are included in it..
Thanks in advance -
shalini_goel14sarveshguptaCan you also throw some light on getting input from keyboard and the classes or keywords involved
Sure sarvesh, it would be my pleasure to share my knowledge with you on "Getting input from key board" thing and "packages" in Java.sarveshguptaAnd For the package myjava;
I want to know what actually a package is to be a bit more clear
How do we create a package and where it is seen and how the classes are included in it..
Thanks in advance
Please give me some time and keep on asking more and more questions and things. π -
shalini_goel14[ Reading Input from Console in Java]
There are may ways of reading input from streams from console.It may be in the form of bytes, characters, objects etc. Before reading further this post, please have a look at following thread [Note: That thread is incomplete if anyone need further information on the same topic, let me know π ]
#-Link-Snipped-#
Reading input from console is mainly done by using "System.in"
All Java programs by default import the "java.lang" package. Now what is this package, for now just remember a package is nothing just a collection of java classes[ I will cover the packages separately] So "java.lang" is a prebuilt package provided by Sun. We can make our own packages also.
So now coming back to "java.lang" package only, at present we are concerned only about its "System" class now. This class as its name mentions everything , it encapsulates things related to runtime environment. So using this class we can access various system related properties and information. To look more closely about this class , check following link:
#-Link-Snipped-#
This class has 3 predefined variables. All are declared as "public static" . Now you might be wondering what does this "publis static" means. Public static means they can be used by any program without using any "System" object or instance.Example, you can use them directly like this - System.in, System.out, System.err. You need not to create its any instance in every program. So following are standard input and out streams.
1. System.in : It is an object of type "InputStream" class.Used to read charcaters from the console.
2. System.out: It is an object of type "PrintStream" class. Used to write characters to the console.
3. System.err: It is an object of type "PrintStream" class. Used to write error message on the console.
Now how to use them is simply wrap them in Character Stream classes and get the input in the form of characters. In fact there are many ways of getting input from users. It depends on you how to do that. Well, I prefer following way of taking inputs form users
1. Reading in the form of buffered characters or Strings
package myjava; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author shalinig */ public class ReadingInputAsStringsFromConsole { public static void main(String[] args) throws IOException{ String name; int age; InputStreamReader readerObj=new InputStreamReader(System.in); BufferedReader br =new BufferedReader(readerObj); System.out.println("Enter your name:"); name=br.readLine(); System.out.println("Enter your age:"); age=Integer.parseInt(br.readLine()); System.out.println(name+" is "+age+" years old"); } }
Output:
Enter your name:
Now let's see what is happening in above program
Shalini
Enter your age:
100
Shalini is 100 years old
InputStreamReader readerObj=new InputStreamReader(System.in);
In above two lines, System.in takes the input we give from console. Now to obtain character based stream , we need to wrap it in BufferedReader class but if you closely look at the constructors of this class , it is like this
BufferedReader br =new BufferedReader(readerObj);
BufferedReader(Reader inputReader)
Now Reader here is an abstract class and one of its concrete(inherited)classes is "InputStreamReader" which converts bytes to characters. Constructor of InputStreamReader looks like this
InputStreamReader(InputStream inputStream)
and as mentioned in the starting also, System.in is an object of type "InputStream" , so it can be passed to "InputStreamReader" class -like following
InputStreamReader(System.in)
and now for getting buffered characters form of input the above InputStreamReader class is wrapped in BufferedReader -like following
BufferedReader(new InputStreamReader(System.in)
So in this way we are converting input from console in the form of buffered character stream and reading it using readLine() method of BufferedReader class. Now point to be noted here is br.readLine() gives the String() object so if you want any integer or float or double kind of input, you will have to use parseXxx() method of corresponding Wrapper classes. Example, the way I have used in above program to get 'age' in int
age = Integer.parseInt(br.readLine());
Now what the above line does is , it takes String as an input and gives int as an output. So in this way you can get int(or float or double or long) type of data also in your program.
Feel free to ask if any questions in above program.
2. One more way of doing above program is using "DataInputStream". Have a look at the following program. It gives the same output as above.
package myjava; import java.io.DataInputStream; import java.io.IOException; /** * * @author shalinig */ public class ReadingInputasDataStreamFromConsole { public static void main(String[] args) throws IOException{ String name; int age; DataInputStream din = new DataInputStream(System.in); System.out.println("Enter your name:"); name = din.readLine(); System.out.println("Enter your age:"); age=Integer.parseInt(din.readLine()); System.out.println(name + " is " + age + " years old"); } }
Note this line in above program
DataInputStream din = new DataInputStream(System.in);
You need not to wrap it in InputStreamReader thing and all as was done in my first program. Reason is because DataInputStream is directly inherited by InputStream class but drawback is it do not provide buffering.
3. There is one more way using Console class, I guess it is not supported ny my OS or what but you can try it out in your system if it works for you. By that time, I will find out how can I make it working in my system. May be I am usin Netbeans that's why it is not working.
package myjava; import java.io.Console; /** * * @author shalinig */ public class ReadingInputFromConsole { public static void main(String[] args) { String name; int age; Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } System.out.println("Enter your name:"); name = c.readLine(); System.out.println("Enter your age:"); age = Integer.parseInt(c.readLine()); System.out.println(name + " is " + age + " years old"); } }
Output:
Case A: If it is supported by your OS, it gives same output as above two programs
Case B: If it do not work like in my system, it gives output as following
No console.
As this is a very vast topic but I tried to cover all relevant things related to "Reading input from Console" in minimum possible time here. If I will remind something missing, I will keep on adding here.
Java Result: 1
References : "Complete Reference in Java" and my own knowledge. Anyone can correct me if any wrong information imparted.
Feel free to ask questions/doubts. Thanks ! π -
sarveshguptaThanks Shalini...Thanks a lot
-
naveen029can u tell me why constructor not have any return type??
-
mayank1055Nice step. It will really help number of interested programmers.
-
xheavenlyxWhy isn't this sticky or in the Tutorial section?? How do new comers find it?
-
Varsha0802
The thread is very nice and helpful for those trying their hands in java. Shalini has done a very nice job!ππxheavenlyxHow do new comers find it? -
sonali singhi want to join this thread
-
sonali singhis anyone is here to help me fr this
-
sonali singhcan u plz tell me why constructor has no return type
-
Kaustubh Katdare@Sonali: You may ask your question in this thread or simply stat a new thread in the same section. Please describe your question in depth so that it's easier for others to answer. It takes time for members to read and respond posts.
-
The_Small_k
Actually in reality constructor is not called by your java code.It is called by the memory allocation code.So that is the reason why Constructor doesn't return any valu.Hope it clear now.sonali singhcan u plz tell me why constructor has no return type
Fell free to ask any question related to java. -
sookieAdditon to mohit's answer :
"Constructor" is called whenever a new object is getting created [rather in the creation process], whenever any method[let us ASSUME constructors also at this moment] has return type then it always return a reference to the constructed object but hold on constructors are already involved in the construction of the object so yet they don't have any complete object created to return the reference to hence it will be wrong to make a constructor with "return type"
Most welcome to correct me wrong ! π -
The_Small_k@sookie you want to say that "new A()" is used to creating object ?
I think this statement is used to initialization.
Correct me if i am wrong !! -
spiky@Sonali
A constructor has a return value , returned by the complier which is the reference id of the same class. Since by defualt it returns this value so we are not allowed to specify the return type.
If you have gone through some of the books they mention that it has a return type which is implicit class type itself π
the default value taken by a constructor is:
constructor_name( this )
where 'this' is the reference id of the same class.
any dispute in my answer please let me know π -
spikyA question??
Is Constructor static or non-static member function ?? -
eternalthinkerI have a simple doubt about local variables in Java. This can be quite intuitive for many others, it's just that I never took my time to get deep into Java!
Suppose we pass an array to a method, and it returns an array. The method will have to create a new array inside for some processing, and return it.
myArray = changeArrays(myArray); public String[] changeArrays(String[] arr) { String[] tarr = new String[arr.length + 1]; // Some processing return tarr; }
Here by the time the function returns, tarr no more exists and myArray becomes null.
Do you have any suggestions to deal with such situations?
Is it necessary that I have to create tarr outside the method every time? -
sookie
Nope, only "new" operator is used to create the object. After the object gets created , a call is made to the constructor for initialization.The_Small_k@sookie you want to say that "new A()" is used to creating object ?
I think this statement is used to initialization.
Correct me if i am wrong !!
@spiky
1. So the conclusion is "constructors" don't have return types but they have a return value instead and it is the reference id of the same class? Correct me if wrong !
2. There is no such thing as "static constructors" . Constructor is non-static member function. You need to have an instance to access them and initialize the variables of that particular instance.
@eternalthinker : How come "tarr" no more exist. Explain the problem in deep. π -
spiky@sookie
1) yes sir it is so....π
2)if constructors are non-static then how can main function which is static make a call to it.
during object creation we take help of constructor because it just tells or uniquely identifies of which class the varaibles have to be initialised.
and constructor is never called by any instance
as for eg:
new ClassA();
this wud create an anonymous object of the ClassA but we havent held its reference so it wont be further used.
you can also give a call to constructor of super class by using:
super();
again you did not use any object.
infact through subclass you can initialise your super class as well and that too without using "new".
hence sir constructors are static member function with a special power which i would discuss only when this point of mine is clear to all π -
spiky@eternalthinker:
why do you say that tarr[] will not exist..
according to me it should exist..
please can you please provide some more details regarding your query. -
eternalthinker@sookie, @spiky
I said so because tarr[] is created within the method, and so is local in scope. You can imagine the aim of the function to be something simple like adding a string to arr. -
sookie@spiky Hey , no need of calling me any "Sir". Can we start this discussion in separate thread ?
I am confused, you asked the question yourself and then making it clear to whom?
You are reading an archived discussion.
Related Posts
Hi friends,
I am here to share our Ideas related to computer field, movies, pictures etc.
Thank you to all
If you would like to know about the new movie reviews than click to signature
This is quite a simple game, I will start off by posting a word and then the next post will be another word and another word. Forming sentences and then...
Name: fake_lover01
*Engineering Trade: electronics & telecomm
Location:india
*Occupation: (Student- final year)
Work Experience:
*Hobbies & Interests: net surfing, computer games, electronics project
*Aim in life: ( To get selected...
hi CE's. i am a mechanical engineering student. for our mini project we are trying to do project on recharging the battery of electric vehicle while it s in motion....